@heybox/hb-sdk 0.9.9-alpha.1 → 0.9.9-alpha.11
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 +38 -0
- package/dist/cli-chunks/{build-vZ5iT2JO.cjs → build-D_2l0CIV.cjs} +4 -4
- package/dist/cli-chunks/{create-DJseFABS.cjs → create-0QH1Tn92.cjs} +1 -1
- package/dist/cli-chunks/{dev-CsuAVpLX.cjs → dev-CS5VPiB1.cjs} +907 -703
- package/dist/cli-chunks/{doctor-BYzYg-oP.cjs → doctor-B33mYzm-.cjs} +1 -1
- package/dist/cli-chunks/{game-binding-guide-BfKQ4e83.cjs → game-binding-guide-DMDuw1Pj.cjs} +2 -2
- package/dist/cli-chunks/{game-bindings-DWOIBCax.cjs → game-bindings-CQWdvXfM.cjs} +3 -3
- package/dist/cli-chunks/{games-DmPaqaDd.cjs → games-deIaD0qu.cjs} +1 -1
- package/dist/cli-chunks/{index-DPEhBPfc.cjs → index-C91c2NGN.cjs} +1 -1
- package/dist/cli-chunks/{index-D5rcGk_z.cjs → index-DpfxAeSH.cjs} +58 -20
- package/dist/cli-chunks/{index.esm-DYWovNyE.cjs → index.esm-B2WXn2A4.cjs} +9 -9
- package/dist/cli-chunks/{login-o1LQxi8P.cjs → login-D7XGHQFo.cjs} +1 -1
- package/dist/cli-chunks/{project-vite-CGIy1XaL.cjs → project-vite-B7sylnO7.cjs} +1 -1
- package/dist/cli-chunks/{remote-BQ3O-aiB.cjs → remote-Crnu4l7X.cjs} +968 -846
- package/dist/cli-chunks/{runtime-permission-env-soFtqTxP.cjs → runtime-permission-env-Cj9STUWz.cjs} +3 -2
- package/dist/cli-chunks/{skill-BHighcnl.cjs → skill-BDswKf84.cjs} +2 -2
- package/dist/cli-chunks/{version-CAh_EBAH.cjs → version-Dl0HQVTu.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-Be8jnz2C.js +224 -0
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-z3rWAJJc.js +6 -0
- package/dist/devtools/browser-dev-host/assets/index-CvUCSIVI.js +574 -0
- package/dist/devtools/browser-dev-host/assets/index-DQgWBZbX.css +1 -0
- package/dist/devtools/browser-dev-host/index.html +3 -3
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/vite.cjs.js +16 -8
- package/dist/vite.esm.js +16 -8
- package/package.json +4 -4
- package/skill/SKILL.md +7 -0
- package/skill/skill.json +5 -5
- package/types/vite/index.d.ts +2 -0
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-D9CVFRHE.js +0 -224
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-FZ3iQQs-.js +0 -13
- package/dist/devtools/browser-dev-host/assets/index-CVzVitcL.js +0 -567
- package/dist/devtools/browser-dev-host/assets/index-D0XGMYIr.css +0 -1
|
@@ -1,224 +0,0 @@
|
|
|
1
|
-
import{m as Ym,H as ou,b0 as Qm,bC as qm,a5 as Wm,bj as $m,bk as Km,n as Dt,bM as Z,bc as Ll,l as Pl,aO as Zm,e as au,aT as Xm,aF as Jm,k as e0,ar as $n,aP as t0,bG as An,a_ as Kn,aZ as Ia,a$ as Gi,b4 as vl,b6 as r0,f as as,w as n0,$ as gc,aS as i0,j as ba,av as ya,h as s0,bg as kl,aK as o0,o as cu,I as a0,b2 as xl,X as c0,A as u0,aH as d0,z as l0,bd as f0,bE as Ul,bD as Bl,b8 as h0,g as Na,aJ as m0,b as Ar,c as E0}from"./desktop-app-launch-FZ3iQQs-.js";function g0(){return{targetId:"ui-preview-target",ownerId:"ui-preview-owner",adapterId:"browser-dev-host",kind:"browser",capabilities:{storage:!0,presentation:!0,sandboxList:!0,sandboxRead:!0},state:"attached",currentInstanceId:"ui-preview-instance",cdpTargetId:"ui-preview-browser-target",metadata:{displayName:"UI 预览(模拟)",browser:"Chrome",os:"macOS"},updatedAt:Date.now(),stale:!1}}function p0(){return[{key:"network",label:"网络请求",state:"approved",facts:{platformApproval:!0,temporary:!1,effective:!0,online:"enabled"}},{key:"companion",label:"桌面辅助应用",state:"temporary",facts:{platformApproval:!1,temporary:!0,effective:!0,online:"disabled"},releaseDifference:"发布前需要获得平台批准。"},{key:"network.useOfficialDomain",label:"官方域名",state:"unavailable",facts:{platformApproval:!1,temporary:!1,effective:!1,online:"disabled"},reason:"不支持本地临时授权,获得平台批准后才能使用。"}]}const Di={device:'[data-preview-target="device"]',screen:'[data-preview-target="screen"]',app:"#device iframe",workbench:'[data-testid="workbench-root"]'},uu=15e3,T0=32*1024*1024,du="data-hb-preview-capture-device",jo="data-hb-preview-capture-ancestor",lu="data-hb-preview-capture-surface",fu=64,_0=1024;function A0(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??uu;if(!Number.isFinite(n)||n<=0||n>uu)throw nt("INVALID_CAPTURE_LEASE","截图租约无效");let i;function s(d,l,f){d.attributes.push({element:l,name:f,previous:l.getAttribute(f)}),l.setAttribute(f,d.token)}function o(d){const l=i;if(!l||l.token!==d)return!1;const f=c(l),h=!!l.style?.isConnected;i=void 0,clearTimeout(l.timer),l.removeAbort?.(),l.removeResize?.(),l.observer?.disconnect(),l.style?.remove(),l.bounds?.remove();for(const{element:_,name:g,previous:b}of l.attributes)_.getAttribute(g)===d&&(b===null?_.removeAttribute(g):_.setAttribute(g,b));return l.overlay.remove(),h&&(r.scrollX!==l.scroll.x||r.scrollY!==l.scroll.y)&&r.scrollTo(l.scroll.x,l.scroll.y),f}function c(d){const{viewport:l,target:f,rect:h}=d;if(!f?.isConnected||!h||Date.now()>=d.expiresAt||r.innerWidth!==l.width||r.innerHeight!==l.height||r.devicePixelRatio!==l.devicePixelRatio)return!1;const _=f.getBoundingClientRect();return["left","top","width","height"].every(g=>Math.abs(_[g]-h[g])<.01)}async function u(d,l){if(l?.throwIfAborted(),!Number.isFinite(d.deadlineAt)||Date.now()>=d.deadlineAt)throw nt("PREVIEW_TIMEOUT","截图操作已超时");if(d.scope==="workbench"||!Object.hasOwn(Di,d.scope))throw nt("INVALID_CAPTURE_SCOPE","设备像素截图仅支持 device、screen 或 app");if(!d.operationId||d.operationId.length>128)throw nt("INVALID_OPERATION","截图操作标识无效");if(!d.previewImage.startsWith("data:image/png;base64,")||d.previewImage.length>T0)throw nt("INVALID_CAPTURE_IMAGE","共享窗口冻结图无效或过大");if(i)throw nt("PREVIEW_BUSY","已有设备截图正在执行");const f=t.querySelectorAll(Di.device);if(f.length!==1)throw nt("DEVICE_NOT_UNIQUE","设备画面不唯一或尚未创建");const h=f[0],_=d.scope==="device"?h:t.querySelector(Di[d.scope]);if(!_||_!==h&&!h.contains(_))throw nt("CAPTURE_TARGET_UNAVAILABLE","截图内容尚未创建");const g=h.getBoundingClientRect();if(!(g.width>0&&g.height>0))throw nt("CAPTURE_TARGET_UNAVAILABLE","设备画面当前不可见");const b=t.createElement("img");b.alt="",b.setAttribute("aria-hidden","true"),b.setAttribute("data-hb-preview-capture-freeze",""),b.style.cssText=`position:fixed;left:0;top:0;width:${r.innerWidth}px;height:${r.innerHeight}px;max-width:none;max-height:none;margin:0;border:0;padding:0;z-index:2147483647;pointer-events:auto;user-select:none;`,b.addEventListener("wheel",Q=>Q.preventDefault(),{passive:!1}),b.addEventListener("touchmove",Q=>Q.preventDefault(),{passive:!1});const N=Math.min(Date.now()+n,d.deadlineAt),y={operationId:d.operationId,token:r.crypto.randomUUID(),overlay:b,attributes:[],scroll:{x:r.scrollX,y:r.scrollY},viewport:{width:r.innerWidth,height:r.innerHeight,devicePixelRatio:r.devicePixelRatio},expiresAt:N};i=y,y.timer=setTimeout(()=>o(y.token),Math.max(0,N-Date.now()));const L=()=>o(y.token);l?.addEventListener("abort",L,{once:!0}),y.removeAbort=()=>l?.removeEventListener("abort",L);const A=()=>{const{viewport:Q}=y;(r.innerWidth!==Q.width||r.innerHeight!==Q.height||r.devicePixelRatio!==Q.devicePixelRatio)&&o(y.token)};r.addEventListener("resize",A),y.removeResize=()=>r.removeEventListener("resize",A);const U=()=>{if(l?.throwIfAborted(),i!==y||Date.now()>=N)throw nt("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{b.src=d.previewImage,await b.decode(),U();const Q=y.token,C=`[${du}="${Q}"]`,P=r.getComputedStyle(h),M=new r.DOMMatrixReadOnly(P.transform==="none"?void 0:P.transform),V=Math.atan2(M.b,M.a),z=h.querySelector(".desktop-window__surface"),te=z?z.offsetWidth:Number.parseFloat(P.width),x=z?z.offsetHeight:Number.parseFloat(P.height),Y=P.backgroundColor,j=r.getComputedStyle(t.body).backgroundColor,H=ye=>!ye||ye==="transparent"||ye==="rgba(0, 0, 0, 0)",F=H(Y)?H(j)?"#fff":j:Y;if(!(te>0&&x>0))throw nt("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");U(),t.body.append(b),s(y,h,du),z&&s(y,z,lu);for(let ye=h.parentElement;ye;ye=ye.parentElement)s(y,ye,jo);const v=t.createElement("style");y.style=v;const R=`
|
|
2
|
-
[${jo}="${Q}"] {overflow:visible!important;scrollbar-width:none!important;}
|
|
3
|
-
[${jo}="${Q}"]::-webkit-scrollbar {display:none!important;}
|
|
4
|
-
[${lu}="${Q}"] {transform:none!important;transition:none!important;}
|
|
5
|
-
`,q=(ye,xe,ve=0,Fe=0)=>`${C} {position:absolute!important;left:${ye}px!important;top:${xe}px!important;width:${te}px!important;height:${x}px!important;transform:translate(${ve}px,${Fe}px) rotate(${V}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${F}!important;}`;v.textContent=R+q(0,0),U(),t.head.append(v);const D=h.getBoundingClientRect(),W=t.querySelector(Di.app),$=W&&h.contains(W)?W.getBoundingClientRect():void 0,m=$&&$.width>0&&$.height>0?$:void 0,w=m?Math.floor(r.innerWidth-1-(m.left-D.left)):r.innerWidth+64,B=m?Math.floor(r.innerHeight-1-(m.top-D.top)):32,K=w-D.left,ce=B-D.top;U(),v.textContent=R+q(K,ce);const pe=h.getBoundingClientRect();v.textContent=R+q(K,ce,w-pe.left,B-pe.top),U();const ue=_.getBoundingClientRect(),Te=Math.floor(xr(ue.left+r.scrollX)),we=Math.floor(xr(ue.top+r.scrollY)),Ae={x:Te,y:we,width:Math.ceil(xr(ue.right+r.scrollX))-Te,height:Math.ceil(xr(ue.bottom+r.scrollY))-we};if(!(Ae.width>0&&Ae.height>0)||Ae.x<0||Ae.y<0)throw nt("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(m&&W){const ye=W.getBoundingClientRect();if(!(ye.left<r.innerWidth&&ye.top<r.innerHeight&&ye.right>0&&ye.bottom>0))throw nt("CAPTURE_LAYOUT_INVALID","无法保持 iframe 的最小绘制区域");const xe=h.getBoundingClientRect(),ve=Math.floor(xr(xe.left))-1,Fe=Math.floor(xr(xe.top))-1,Ge=r.innerWidth-ve,hr=r.innerHeight-Fe;if(ve<0||Fe<0||Ge<=0||hr<=0||Ge>fu||hr>fu||Ge*hr>_0)throw nt("CAPTURE_LAYOUT_INVALID","无法在有界角部保持完整设备绘制,请改用 --scale css");b.style.clipPath=`polygon(0 0,100% 0,100% ${Fe}px,${ve}px ${Fe}px,${ve}px 100%,0 100%)`,b.setAttribute("data-hb-preview-capture-corner",JSON.stringify({x:ve,y:Fe,width:Ge,height:hr}))}const Ie=t.createElement("div");if(Ie.setAttribute("aria-hidden","true"),Ie.style.cssText=`position:absolute;left:${Ae.x+Ae.width+2}px;top:${Ae.y+Ae.height+2}px;width:1px;height:1px;pointer-events:none;opacity:0;`,y.bounds=Ie,U(),t.body.append(Ie),y.target=_,y.rect=ue,await I0(r,l),U(),!c(y))throw nt("CAPTURE_LAYOUT_INVALID","截图准备期间布局发生变化,请重新截图");y.observer=new r.ResizeObserver(()=>{i===y&&!c(y)&&o(y.token)});for(const{element:ye}of y.attributes)y.observer.observe(ye);return{token:Q,clip:Ae,devicePixelRatio:r.devicePixelRatio,expiresAt:N}}catch(Q){throw o(y.token),Q}}return{prepare:u,restore:o,cancel:d=>i?.operationId!==d?!1:(o(i.token),!0),dispose:()=>{i&&o(i.token)}}}function I0(e,t){return new Promise((r,n)=>{let i=e.requestAnimationFrame(()=>{i=e.requestAnimationFrame(o)});const s=()=>{e.cancelAnimationFrame(i),t?.removeEventListener("abort",s),n(t?.reason)};function o(){t?.removeEventListener("abort",s),r()}t?.addEventListener("abort",s,{once:!0}),t?.aborted&&s()})}function nt(e,t){return Object.assign(new Error(t),{name:"PreviewError",code:e})}function xr(e){const t=Math.round(e);return Math.abs(e-t)<.001?t:e}const lo=["post.get","post.comments.list","post.watch"],Zn=["post.setLiked","post.setFavorited","post.comments.openEditor","post.comments.delete","post.comments.setLiked"],pc="user.games.getOverview",cs="user.data.query",Un="user.data.sync",us="user.data.file",Tc="user.dataPermission.request",_c="user.dataPermission.get",Ac="user.dataPermission.set",Ic="user.dataPermission.openSettings",bc="user.dataPermission.revokeSession",Hl=[pc,cs,Un,us,Tc,_c,Ac,Ic,bc],ds="workspaceCards.requestRefresh",ls="auth.getAccountState",fs="auth.login",hs="user.getFollowStatus",ms="user.requestFollowAuthor",b0="gameSaves.list",y0="gameSaves.sync",N0="gameSaves.getFile",w0="gameSaves.readParsedData",Es="user.getInfo",gs="user.revokeAuthorization",ps="user.getSteamGameList",Xn="user.showAppreciation",Ts="share.copyLink",_s="share.showShareMenu",As="share.screenshot",Is="share.screenshotLong",Cr="viewport.setDisplay",bs="viewport.getWindowInfo",ys="viewport.setNavigationBarStyle",Jn="storage.getStorage",ei="storage.setStorage",Ns="network.request",ws="network.download",Ds="network.upload",Ss="files.pickFiles",Os="files.pickDirectory",Ms="files.saveFile",ti="file.create",ri="file.remove",Cs="file.exists",ni="file.readText",Rs="file.writeText",ii="file.readBytes",Ls="file.writeBytes",si="file.stat",Ps="directory.create",oi="directory.remove",vs="directory.exists",ks="directory.list",ai="media.pick",xs="ui.showToast",Us="ui.showLoading",Bs="ui.hideLoading",Hs="device.vibrate",Fs="device.setClipboard",zs="device.executeProtocol",js="navigation.close",Vs="navigation.reload",Gs="navigation.openAppPage",Wt="cloud.leaderboard.submit",wt="cloud.leaderboard.getList",ar="cloud.leaderboard.getCurrentUserEntry",Rr="cloud.leaderboard.deleteCurrentUserEntry",Ut="cloud.leaderboard.getInfo",en="cloud.storage.getStorage",tn="cloud.storage.setStorage",rn="cloud.storage.removeItem",Lr="cloud.storage.getKeys",fo="companion.getInfo",ho="companion.getPreparationStatus",mo="companion.prepare",Eo="companion.cancelPreparation",go="companion.getActiveSession",po="companion.launch",To="companion.session.write",_o="companion.session.closeStdin",Ao="companion.session.terminate",Io="companion.session.ackOutput",bo="companion.openAttachment",yo="companion.showNotification",cr=[...lo.map(e=>({method:e,module:"post",capability:e,requirement:{kind:"all",permissions:["post"]},risk:"medium"})),...Zn.map(e=>({method:e,module:"post",capability:e,requirement:{kind:"all",permissions:["post"]},risk:"high"})),...[b0,y0,N0,w0].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),...Hl.map(e=>({method:e,module:"userGameData",capability:e,requirement:{kind:"all",permissions:["user_game_data"]},risk:"high"})),{method:ds,module:"workspaceCards",capability:ds,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:ls,module:"auth",capability:ls,requirement:{kind:"none"},risk:"low"},{method:fs,module:"auth",capability:fs,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:hs,module:"user",capability:hs,requirement:{kind:"none"},risk:"low"},{method:ms,module:"user",capability:ms,requirement:{kind:"none"},risk:"high"},{method:Es,module:"user",capability:Es,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:gs,module:"user",capability:gs,requirement:{kind:"none"},risk:"high"},{method:ps,module:"user",capability:ps,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:Xn,module:"user",capability:Xn,requirement:{kind:"none"},risk:"medium"},{method:Ts,module:"share",capability:Ts,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:_s,module:"share",capability:_s,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:As,module:"share",capability:As,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Is,module:"share",capability:Is,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:bs,module:"viewport",capability:bs,requirement:{kind:"none"},risk:"low"},{method:ys,module:"viewport",capability:ys,requirement:{kind:"none"},risk:"low"},{method:Cr,module:"viewport",capability:Cr,requirement:{kind:"none"},risk:"low"},{method:Jn,module:"storage",capability:Jn,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:ei,module:"storage",capability:ei,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Ns,module:"network",capability:Ns,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:ws,module:"network",capability:ws,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Ds,module:"network",capability:Ds,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Ss,module:"files",capability:Ss,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Os,module:"files",capability:Os,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ms,module:"files",capability:Ms,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ti,module:"file",capability:ti,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ri,module:"file",capability:ri,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Cs,module:"file",capability:Cs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ni,module:"file",capability:ni,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Rs,module:"file",capability:Rs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ii,module:"file",capability:ii,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ls,module:"file",capability:Ls,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:si,module:"file",capability:si,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ps,module:"directory",capability:Ps,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:oi,module:"directory",capability:oi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:vs,module:"directory",capability:vs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ks,module:"directory",capability:ks,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ai,module:"media",capability:ai,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:xs,module:"ui",capability:xs,requirement:{kind:"none"},risk:"low"},{method:Us,module:"ui",capability:Us,requirement:{kind:"none"},risk:"low"},{method:Bs,module:"ui",capability:Bs,requirement:{kind:"none"},risk:"low"},{method:Hs,module:"device",capability:Hs,requirement:{kind:"none"},risk:"low"},{method:Fs,module:"device",capability:Fs,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:zs,module:"device",capability:zs,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:js,module:"navigation",capability:js,requirement:{kind:"none"},risk:"medium"},{method:Vs,module:"navigation",capability:Vs,requirement:{kind:"none"},risk:"medium"},{method:Gs,module:"navigation",capability:Gs,requirement:{kind:"none"},risk:"medium"},{method:Wt,module:"cloud",capability:Wt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:wt,module:"cloud",capability:wt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:ar,module:"cloud",capability:ar,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Rr,module:"cloud",capability:Rr,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ut,module:"cloud",capability:Ut,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:en,module:"cloud",capability:en,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:tn,module:"cloud",capability:tn,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:rn,module:"cloud",capability:rn,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Lr,module:"cloud",capability:Lr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[fo,ho,mo,Eo,go,po,To,_o,Ao,Io,bo,yo].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],gr="heybox:miniprogram",Fl=2,zl="hb_mini_bridge_nonce",jl="sdk.handshake",Si="runtime.location.probe",D0="sdk.location.report",S0="sdk.csp.violation",Vl="operation.progress",O0="companion.session.output",M0="companion.session.exit",C0="companion.session.ownershipLost";function R0(e){return!bt(e)||e.namespace!==gr||e.version!==1&&e.version!==2||!Ve(e.nonce)?!1:e.type==="handshake"?Ve(e.id)&&e.method===jl&&e.error===void 0&&H0(e.payload):e.type==="request"?Ve(e.id)&&Ve(e.method)&&e.error===void 0:e.type==="response"?Ve(e.id)&&(e.method===void 0||Ve(e.method))&&(e.error===void 0||F0(e.error)):e.type==="event"?!Ve(e.method)||e.error!==void 0?!1:e.method===Vl?e.version===2&&Ve(e.id)&&B0(e.payload):e.id===void 0||Ve(e.id):e.type==="cancel"?e.version===2&&Ve(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function yc(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function Gl(e){return bt(e)?e.kind==="sandbox"?gt(e,["kind"]):e.kind==="directory"&&Ve(e.handleId)&>(e,["kind","handleId"]):!1}function Dr(e){return!bt(e)||e.kind!=="file"?!1:Ve(e.handleId)?gt(e,["kind","handleId"]):Gl(e.root)&&yc(e.relativePath)&>(e,["kind","root","relativePath"])}function Yl(e){return!bt(e)||e.kind!=="directory"?!1:Ve(e.handleId)?gt(e,["kind","handleId"]):Gl(e.root)&&(e.relativePath==="."||yc(e.relativePath))&>(e,["kind","root","relativePath"])}function L0(e){return bt(e)&&e.kind==="file"&&Ve(e.name)&&z0(e.mode)&&Dr(e.ref)&>(e,["kind","name","mode","ref"])}const Ql=20,hu=["type","mimeType","size","width","height","previewUrl","file"];function P0(e){return e===void 0?!0:!(!bt(e)||!gt(e,["source","mediaType","maxCount"])||e.source!==void 0&&e.source!=="album"&&e.source!=="camera"||e.mediaType!==void 0&&e.mediaType!=="image"&&e.mediaType!=="video"&&e.mediaType!=="all"||e.maxCount!==void 0&&(!j0(e.maxCount,1,Ql)||e.source==="camera"&&e.maxCount!==1))}function ql(e){if(!bt(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!gt(e,t?[...hu,"durationMs"]:hu)||!Ve(e.mimeType)||!nr(e.size)||!mu(e.width)||!mu(e.height)||!Ve(e.previewUrl)||!k0(e.file)?!1:t?nr(e.durationMs):!0}function v0(e){if(!Array.isArray(e)||e.length<1||e.length>Ql)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!ql(e[t]))return!1;return!0}function k0(e){return!L0(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&Ve(e.ref.handleId)}function Wl(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function x0(e){return!bt(e)||!nr(e.loaded)||typeof e.lengthComputable!="boolean"||!gt(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?nr(e.total)&&e.loaded<=e.total:e.total===void 0}function U0(e){return bt(e)?e.phase==="downloading"?nr(e.loaded)&&(e.total===void 0||nr(e.total)&&e.loaded<=e.total)&>(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:nr(e.processed)&&nr(e.total)&&e.processed<=e.total&>(e,["phase","processed","total"]):!1}function B0(e){return x0(e)||U0(e)||bt(e)&>(e,["watching"])&&e.watching===!0}function H0(e){return bt(e)&&Ve(e.href)&&typeof e.userAgent=="string"&&Ve(e.sdkVersion)}function F0(e){return bt(e)&&Ve(e.code)&&typeof e.message=="string"}function z0(e){return e==="read"||e==="readwrite"}function nr(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function mu(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function j0(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function Ve(e){return typeof e=="string"&&e.length>0}function gt(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const $l={ark:"明日方舟",black_myth_wukong:"黑神话悟空",task_bar_hero:"任务栏英雄",phantom_blade_zero:"影之刃零"},Kl=Object.keys($l),Sr=[{key:"game.ark.profile",game:"ark",family:"profile",name:"明日方舟角色与养成资料",disclosureRevision:1,queries:{get:{schema:"ark.profile",version:1}},sync:!1,file:!1},{key:"game.ark.gacha",game:"ark",family:"gacha",name:"明日方舟抽卡记录与分析",disclosureRevision:1,queries:{get:{schema:"ark.gacha-analysis",version:1},list:{schema:"ark.gacha-record-page",version:1,page:{defaultSize:50,maxSize:100}}},sync:!1,file:!1},{key:"game.black_myth_wukong.save_analysis",game:"black_myth_wukong",family:"save_analysis",name:"黑神话悟空存档解析结果",disclosureRevision:1,queries:{get:{schema:"black_myth_wukong.save",version:1}},sync:!0,file:!1},{key:"game.black_myth_wukong.save_files",game:"black_myth_wukong",family:"save_files",name:"黑神话悟空云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.task_bar_hero.save_analysis",game:"task_bar_hero",family:"save_analysis",name:"任务栏英雄存档解析结果",disclosureRevision:1,queries:{get:{schema:"task_bar_hero.save",version:1}},sync:!0,file:!1},{key:"game.task_bar_hero.save_files",game:"task_bar_hero",family:"save_files",name:"任务栏英雄云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.phantom_blade_zero.save_analysis",game:"phantom_blade_zero",family:"save_analysis",name:"影之刃零存档解析结果",disclosureRevision:1,queries:{get:{schema:"phantom_blade_zero.save",version:1}},sync:!0,file:!1},{key:"game.phantom_blade_zero.save_files",game:"phantom_blade_zero",family:"save_files",name:"影之刃零云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0}],Ir=Sr.map(e=>e.key),V0=new Set(Ir),G0=new Set(Kl);function tr(e){return V0.has(e)}function Eu(e){return G0.has(e)}function Nc(e){const t=Sr.find(i=>i.key===e);if(!t)return;const r=t.queries,n=Object.keys(r);return t.sync&&n.push("sync"),t.file&&n.push("file"),{key:t.key,game:t.game,name:t.name,family:t.family,disclosureRevision:t.disclosureRevision,queries:r,operations:n}}const Y0="同步时,原始存档将上传至小黑盒;向小程序提供原始文件仍需单独许可。",Pr=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards","user_game_data","post"],wc=[{key:"gameSaves",name:"游戏存档",description:"已废弃,将在 SDK 0.10.0 移除;新接入使用 user.games。",access:"declaration",risk:"high",config:{},methods:["gameSaves.list","gameSaves.sync","gameSaves.getFile","gameSaves.readParsedData"],conditions:["SDK < 0.10.0-0 保留兼容入口,保留原合同,不增加本版逐资源确认;需要有效 Steam 登录和宿主支持。"]},{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","share.screenshotLong"],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:"media",name:"媒体",description:"通过系统图库或相机选择图片、视频。",access:"declaration",risk:"high",config:{},methods:["media.pick"],conditions:["图库授权范围仅限本次用户选择的媒体,不包含任意文件或沙盒访问权;继续执行可信手势、Host 能力与会话资源规则。"]},{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 支持与有效执行租约;不隐式授予网络或存储权限。"]},{key:"user_game_data",name:"游戏资料",description:"在精确资源声明范围内读取当前用户的游戏资料:明日方舟角色/养成与抽卡,以及黑神话悟空、任务栏英雄、影之刃零的云存档解析结果与文件。",access:"declaration",risk:"high",config:{resources:{type:"resource-map",required:!0,items:Ir,description:"精确资源声明对象;每项必须填写 1~30 个 Unicode 码点的 purpose,不接受通配符或未开放资源。"}},methods:Hl,conditions:["逐项声明资源与用途,读取前需用户许可;未取得许可不查询个人来源。","文件与解析结果分别许可;本次许可仅当前实例有效,持久许可保存在本机。","同步会将原存档上传至小黑盒,向小程序交付原文件仍需 `save_files` 许可。","平台取数不授予小程序 `network` 权限;已交付的数据副本无法撤回。"]},{key:"post",name:"关联帖子",description:"读取关联帖子与评论,或以当前用户身份互动并打开社区原生编辑器。",access:"declaration",risk:"high",config:{read:{type:"boolean",required:!1,default:!1,description:"读取帖子、评论和订阅变化。"},write:{type:"boolean",required:!1,default:!1,description:"点赞、收藏、删除评论及打开社区原生编辑器。"}},methods:[...lo,...Zn],conditions:["显式声明 read / write,省略时为 false;写操作须由用户明确触发,继续执行社区审核和权限校验。"]}];new Set(Pr);const Q0=30;function q0(e){if(typeof e!="string")throw new Error("purpose 必须是字符串");const t=e.trim(),r=Array.from(t);if(r.length<1||r.length>Q0)throw new Error("purpose 去除首尾空白后必须为 1~30 个 Unicode 码点");if(r.some(n=>{const i=n.codePointAt(0);return i>=55296&&i<=57343}))throw new Error("purpose 包含非法 Unicode 字符");return t}function ci(e){return Zl(e,!1)}function W0(e){return Zl(e,!0)}function Zl(e,t){if(!gu(e))throw new Error("resources 必须是资源声明对象;每项资源必须填写 purpose");const r={};for(const n of Object.keys(e).sort()){const i=e[n];if(!gu(i)||Object.keys(i).length!==1||!Object.prototype.hasOwnProperty.call(i,"purpose"))throw new Error(`resources.${n} 必须且只能包含 purpose`);let s;try{s=q0(i.purpose)}catch(o){throw new Error(`resources.${n}: ${o.message}`)}if(!tr(n)){if(t&&/^game\.[a-z0-9_]+\.[a-z0-9_.]+$/.test(n))continue;throw new Error(`resources 包含未开放资源:${n}`)}r[n]={purpose:s}}return r}function $0(e){return Ir.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function gu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xl(e,t,r,n){return JSON.stringify(["user-game-data-purpose-v1",e,t,r,n])}const K0=new Set(Pr);function Z0(e){return K0.has(e)}function ot(e){if(!Ur(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(!Ur(n)||typeof n.key!="string"||!n.key.trim())return{valid:!1,permissions:{}};const i=n.key.trim(),s=i==="network.request"?"network":i;if(t.has(s)||n.status!=="enabled"&&n.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(s),!!Z0(s)){if(s==="network"){const o=n.config;if(!Ur(o)||typeof o.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{useOfficialDomain:o.useOfficialDomain}};continue}if(s==="post"){const o=n.config;if(!Ur(o)||typeof o.read!="boolean"||typeof o.write!="boolean")return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{read:o.read,write:o.write}};continue}if(s==="user_game_data"){const o=n.config;if(!Ur(o))return{valid:!1,permissions:{}};try{const c=W0(o.resources);r[s]={key:s,status:n.status,config:{resources:c}}}catch{return{valid:!1,permissions:{}}}continue}if(n.config!==null&&n.config!==void 0&&(!Ur(n.config)||Object.keys(n.config).length>0))return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{}}}}return{valid:!0,permissions:r}}function Ur(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Yi=["network","companion","appProtocol"];function Jl(e){if(!In(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>Yi.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!In(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(!In(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(!In(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!In(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>Yi.indexOf(n.key)-Yi.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function X0(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=ot(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of Yi)!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 Dc(e){const t=ot(e.runtimePermissions),r=Jl(e.localDevGrant),n=t.valid?t.permissions:{};for(const o of Pr)e.declaredPermissions[o]?.enabled!==!0?delete n[o]:wc.some(c=>c.key===o&&c.access==="declaration")?n[o]={key:o,status:"enabled",config:J0(o,e.declaredPermissions)}:o==="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 o of r.grant.entries)e.declaredPermissions[o.key]?.enabled!==!0||n[o.key]?.status==="enabled"||(n[o.key]=o,i.push(o.key));const s=ef(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,...s===void 0?{}:{revision:s},entries:Pr.flatMap(o=>n[o]?[n[o]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function J0(e,t){const r=wc.find(i=>i.key===e);if(!r)return{};const n={};for(const[i,s]of Object.entries(r.config)){if(e==="post"&&s.type==="boolean"){n[i]=t.post?.[i]===!0;continue}s.type==="resource-map"&&(n[i]=i==="resources"?ci(t[e]?.resources):{})}return n}function ef(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function In(e,t){return ef(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const nn=["identity","profile","steam_account"],eE=/^[a-z][a-z0-9-]{0,31}$/,tf=["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"];var pu;function Pe(e,t,r){function n(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:o,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const d=o.prototype,l=Object.keys(d);for(let f=0;f<l.length;f++){const h=l[f];h in c||(c[h]=d[h].bind(c))}}const i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function o(c){var u;const d=r?.Parent?new s:this;n(d,c),(u=d._zod).deferred??(u.deferred=[]);for(const l of d._zod.deferred)l();return d}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}class Bn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(pu=globalThis).__zod_globalConfig??(pu.__zod_globalConfig={});const Tu=globalThis.__zod_globalConfig;function pn(e){return e&&Object.assign(Tu,e),Tu}function tE(e,t){return typeof t=="bigint"?t.toString():t}function rE(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function rf(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const _u=Symbol("evaluating");function ct(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==_u)return n===void 0&&(n=_u,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}const nf="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function nE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Au(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function iE(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function yt(e){return{}}function sE(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const oE={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ln(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function aE(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function sf(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Oi(e){return typeof e=="string"?e:e?.message}function gi(e,t,r){const n=e.message?e.message:Oi(e.inst?._zod.def?.error?.(e))??Oi(t?.error?.(e))??Oi(r.customError?.(e))??Oi(r.localeError?.(e))??"Invalid input",{inst:i,continue:s,input:o,...c}=e;return c.path??(c.path=[]),c.message=n,t?.reportInput&&(c.input=o),c}const of=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,tE,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},cE=Pe("$ZodError",of),No=Pe("$ZodError",of,{Parent:Error}),uE=e=>(t,r,n,i)=>{const s=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Bn;if(o.issues.length){const c=new(i?.Err??e)(o.issues.map(u=>gi(u,s,pn())));throw nf(c,i?.callee),c}return o.value},dE=uE(No),lE=e=>async(t,r,n,i)=>{const s=n?{...n,async:!0}:{async:!0};let o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new(i?.Err??e)(o.issues.map(u=>gi(u,s,pn())));throw nf(c,i?.callee),c}return o.value},fE=lE(No),hE=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Bn;return s.issues.length?{success:!1,error:new(e??cE)(s.issues.map(o=>gi(o,i,pn())))}:{success:!0,data:s.value}},af=hE(No),mE=e=>async(t,r,n)=>{const i=n?{...n,async:!0}:{async:!0};let s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(o=>gi(o,i,pn())))}:{success:!0,data:s.value}},cf=mE(No),EE=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},gE=/^-?\d+$/,pE=/^-?\d+(?:\.\d+)?$/,TE=/^null$/i,wo=Pe("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),uf={number:"number",bigint:"bigint",object:"date"},_E=Pe("$ZodCheckLessThan",(e,t)=>{wo.init(e,t);const r=uf[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),AE=Pe("$ZodCheckGreaterThan",(e,t)=>{wo.init(e,t);const r=uf[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),IE=Pe("$ZodCheckNumberFormat",(e,t)=>{wo.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=oE[t.format];e._zod.onattach.push(o=>{const c=o._zod.bag;c.format=t.format,c.minimum=i,c.maximum=s,r&&(c.pattern=gE)}),e._zod.check=o=>{const c=o.value;if(r){if(!Number.isInteger(c)){o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}c<i&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),c>s&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),bE=Pe("$ZodCheckStringFormat",(e,t)=>{var r,n;wo.init(e,t),e._zod.onattach.push(i=>{const s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),yE=Pe("$ZodCheckRegex",(e,t)=>{bE.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),NE={major:4,minor:4,patch:3},Ot=Pe("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=NE;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const i of n)for(const s of i._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(o,c,u)=>{let d=Ln(o),l;for(const f of c){if(f._zod.def.when){if(aE(o)||!f._zod.def.when(o))continue}else if(d)continue;const h=o.issues.length,_=f._zod.check(o);if(_ instanceof Promise&&u?.async===!1)throw new Bn;if(l||_ instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await _,o.issues.length!==h&&(d||(d=Ln(o,h)))});else{if(o.issues.length===h)continue;d||(d=Ln(o,h))}}return l?l.then(()=>o):o},s=(o,c,u)=>{if(Ln(o))return o.aborted=!0,o;const d=i(c,n,u);if(d instanceof Promise){if(u.async===!1)throw new Bn;return d.then(l=>e._zod.parse(l,u))}return e._zod.parse(d,u)};e._zod.run=(o,c)=>{if(c.skipChecks)return e._zod.parse(o,c);if(c.direction==="backward"){const d=e._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(l=>s(l,o,c)):s(d,o,c)}const u=e._zod.parse(o,c);if(u instanceof Promise){if(c.async===!1)throw new Bn;return u.then(d=>i(d,n,c))}return i(u,n,c)}}ct(e,"~standard",()=>({validate:i=>{try{const s=af(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return cf(e,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),wE=Pe("$ZodString",(e,t)=>{Ot.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??EE(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),df=Pe("$ZodNumber",(e,t)=>{Ot.init(e,t),e._zod.pattern=e._zod.bag.pattern??pE,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}}),DE=Pe("$ZodNumberFormat",(e,t)=>{IE.init(e,t),df.init(e,t)}),SE=Pe("$ZodNull",(e,t)=>{Ot.init(e,t),e._zod.pattern=TE,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),OE=Pe("$ZodNever",(e,t)=>{Ot.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Iu(e,t,r){e.issues.length&&t.issues.push(...sf(r,e.issues)),t.value[r]=e.value}const ME=Pe("$ZodArray",(e,t)=>{Ot.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const s=[];for(let o=0;o<i.length;o++){const c=i[o],u=t.element._zod.run({value:c,issues:[]},n);u instanceof Promise?s.push(u.then(d=>Iu(d,r,o))):Iu(u,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function Ys(e,t,r,n,i,s){const o=r in n;if(e.issues.length){if(i&&s&&!o)return;t.issues.push(...sf(r,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?o&&(t.value[r]=void 0):t.value[r]=e.value}function CE(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=sE(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function RE(e,t,r,n,i,s){const o=[],c=i.keySet,u=i.catchall._zod,d=u.def.type,l=u.optin==="optional",f=u.optout==="optional";for(const h in t){if(h==="__proto__"||c.has(h))continue;if(d==="never"){o.push(h);continue}const _=u.run({value:t[h],issues:[]},n);_ instanceof Promise?e.push(_.then(g=>Ys(g,r,h,t,l,f))):Ys(_,r,h,t,l,f)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}const LE=Pe("$ZodObject",(e,t)=>{if(Ot.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...c};return Object.defineProperty(t,"shape",{value:u}),u}})}const n=rE(()=>CE(t));ct(e._zod,"propValues",()=>{const c=t.shape,u={};for(const d in c){const l=c[d]._zod;if(l.values){u[d]??(u[d]=new Set);for(const f of l.values)u[d].add(f)}}return u});const i=nE,s=t.catchall;let o;e._zod.parse=(c,u)=>{o??(o=n.value);const d=c.value;if(!i(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const l=[],f=o.shape;for(const h of o.keys){const _=f[h],g=_._zod.optin==="optional",b=_._zod.optout==="optional",N=_._zod.run({value:d[h],issues:[]},u);N instanceof Promise?l.push(N.then(y=>Ys(y,c,h,d,g,b))):Ys(N,c,h,d,g,b)}return s?RE(l,d,c,u,n.value,e):l.length?Promise.all(l).then(()=>c):c}});function bu(e,t,r,n){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const i=e.filter(s=>!Ln(s));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(o=>gi(o,n,pn())))}),t)}const PE=Pe("$ZodUnion",(e,t)=>{Ot.init(e,t),ct(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ct(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ct(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),ct(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>rf(i.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let s=!1;const o=[];for(const c of t.options){const u=c._zod.run({value:n.value,issues:[]},i);if(u instanceof Promise)o.push(u),s=!0;else{if(u.issues.length===0)return u;o.push(u)}}return s?Promise.all(o).then(c=>bu(c,n,e,i)):bu(o,n,e,i)}}),vE=Pe("$ZodLiteral",(e,t)=>{if(Ot.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Au(n):n?Au(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,i)=>{const s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}});function yu(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const kE=Pe("$ZodOptional",(e,t)=>{Ot.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ct(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ct(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${rf(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const i=r.value,s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>yu(o,i)):yu(s,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),xE=Pe("$ZodLazy",(e,t)=>{Ot.init(e,t),ct(e._zod,"innerType",()=>{const r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),ct(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),ct(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),ct(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),ct(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)});function UE(e,t){return new e({type:"string",...yt()})}function BE(e,t){return new e({type:"number",checks:[],...yt()})}function HE(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...yt()})}function FE(e,t){return new e({type:"null",...yt()})}function zE(e,t){return new e({type:"never",...yt()})}function he(e,t){return new _E({check:"less_than",...yt(),value:e,inclusive:!0})}function me(e,t){return new AE({check:"greater_than",...yt(),value:e,inclusive:!0})}function Ee(e,t){return new yE({check:"string_format",format:"regex",...yt(),pattern:e})}pn({jitless:!0});function lf(e){if(e.schema_version!==1||!/^[a-f0-9]{32}$/.test(e.session_id)||!Number.isSafeInteger(e.revision)||e.revision<1||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(e.sdk_version)||!e.declared_permissions||typeof e.declared_permissions!="object"||Array.isArray(e.declared_permissions)||!Array.isArray(e.platforms)||e.platforms.some(r=>!["android","ios","ohos","windows","macos","linux"].includes(r))||new Set(e.platforms).size!==e.platforms.length)throw new Error("开发快照无效");const t={};for(const r of Pr){const n=e.declared_permissions[r];if(n){if(typeof n.enabled!="boolean")throw new Error("开发权限声明无效");if(r==="network"){t[r]={enabled:n.enabled,useOfficialDomain:n.useOfficialDomain===!0};continue}if(r==="post"){for(const i of["read","write"])if(n[i]!==void 0&&typeof n[i]!="boolean")throw new Error("开发权限声明无效");t.post={enabled:n.enabled,read:n.read===!0,write:n.write===!0};continue}if(r==="user_game_data"){t[r]={enabled:n.enabled,resources:ci(n.resources)};continue}t[r]={enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!Pr.includes(r)))throw new Error("开发权限声明无效");if(e.companion_manifest_sha256!==void 0&&!/^[a-f0-9]{64}$/.test(e.companion_manifest_sha256))throw new Error("开发产物摘要无效");return JSON.stringify({schema_version:1,session_id:e.session_id,revision:e.revision,sdk_version:e.sdk_version,declared_permissions:t,platforms:[...e.platforms].sort(),...e.companion_manifest_sha256?{companion_manifest_sha256:e.companion_manifest_sha256}:{}})}function jE(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return lf(t)===e?t:void 0}catch{return}}const Vt=Pe("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ot.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>dE(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>af(e,r,n),e.parseAsync=async(r,n)=>fE(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>cf(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>iE(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),VE=Pe("ZodMiniString",(e,t)=>{wE.init(e,t),Vt.init(e,t)});function O(e){return UE(VE)}const ff=Pe("ZodMiniNumber",(e,t)=>{df.init(e,t),Vt.init(e,t)});function X(e){return BE(ff)}const GE=Pe("ZodMiniNumberFormat",(e,t)=>{DE.init(e,t),ff.init(e,t)});function ge(e){return HE(GE)}const YE=Pe("ZodMiniNull",(e,t)=>{SE.init(e,t),Vt.init(e,t)});function de(e){return FE(YE)}const QE=Pe("ZodMiniNever",(e,t)=>{OE.init(e,t),Vt.init(e,t)});function qE(e){return zE(QE)}const WE=Pe("ZodMiniArray",(e,t)=>{ME.init(e,t),Vt.init(e,t)});function ae(e,t){return new WE({type:"array",element:e,...yt()})}const $E=Pe("ZodMiniObject",(e,t)=>{LE.init(e,t),Vt.init(e,t),ct(e,"shape",()=>t.shape)});function fe(e,t){return new $E({type:"object",shape:e,catchall:qE(),...yt()})}const KE=Pe("ZodMiniUnion",(e,t)=>{PE.init(e,t),Vt.init(e,t)});function S(e,t){return new KE({type:"union",options:e,...yt()})}const ZE=Pe("ZodMiniLiteral",(e,t)=>{vE.init(e,t),Vt.init(e,t)});function _e(e,t){return new ZE({type:"literal",values:Array.isArray(e)?e:[e],...yt()})}const XE=Pe("ZodMiniOptional",(e,t)=>{kE.init(e,t),Vt.init(e,t)});function J(e){return new XE({type:"optional",innerType:e})}const JE=Pe("ZodMiniLazy",(e,t)=>{xE.init(e,t),Vt.init(e,t)});function ie(e){return new JE({type:"lazy",getter:e})}const se={ArkProfile:fe({uid:O(),name:O(),level:X(),avatar:J(ie(()=>se.ArkPlayerAvatar)),characterCount:X(),totalCharacterCount:X(),mainStageProgress:O(),rogueLevel:X(),campaignFullKillCount:X(),tag:O(),observedAt:J(S([O(),X()])),lastOnlineTs:J(S([O(),X()])),registerTs:J(S([O(),X()])),changeTime:J(S([O(),X()])),operators:J(ae(ie(()=>se.ArkOperator)))}),ArkPlayerAvatar:fe({url:O(),type:O(),id:O()}),ArkOperator:fe({characterId:O(),name:O(),profession:O(),evolvePhase:X(),potentialRank:X()}),ArkGachaAnalysis:fe({uid:O(),year:X(),total:X(),srCount:X(),upCount:X(),missCount:X(),careerEvaluation:O(),careerIsLucky:S([_e(!1),_e(!0)]),pools:ae(ie(()=>se.ArkGachaPoolStat)),records:ae(ie(()=>se.ArkGachaAnalysisRecord)),luckyLottery:ae(X())}),ArkGachaPoolStat:fe({poolId:O(),totalCost:X(),ssrCount:X(),ssrCost:X(),records:ae(ie(()=>se.ArkGachaAnalysisRecord))}),ArkGachaAnalysisRecord:fe({name:O(),timestamp:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),diff:X(),negativeDiff:X(),tag:O(),missUp:S([_e(!1),_e(!0)])}),GachaRecord:fe({id:O(),name:O(),pool:O(),rarity:X(),timestamp:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),BlackMythWukongSave:fe({level:J(X()),newGamePlusCount:J(X()),gameTotalTime:J(X()),playerDeathCount:J(X()),totalMoney:J(O()),meditationList:J(S([de(),ae(X())])),monsterCollectionList:J(S([de(),ae(X())])),returnPointList:J(S([de(),ae(X())])),activatedWeaponIdList:J(S([de(),ae(O())])),activatedEquipIdList:J(S([de(),ae(X())])),magicArtifactList:J(S([de(),ae(X())])),soulSkillIdList:J(S([de(),ae(X())])),huluIdLits:J(S([de(),ae(X())])),wineIdList:J(S([de(),ae(X())])),wineIdPartnerList:J(S([de(),ae(X())])),cropIdList:J(S([de(),ae(X())])),recipeIdList:J(S([de(),ae(X())])),wearedWaeponId:J(O()),wearedMagicArtifact:J(X()),wearedSoulSkill:J(X()),wearedHead:J(X()),wearedUpware:J(X()),wearedArm:J(X()),wearedFoot:J(X()),wearedHulu:J(X()),wearedAccessoryList:J(S([de(),ae(X())])),spellQishu:J(S([de(),ae(X())])),spellShenfa:J(S([de(),ae(X())])),spellHaomao:J(S([de(),ae(X())])),spellBianshen:J(S([de(),ae(X())])),bossRushBossgroup:J(ie(()=>se.BlackMythWukongBossRushData)),bossRushRefight:J(ie(()=>se.BlackMythWukongBossRefightData))}),BlackMythWukongBossRushData:fe({bossGroups:J(S([de(),ae(ie(()=>se.BlackMythWukongBossRushRecord))]))}),BlackMythWukongBossRushRecord:fe({bossGroupId:J(X()),isPassed:J(S([_e(!1),_e(!0)])),bestRecords:J(S([de(),ae(ie(()=>se.BlackMythWukongBattleRecord))])),encounterBossIndex:J(X()),battleCount:J(X())}),BlackMythWukongBattleRecord:fe({battleId:J(O()),battleData:J(ie(()=>se.BlackMythWukongBattleData))}),BlackMythWukongBattleData:fe({totalTime:J(X()),score:J(X()),debuffList:J(S([de(),ae(X())])),targetId:J(X()),archiveTime:J(O()),roleBase:J(ie(()=>se.BlackMythWukongRoleBase)),battleStyleInfo:J(ie(()=>se.BlackMythWukongBattleStyleInfo)),damageInfo:J(ie(()=>se.BlackMythWukongDamageInfo))}),BlackMythWukongRoleBase:fe({level:J(X()),atk:J(X()),hpMax:J(X()),staminaMax:J(X()),mpMax:J(X())}),BlackMythWukongBattleStyleInfo:fe({spellList:J(S([de(),ae(ie(()=>se.BlackMythWukongCast))])),fabaoInfo:J(ie(()=>se.BlackMythWukongCast)),soulInfo:J(ie(()=>se.BlackMythWukongCast)),itemCount:J(X()),wineCount:J(X()),rollCount:J(X()),defuseCount:J(X()),fourPeCount:J(X())}),BlackMythWukongCast:fe({castId:J(X()),castCount:J(X())}),BlackMythWukongDamageInfo:fe({totalDamage:J(S([O(),X()])),hightestDamage:J(S([O(),X()])),criticalDmgRate:J(X()),totalBeDamaged:J(S([O(),X()])),criticalDmgTotal:J(S([O(),X()])),elemDotDmgTotal:J(S([O(),X()])),elemDotDmgRate:J(X())}),BlackMythWukongBossRefightData:fe({bossList:J(S([de(),ae(ie(()=>se.BlackMythWukongBossRefightRecord))]))}),BlackMythWukongBossRefightRecord:fe({bossId:J(X()),passedMaxLevel:J(X()),lastChallengeLevel:J(X()),bestRecords:J(S([de(),ae(ie(()=>se.BlackMythWukongBattleRecord))])),refightStatisticsList:J(S([de(),ae(ie(()=>se.BlackMythWukongRefightStatistic))]))}),BlackMythWukongRefightStatistic:fe({challengeLevel:J(X()),battleCount:J(X())}),TaskBarHeroSave:fe({update_time:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),game_version:O(),account_version:O(),play_time:X(),last_saved_time:O(),common:ie(()=>se.TaskBarHeroCommon),summary:ie(()=>se.TaskBarHeroSummary),heroes:S([de(),ae(ie(()=>se.TaskBarHeroHero))]),rune_save_data:S([de(),ae(ie(()=>se.TaskBarHeroRune))]),pets:S([de(),ae(ie(()=>se.TaskBarHeroPet))]),attributes:S([de(),ae(ie(()=>se.TaskBarHeroAttribute))]),inventory_slots:S([de(),ae(ie(()=>se.TaskBarHeroItemSlot))]),stash_slots:S([de(),ae(ie(()=>se.TaskBarHeroItemSlot))]),item_instances:S([de(),ae(ie(()=>se.TaskBarHeroItemInstance))]),values:ie(()=>se.TaskBarHeroValueSummary)}),TaskBarHeroCommon:fe({max_completed_stage:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_wave:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),arranged_hero_keys:S([de(),ae(S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),arranged_pet_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroSummary:fe({max_hero_level:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),learned_rune_count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unlocked_hero:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total_hero:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inventory_slots:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stash_slots:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroHero:fe({hero_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),hero_level:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:S([_e(!1),_e(!0)]),hero_exp:X(),ability_point:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),allocated_hero_ability_point:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),equipped_item_ids:S([de(),ae(O())]),equipped_skill_keys:S([de(),ae(S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),unlocked_attribute_group_keys:S([de(),ae(S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]))])}),TaskBarHeroRune:fe({rune_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroPet:fe({pet_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:S([_e(!1),_e(!0)])}),TaskBarHeroAttribute:fe({key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroItemSlot:fe({index:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_unique_id:O(),is_unlock:S([_e(!1),_e(!0)]),is_unlocked_by_rune:S([_e(!1),_e(!0)])}),TaskBarHeroItemInstance:fe({item_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unique_id:O(),is_chaotic:S([_e(!1),_e(!0)]),is_blocked:S([_e(!1),_e(!0)]),is_server_pending_item:S([_e(!1),_e(!0)]),enchant_count:S([de(),ae(S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),enchant_data:S([de(),ae(ie(()=>se.TaskBarHeroEnchantData))]),item_get_source_type:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),decoration_applied_total_count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),engraving_applied_total_count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inscription_applied_total_count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroEnchantData:fe({stat_mod_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),tier:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),value:X(),recipe_type:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),mod_type:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),material_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stat_type:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroValueSummary:fe({market_value:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),price_state:O(),currency:O()}),PhantomBladeZeroSave:fe({defaultSlot:O(),slots:ae(ie(()=>se.PhantomBladeZeroSaveSlot))}),PhantomBladeZeroSaveSlot:fe({slot:O(),head:ie(()=>se.PhantomBladeZeroSlotHead),firstClear:ie(()=>se.PhantomBladeZeroSlotFirstClear),progress:ie(()=>se.PhantomBladeZeroSlotProgress),combat:ie(()=>se.PhantomBladeZeroSlotCombat),achievements:ie(()=>se.PhantomBladeZeroSlotAchievementSummary),bosses:ie(()=>se.PhantomBladeZeroSlotBossSummary),collectibles:ie(()=>se.PhantomBladeZeroSlotCollectibles),quest_details:S([de(),ie(()=>se.PhantomBladeZeroQuestDetails)]),inventory_details:S([de(),ae(ie(()=>se.PhantomBladeZeroInventoryItem))]),detail:ie(()=>se.PhantomBladeZeroSlotDetail)}),PhantomBladeZeroSlotHead:fe({saveTime:O(),currentLevel:O(),cycle:O(),difficulty:ie(()=>se.PhantomBladeZeroSlotDifficulty)}),PhantomBladeZeroSlotDifficulty:fe({raw:X(),name:O()}),PhantomBladeZeroSlotFirstClear:fe({clearDate:ie(()=>se.PhantomBladeZeroUnavailableValue),cycles:S([de(),ae(ie(()=>se.PhantomBladeZeroClearanceRecord))])}),PhantomBladeZeroUnavailableValue:fe({value:de(),reason:O()}),PhantomBladeZeroClearanceRecord:fe({Cycle:J(S([de(),X()])),Ending:X(),Difficulty:X(),GameTime:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),Completion:X(),DiedTimes:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotProgress:fe({playTimeSeconds:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),playTime:O(),lastLaunch:ie(()=>se.PhantomBladeZeroUnavailableValue),narrativePercentage:X(),chapter:O(),remainingDays:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCombat:fe({loadout:J(ie(()=>se.PhantomBladeZeroSlotLoadout)),totalDeaths:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),cycleDeaths:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bossKillTotal:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),currentMainWeapon:J(S([de(),ie(()=>se.PhantomBladeZeroNamedItem)])),mainWeapon:ie(()=>se.PhantomBladeZeroCollectionCount),currentShaqi:J(S([de(),ie(()=>se.PhantomBladeZeroNamedItem)])),shaqi:ie(()=>se.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroSlotLoadout:fe({states:J(S([de(),ae(ie(()=>se.PhantomBladeZeroLoadoutState))])),main_weapons:S([de(),ae(O())]),shaqi_weapons:S([de(),ae(O())]),accessory_ids:S([de(),ae(O())]),top_medicine:O(),bottom_medicine:O(),current_weapon_index:X(),current_shaqi_weapon_index:X()}),PhantomBladeZeroLoadoutState:fe({category:O(),id:O(),level:J(X()),soul_forged:J(S([_e(!1),_e(!0)])),reincarnation_count:J(X())}),PhantomBladeZeroNamedItem:fe({id:O(),name:O()}),PhantomBladeZeroCollectionCount:fe({unknown:J(S([O(),X()])),done:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotAchievementSummary:fe({unlocked:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:O()}),PhantomBladeZeroSlotBossSummary:fe({groups:S([de(),ae(ie(()=>se.PhantomBladeZeroBossGroup))])}),PhantomBladeZeroBossGroup:fe({map:O(),mapName:O(),count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bosses:S([de(),ae(ie(()=>se.PhantomBladeZeroBoss))])}),PhantomBladeZeroBoss:fe({id:O(),classPath:O(),map:O(),mapName:O(),encountered:S([_e(!1),_e(!0)]),killed:S([_e(!1),_e(!0)]),kill:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),records:S([de(),ae(ie(()=>se.PhantomBladeZeroBossRecord))])}),PhantomBladeZeroBossRecord:fe({cycle:O(),diff:O(),diffName:O(),kill:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCollectibles:fe({overall:ie(()=>se.PhantomBladeZeroCollectionSummary),craneBellCount:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),byBigMap:S([de(),ae(ie(()=>se.PhantomBladeZeroBigMapProgress))]),currentChapter:ie(()=>se.PhantomBladeZeroChapterProgress)}),PhantomBladeZeroCollectionSummary:fe({bell:ie(()=>se.PhantomBladeZeroCollectionCount),weapon:ie(()=>se.PhantomBladeZeroCollectionCount),shaqi:ie(()=>se.PhantomBladeZeroCollectionCount),accessory:ie(()=>se.PhantomBladeZeroCollectionCount),medicine:ie(()=>se.PhantomBladeZeroCollectionCount),challenge:ie(()=>se.PhantomBladeZeroCollectionCount),hupo:ie(()=>se.PhantomBladeZeroCollectionCount),heishi:ie(()=>se.PhantomBladeZeroCollectionCount),flower:ie(()=>se.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroBigMapProgress:fe({unknown:J(S([O(),X()])),mapID:O(),name:O(),pct:X(),done:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),subMaps:S([de(),ae(O())])}),PhantomBladeZeroChapterProgress:fe({unknown:J(S([O(),X()])),mapID:O(),pct:X(),done:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:O()}),PhantomBladeZeroQuestDetails:fe({CurrentMainQuestPath:O(),CurrentTutorialQuestPath:O(),TrackedQuestPath:O(),TrackedBranchID:O(),TrackedTaskPointID:O(),ManualTrackingOptOut:S([_e(!1),_e(!0)]),NarrativeSavedQuests:S([de(),ae(ie(()=>se.PhantomBladeZeroQuest))])}),PhantomBladeZeroQuest:fe({QuestClass:O(),QuestCompletion:O(),QuestBranches:S([de(),ae(ie(()=>se.PhantomBladeZeroQuestBranch))]),CompletedBranches:S([de(),ae(O())]),ReachedStateNames:S([de(),ae(O())])}),PhantomBladeZeroQuestBranch:fe({BranchID:O(),TasksProgress:S([de(),ae(S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),BranchType:O()}),PhantomBladeZeroInventoryItem:fe({id:O(),amount:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotDetail:fe({bell:S([de(),ae(ie(()=>se.PhantomBladeZeroBellDetail))]),weapon:S([de(),ae(ie(()=>se.PhantomBladeZeroItemDetail))]),shaqi:S([de(),ae(ie(()=>se.PhantomBladeZeroItemDetail))]),accessory:S([de(),ae(ie(()=>se.PhantomBladeZeroItemDetail))]),medicine:S([de(),ae(ie(()=>se.PhantomBladeZeroItemDetail))]),challenge:S([de(),ae(ie(()=>se.PhantomBladeZeroChallengeDetail))]),hupo:S([de(),ae(ie(()=>se.PhantomBladeZeroWorldItemDetail))]),heishi:S([de(),ae(ie(()=>se.PhantomBladeZeroWorldItemDetail))]),flower:S([de(),ae(ie(()=>se.PhantomBladeZeroItemDetail))]),achievements:S([de(),ae(ie(()=>se.PhantomBladeZeroAchievementDetail))])}),PhantomBladeZeroBellDetail:fe({unknown:J(S([_e(!1),_e(!0)])),id:O(),done:S([_e(!1),_e(!0)]),equip:S([_e(!1),_e(!0)])}),PhantomBladeZeroItemDetail:fe({level:J(X()),soul_forged:J(S([_e(!1),_e(!0)])),reincarnation_count:J(X()),unknown:J(S([_e(!1),_e(!0)])),id:O(),name:O(),done:S([_e(!1),_e(!0)]),equip:S([_e(!1),_e(!0)]),locs:S([de(),ae(ie(()=>se.PhantomBladeZeroLocation))])}),PhantomBladeZeroLocation:fe({map:O(),mapName:O(),x:X(),y:X(),z:X()}),PhantomBladeZeroChallengeDetail:fe({key:J(O()),unknown:J(S([_e(!1),_e(!0)])),index:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),guids:S([de(),ae(O())]),done:S([_e(!1),_e(!0)]),locs:S([de(),ae(ie(()=>se.PhantomBladeZeroLocation))])}),PhantomBladeZeroWorldItemDetail:fe({key:J(O()),unknown:J(S([_e(!1),_e(!0)])),id:O(),saveGuid:O(),mobDomain:O(),done:S([_e(!1),_e(!0)]),locs:S([de(),ae(ie(()=>se.PhantomBladeZeroLocation))])}),PhantomBladeZeroAchievementDetail:fe({id:O(),name:O(),desc:O(),grade:O(),hidden:S([_e(!1),_e(!0)]),done:S([_e(!1),_e(!0)])}),UserGameDataSaveFilePage:fe({items:ae(ie(()=>se.UserGameDataSaveInfo)),hasMore:_e(!1)}),UserGameDataSaveInfo:fe({saveId:O(),createdAt:O(),files:ae(ie(()=>se.UserGameDataSaveFileInfo))}),UserGameDataSaveFileInfo:fe({fileId:O(),name:O(),sizeBytes:X(),modifiedAt:O()})},eg=new Map([["ark.profile",ie(()=>se.ArkProfile)],["ark.gacha-analysis",ie(()=>se.ArkGachaAnalysis)],["ark.gacha-record-page",fe({items:ae(ie(()=>se.GachaRecord)),nextCursor:J(O()),hasMore:S([_e(!1),_e(!0)]),total:J(X())})],["black_myth_wukong.save",ie(()=>se.BlackMythWukongSave)],["task_bar_hero.save",ie(()=>se.TaskBarHeroSave)],["phantom_blade_zero.save",ie(()=>se.PhantomBladeZeroSave)],["save-file-page",ie(()=>se.UserGameDataSaveFilePage)]]);function tg(e,t){return eg.get(e)?.safeParse(t).success??!1}cr.map(e=>e.method);function Qi(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Oe(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:Qi()}function hf(e){if(e.source!=="runtime-private"||e.credentials!=="omit"||e.route!=="game-save"||e.target.kind!=="absolute-url"||e.method!=="GET"||e.redirectPolicy!=="error"||e.data!==void 0||e.params!==void 0||e.headers!==void 0)return!1;try{const t=new URL(e.target.url);return t.protocol==="https:"&&t.hostname==="heybox-beijing-1251007209.cos.ap-beijing.myqcloud.com"&&!t.port&&!t.username&&!t.password&&!t.hash&&/^\/cloud_archive\/[0-9]{1,20}\.zip$/.test(t.pathname)&&t.searchParams.has("q-signature")}catch{return!1}}const mf="METHOD_FORBIDDEN";function At(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=mf,t}class qe 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 rg=/^[A-Za-z0-9_-]{1,64}$/,Nu=1e3;function Ef(e){return rg.test(e)?e:og(e)}function ng(e){return`id_${Ef(e.trim())}`}function Br(e,t){return`hb_miniprogram_${e}_${t}`}function Mi(e){return`hb_miniprogram_keys_${e}`}const ig="hb_user_game_data_consent_";function sg(e){return`${ig}${e}`}function og(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 ag=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 Sc(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]),s=new Uint32Array(64),o=new DataView(n.buffer);for(let c=0;c<r;c+=64){for(let N=0;N<16;N+=1)s[N]=o.getUint32(c+N*4,!1);for(let N=16;N<64;N+=1){const y=s[N-15],L=s[N-2],A=Ct(y,7)^Ct(y,18)^y>>>3,U=Ct(L,17)^Ct(L,19)^L>>>10;s[N]=s[N-16]+A+s[N-7]+U>>>0}let[u,d,l,f,h,_,g,b]=i;for(let N=0;N<64;N+=1){const y=b+(Ct(h,6)^Ct(h,11)^Ct(h,25))+(h&_^~h&g)+ag[N]+s[N]>>>0,L=(Ct(u,2)^Ct(u,13)^Ct(u,22))+(u&d^u&l^d&l);b=g,g=_,_=h,h=f+y>>>0,f=l,l=d,d=u,u=y+L>>>0}[u,d,l,f,h,_,g,b].forEach((N,y)=>{i[y]=i[y]+N>>>0})}return Array.from(i,c=>c.toString(16).padStart(8,"0")).join("")}function Ct(e,t){return e>>>t|e<<32-t}const cg=Object.freeze({upload:"你允许读取的数据可能会被上传至开发者服务器。",no_network:"此小程序未获准将你允许读取的数据上传至开发者服务器。"});function ug(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null||Array.isArray(t))return;const r=t;if(r.schema_version!==1||typeof r.records!="object"||r.records===null||Array.isArray(r.records))return;const n={};for(const[i,s]of Object.entries(r.records)){if(typeof s!="object"||s===null||Array.isArray(s))return;const o=s;if(o.decision!=="ask"&&o.decision!=="allow"&&o.decision!=="deny"||typeof o.revision!="number"||!Number.isSafeInteger(o.revision)||o.revision<1||o.consentFingerprint!==void 0&&!fg(o.consentFingerprint))return;n[i]={decision:o.decision,revision:o.revision,...o.decision==="allow"&&o.consentFingerprint!==void 0?{consentFingerprint:o.consentFingerprint}:{}}}return{schema_version:1,records:n}}function dg(e){return Sc(`${e.miniProgramId}\0${e.userId}\0${e.environment}`).slice(0,32)}function lg(e){const t=e.miniProgramId?.trim(),r=e.userId?.trim(),n=e.environment?.trim();if(!t||!r||!n)throw Object.assign(new Error("无法确定用户数据许可作用域"),{code:"INVALID_STATE"});return Object.freeze({miniProgramId:t,userId:r,environment:n})}function fg(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function Me(e,t,r){return{code:e,message:t,data:r}}function Qs(e){return hg(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?Me("RUNTIME_ERROR",e.message):Me("UNKNOWN_ERROR","小程序运行时异常",e)}function hg(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}const pr=["account.getCurrentUserId","account.onChange","storage.getRaw","storage.setRaw"],Vo=[...pr,"network.request"],wu={"post.get":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.list":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.delete":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.setLiked":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.openEditor":["account.getCurrentUserId","account.onChange","network.request","presentation.openPostCommentEditor"],"post.watch":["account.getCurrentUserId","account.onChange","network.request"],"post.setLiked":["account.getCurrentUserId","account.onChange","network.request"],"post.setFavorited":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.list":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.sync":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.readParsedData":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.getFile":["account.getCurrentUserId","account.onChange","network.request","network.stream","files.transfer","files.access"],[ds]:["workspaceCards.requestRefresh"],[ls]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[fs]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[hs]:["account.getCurrentUserId","account.onChange","network.request"],[ms]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Es]:["account.getCurrentUserId","account.onChange","network.request"],[gs]:["account.getCurrentUserId","account.onChange","network.request"],[ps]:["account.getCurrentUserId","account.onChange","network.request"],[Ts]:["presentation.setClipboard"],[_s]:["presentation.showShareMenu"],[As]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Is]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Cr]:["presentation.applyOrientation"],[bs]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[ys]:["presentation.setNavigationBarStyle"],[Jn]:["storage.getRaw"],[ei]:["storage.setRaw"],[Ns]:["network.request"],[ws]:["network.stream","files.transfer","files.access"],[Ds]:["network.upload","files.access"],[Ss]:["files.external"],[Os]:["files.external"],[Ms]:["files.save"],[ti]:["files.access"],[ri]:["files.removeFile"],[Cs]:["files.access"],[ni]:["files.access"],[Rs]:["files.access"],[ii]:["files.access"],[Ls]:["files.access"],[si]:["files.access"],[Ps]:["files.access"],[oi]:["files.removeDirectory"],[vs]:["files.access"],[ks]:["files.access"],[ai]:["media.pick"],[Xn]:["presentation.showAppreciation"],[xs]:["presentation.showToast"],[Us]:["presentation.showLoading"],[Bs]:["presentation.hideLoading"],[Hs]:["presentation.vibrate"],[Fs]:["presentation.setClipboard"],[zs]:["protocol.invoke"],[js]:["presentation.close"],[Vs]:["presentation.reload"],[Gs]:["presentation.openAppPage"],[Wt]:["account.getCurrentUserId","account.onChange","network.request"],[wt]:["account.onChange","network.request"],[ar]:["account.getCurrentUserId","account.onChange","network.request"],[Rr]:["account.getCurrentUserId","account.onChange","network.request"],[Ut]:["account.onChange","network.request"],[en]:["account.getCurrentUserId","account.onChange","network.request"],[tn]:["account.getCurrentUserId","account.onChange","network.request"],[rn]:["account.getCurrentUserId","account.onChange","network.request"],[Lr]:["account.getCurrentUserId","account.onChange","network.request"],[fo]:["companion.getInfo"],[ho]:["companion.getPreparationStatus"],[mo]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[Eo]:["companion.cancelPreparation"],[go]:["companion.getActiveSession"],[po]:["companion.getInfo","companion.launch"],[To]:["companion.session.write"],[_o]:["companion.session.closeStdin"],[Ao]:["companion.session.terminate"],[Io]:["companion.session.ackOutput"],[bo]:["companion.openAttachment"],[yo]:["companion.showNotification"],[pc]:pr,[cs]:Vo,[Un]:Vo,[us]:[...Vo,"files.sandbox","files.removeFile","network.stream","files.transfer"],[Tc]:[...pr,"presentation.confirmDataPermission"],[_c]:pr,[Ac]:pr,[Ic]:[...pr,"presentation.openDataPermissions"],[bc]:pr},mg=new Set([Xn]);function gf(e,t){if(t[e]!==!0)throw mg.has(e)?Me("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):At(e)}const Eg=32*1024*1024,gg=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function pg(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 s=await r.open(n,i);let o;try{const c=await t(s.body,{maxBytes:Eg},i);return Tg(s,c)}catch(c){throw o=c,c}finally{try{await r.release(s.body)}catch(c){if(o===void 0)throw c}}}}}}function Tg(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:_g(t,Ig(e,"content-type"))}}function _g(e,t){Ag(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new qe("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!gg.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function Ag(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new qe(`Host network response 不支持 charset=${t}`)}function Ig(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function oe(e){return typeof e=="function"}function Du(e){return(...t)=>{throw At(e)}}function Ye(e){return async(...t)=>{throw At(e)}}const bg=(e,t)=>{},yg=()=>()=>{};function Ng(e){const t={request:oe(e.network?.request)?e.network.request.bind(e.network):Ye("network.request")},r={...oe(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:oe(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):Ye("account.getCurrentUserId"),ensureAuthenticated:oe(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Ye("account.ensureAuthenticated"),onChange:oe(e.account?.onChange)?e.account.onChange.bind(e.account):yg},n={...e.storage?.withLock?{withLock:e.storage.withLock.bind(e.storage)}:{},getRaw:oe(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Ye("storage.getRaw"),setRaw:oe(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Ye("storage.setRaw")},i={...oe(e.presentation?.showSteamLoginRequired)?{showSteamLoginRequired:e.presentation.showSteamLoginRequired.bind(e.presentation)}:{},...oe(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...oe(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:oe(e.presentation?.close)?e.presentation.close.bind(e.presentation):Ye("presentation.close"),reload:oe(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Ye("presentation.reload"),openAppPage:oe(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Ye("presentation.openAppPage"),openWindow:oe(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Ye("presentation.openWindow"),getViewportMetrics:oe(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Du("presentation.getViewportMetrics"),getNavigationBarHeight:oe(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Du("presentation.getNavigationBarHeight"),setNavigationBarStyle:oe(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Ye("presentation.setNavigationBarStyle"),showShareMenu:oe(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Ye("presentation.showShareMenu"),setScreenshotChromeHidden:oe(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):bg,supportsLongScreenshot:e.presentation?.supportsLongScreenshot===!0,captureAndShare:oe(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Ye("presentation.captureAndShare"),openPostCommentEditor:oe(e.presentation?.openPostCommentEditor)?e.presentation.openPostCommentEditor.bind(e.presentation):void 0,showAppreciation:oe(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw Me("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:oe(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Ye("presentation.showToast"),showLoading:oe(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Ye("presentation.showLoading"),hideLoading:oe(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Ye("presentation.hideLoading"),vibrate:oe(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Ye("presentation.vibrate"),setClipboard:oe(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Ye("presentation.setClipboard")},s=oe(e.storageDiagnostics?.listRaw)?{listRaw:e.storageDiagnostics.listRaw.bind(e.storageDiagnostics)}:void 0,o=Object.fromEntries(["getInfo","getPreparationStatus","prepare","cancelPreparation","getActiveSession","launch","write","closeStdin","terminate","ackOutput","openAttachment","showNotification"].map(u=>[u,oe(e.companion?.[u])?e.companion[u].bind(e.companion):Ye(`companion.${u}`)]));oe(e.companion?.onSessionEvent)&&(o.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const c={invoke:oe(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):Ye("protocol.invoke")};return{network:t,...e.workspaceCards?{workspaceCards:e.workspaceCards}:{},account:r,storage:n,presentation:i,companion:o,protocol:c,...e.files===void 0?{}:{files:e.files},...e.picker===void 0?{}:{picker:e.picker},...e.media===void 0?{}:{media:e.media},...e.transfer===void 0?{}:{transfer:e.transfer},...e.scopedStorage?{scopedStorage:e.scopedStorage}:{},...s?{storageDiagnostics:s}:{}}}function wg(e,t={}){const r=Dg(e.files?.sandbox),n=oe(e.picker?.pickFiles)&&oe(e.picker?.pickDirectory),i=oe(e.picker?.saveFile),s=r||n||i||oe(e.companion?.openAttachment),o=r?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":oe(e.account?.getAccountKey),"account.getCurrentUserId":oe(e.account?.getCurrentUserId),"account.ensureAuthenticated":oe(e.account?.ensureAuthenticated),"account.onChange":oe(e.account?.onChange),"network.request":oe(e.network?.request),"network.stream":oe(e.transfer?.network.open)&&oe(e.transfer?.network.release),"network.upload":oe(e.transfer?.upload?.upload),"files.sandbox":r,"files.external":n,"files.save":i,"files.access":s,"files.removeFile":oe(o?.remove),"files.removeDirectory":oe(e.files?.sandbox.remove),"files.transfer":oe(e.transfer?.files.writeResource),"media.pick":oe(e.media?.pick),"storage.getRaw":oe(e.scopedStorage?.get)||oe(e.storage?.getRaw),"storage.setRaw":oe(e.scopedStorage?.set)||oe(e.storage?.setRaw),"presentation.close":oe(e.presentation?.close),"presentation.reload":oe(e.presentation?.reload),"presentation.openAppPage":oe(e.presentation?.openAppPage),"presentation.applyOrientation":oe(e.presentation?.applyOrientation),"presentation.openWindow":oe(e.presentation?.openWindow),"presentation.getViewportMetrics":oe(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":oe(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":oe(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":oe(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":oe(e.presentation?.captureAndShare),"presentation.openPostCommentEditor":oe(e.presentation?.openPostCommentEditor),"presentation.showAppreciation":oe(e.presentation?.showAppreciation),"presentation.showToast":oe(e.presentation?.showToast),"presentation.showLoading":oe(e.presentation?.showLoading),"presentation.hideLoading":oe(e.presentation?.hideLoading),"presentation.vibrate":oe(e.presentation?.vibrate),"presentation.setClipboard":oe(e.presentation?.setClipboard),"workspaceCards.requestRefresh":oe(e.workspaceCards?.requestRefresh),"companion.getInfo":oe(e.companion?.getInfo),"companion.getPreparationStatus":oe(e.companion?.getPreparationStatus),"companion.prepare":oe(e.companion?.prepare),"companion.cancelPreparation":oe(e.companion?.cancelPreparation),"companion.getActiveSession":oe(e.companion?.getActiveSession),"companion.launch":oe(e.companion?.launch),"companion.session.write":oe(e.companion?.write),"companion.session.closeStdin":oe(e.companion?.closeStdin),"companion.session.terminate":oe(e.companion?.terminate),"companion.session.ackOutput":oe(e.companion?.ackOutput),"companion.openAttachment":oe(e.companion?.openAttachment),"companion.showNotification":oe(e.companion?.showNotification),"protocol.invoke":oe(e.protocol?.invoke),"presentation.confirmDataPermission":t.hasUserDataPresentation===!0,"presentation.openDataPermissions":t.hasUserDataSettings===!0}}function Dg(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&oe(t.file)&&oe(t.directory)&&oe(t.create)&&oe(t.stat)&&oe(t.list)}function Su(e,t){return t?.[e]!==!1}function Sg(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function pf(e,t={}){const r={};for(const n of Object.keys(wu)){const s=wu[n].every(c=>e[c]),o=!Sg(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=Su(n,t.callerCapabilities)&&Su(n,t.hostCapabilities)&&s&&o}return r}function Tf(e={},t={}){const r=wg(e,t),n=pf(r,t);return{ports:Ng(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function Re(e,t,r){if(!t||t===e.signal)return r===void 0?e:{...e,requestId:r};const n=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):Og(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function Og(e,t){const r=new AbortController,n=()=>{e.removeEventListener("abort",s),t.removeEventListener("abort",o)},i=c=>{r.signal.aborted||(n(),r.abort(c.reason))},s=()=>i(e),o=()=>i(t);return e.aborted?i(e):t.aborted?i(t):(e.addEventListener("abort",s,{once:!0}),t.addEventListener("abort",o,{once:!0})),r.signal}function Mg(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 Cg=4,Rg=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Lg=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),Pg=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],vg=["/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 kg(e,t){const r=Bg(e);return r===null||Ou(r,Pg)?!0:t&&Ou(r,vg)}function xg(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Rg.some(r=>t===r||t.endsWith(`.${r}`))}function Ug(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||Lg.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Bg(e){let t=e;for(let r=0;r<Cg;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Mu(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Mu(t)}function Ou(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Mu(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Hg(e){if(typeof e!="string"||e!==e.trim()||e.length>253)return;const t=e.toLowerCase();if(!(!t.includes(".")||/^\d+(?:\.\d+)*$/.test(t))&&t.split(".").every(r=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(r))&&!(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")))return t}function _f(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw Go("网络策略格式无效");const t=e,r=t.entries===void 0?[]:t.entries;if(!Number.isSafeInteger(t.revision)||t.revision<1||t.enforcement!=="approved_domains"&&t.enforcement!=="restricted"||!Array.isArray(r)||r.length>20)throw Go("网络策略格式无效");const n=new Set;for(const i of r){const s=Hg(i&&typeof i=="object"?i.domain:void 0);if(!s)throw Go("网络策略包含无效域名");n.add(s)}return Object.freeze({revision:t.revision,enforcement:t.enforcement,entries:Object.freeze([...n].sort().map(i=>Object.freeze({domain:i})))})}function Go(e){return Object.assign(new TypeError(e),{code:"NETWORK_POLICY_INVALID"})}function Cu(e){return e instanceof qe?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function be(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Qi());let n;try{n=e()}catch(i){return Promise.reject(Cu(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Qi())):new Promise((i,s)=>{let o=!1;const c=d=>{o||(o=!0,t.removeEventListener("abort",u),d())},u=()=>c(()=>s(Qi()));t.addEventListener("abort",u,{once:!0}),Promise.resolve(n).then(d=>c(()=>i(d)),d=>c(()=>s(Cu(d))))})}async function Fg(e,t,r){Oe(r);const i=e.ownerDocument.defaultView;if(!i||!e.isConnected)throw new Error("长图容器不可用");const s=e.getAttribute("style"),o=i.scrollX,c=i.scrollY,u=e.getBoundingClientRect().width,d=()=>{s===null?e.removeAttribute("style"):e.setAttribute("style",s),i.scrollTo(o,c)};try{e.style.setProperty("width",`${u}px`,"important"),e.style.setProperty("height",`${t.top+t.height}px`,"important"),e.style.setProperty("min-height","0","important"),e.style.setProperty("max-height","none","important"),i.scrollTo(0,0),await be(()=>new Promise(f=>i.requestAnimationFrame(()=>i.requestAnimationFrame(()=>f()))),r);const l=e.getBoundingClientRect();if(l.height+1<t.top+t.height||l.width+1<t.left+t.width||l.left<0||l.top<0)throw new Error("宿主布局无法容纳长图");for(let f=e.parentElement;f;f=f.parentElement){const h=i.getComputedStyle(f),_=f.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(h.overflowY)&&(l.top+t.top<_.top-1||l.top+t.top+t.height>_.bottom+1))throw new Error("宿主布局无法容纳长图:祖先容器存在纵向裁剪")}return{rect:{...t,left:t.left+l.left,top:t.top+l.top},restore:d}}catch(l){throw d(),l}}function zg(e,t,r,n=1e4){const i=new AbortController;return new Promise((s,o)=>{let c=!1;const u=f=>{c||(c=!0,clearTimeout(l),r.signal.removeEventListener("abort",d),i.abort(f),o(f))},d=()=>{i.abort(),u({code:"NETWORK_POLICY_CHANGED",message:"网络策略初始化已取消"})},l=setTimeout(()=>u({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 网络策略初始化超时"}),n);if(r.signal.addEventListener("abort",d,{once:!0}),r.signal.aborted){d();return}Promise.resolve().then(()=>e.activate(t,{signal:i.signal})).then(f=>{if(typeof f!="function"){u({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 未完成严格网络策略初始化"});return}if(c){try{f()}catch{}return}c=!0,clearTimeout(l),s(()=>{r.signal.removeEventListener("abort",d),i.abort(),f()})},u)})}function Af(e,t){return jg(t)??Vg(e.pathname)}function jg(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Vg(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const Gg=1,If="allow-scripts allow-same-origin",Yg="",Qg="no-referrer";function qg(e=If){return!e.split(/\s+/).includes("allow-same-origin")}function Ru(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Wg=new Set(["javascript:","data:","blob:","file:"]),Lu="xiaoheihe.cn";function $g(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(Wg.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!Zg(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Kg(e,t){const r=new URL(e);return r.searchParams.set(zl,t),r.toString()}function bf(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const s=Af(n,r);return i.pathname.startsWith(s)}catch{return!1}}function Pu(e){const t=new URL(e);return Oc(t)?"loopback":Mc(t)?"lan":"production"}function Zg(e,t,r){return Xg(e)||Oc(e)||Mc(e)&&ep(t,r)}function Xg(e){return e.protocol==="https:"&&np(e.hostname)}function Oc(e){return e.protocol==="http:"&&Jg(e.hostname)}function Jg(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Mc(e){return e.protocol==="http:"&&tp(e.hostname)}function ep(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Oc(r)||Mc(r)}catch{return!1}}function tp(e){const t=rp(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function rp(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 np(e){return e===Lu||e.endsWith(`.${Lu}`)}function ip(e){let t,r=!1,n=!1;const i=new URL(e.launchUrl).origin,s=o=>{const c=o.data;if(n||!e.iframe.contentWindow||o.source!==e.iframe.contentWindow||o.origin!==i||c?.type!=="hb-sdk:dev-document"||c.nonce!==e.nonce||typeof c.documentId!="string"||!/^[a-f0-9]{32}$/.test(c.documentId)||typeof c.href!="string"||c.href.length>8192||!bf(e.launchUrl,c.href,e.locationBasePath))return;const u=new URL(c.href);if(!(u.username||u.password||u.searchParams.get(zl)!==e.nonce)){if(c.phase==="leaving"){c.documentId===t&&!r&&(r=!0,e.onLeaving());return}if(c.phase==="boot"){if(t!==void 0&&t!==c.documentId&&c.navigationType==="reload"){n=!0,e.onReload(u.href);return}r&&t===c.documentId&&e.onResume(),t=c.documentId,r=!1}}};return window.addEventListener("message",s),()=>{window.removeEventListener("message",s)}}function yf(e){const t=ot(e);return(r,n)=>{if(r.kind==="none")return{allowed:!0};for(const i of r.permissions){const s=t.valid?t.permissions[i]:void 0;if(!s)return{allowed:!1,code:"PERMISSION_NOT_IN_SNAPSHOT",message:`当前运行快照不包含权限: ${i};正式入口需发布包含该声明的新版本,开发入口请重新打开调试`,data:{permission:i,method:n}};if(s.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${i}`,data:{permission:i,method:n}};if(i==="post"){const o=lo.includes(n)?"read":Zn.includes(n)?"write":void 0;if(!o||s.config[o]!==!0)return{allowed:!1,code:"PERMISSION_DENIED",message:`关联帖子未声明 ${o??n} 权限`,data:{permission:i,method:n}}}}return{allowed:!0}}}function sp(e){const t=ot(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 op(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const ap=1e3;function cp(e,t=op()){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<=ap}const up="runtime.gate.probe",Nf=new Set(cr.map(e=>e.method));class dp{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=Fl;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.getWorkspaceCardLaunchContext=t.getWorkspaceCardLaunchContext,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,this.onDevUploadSession=t.onDevUploadSession,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:gr,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:gr,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:gr,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:gr,version:2,nonce:this.nonce,type:"event",id:t,method:Vl,payload:r})}onMessage(t){if(!this.started||this.destroyed)return;if(this.onDevUploadSession&&this.iframe.contentWindow&&t.source===this.iframe.contentWindow&&t.data?.type==="hb-sdk:dev-upload-session"){const n=t.data.deviceSessionId;if(typeof n=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(n))try{this.onDevUploadSession(n)}catch{}return}if(!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=cp(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&&R0(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,s=!this.handshaken;if(s){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:gr,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:jl,payload:{environment:this.environmentInfo,...this.getWorkspaceCardLaunchContext?{workspaceCardLaunchContext:this.getWorkspaceCardLaunchContext()}:{}}}),this.postEvent("ready",{timestamp:Date.now()}),s?this.onReady?.(n):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===up){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,Me("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Nf.has(t.method)){this.postResponse(t,void 0,Me("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,Me("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,{requestId:t.id,postEvent:this.postEvent.bind(this),postProgress:s=>{this.operations.get(t.id)===n&&this.postProgress(t.id,s)},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 s=Qs(i);this.postResponse(t,void 0,s),this.postEvent("error",s)}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:gr,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!lp(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 lp(e){return typeof e=="string"&&Nf.has(e)}function p(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function le(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cc(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw p("FILE_IO_FAILED","当前环境缺少安全随机数能力");try{const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}catch{throw p("FILE_IO_FAILED","无法生成安全文件标识")}}function wf(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",s=r.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:n,create:i?(o,c)=>e.create(o,c):wa,remove:s?o=>e.remove(o):Sf,read:o=>e.read(o),...typeof e.readPrefix=="function"?{readPrefix:(o,c)=>e.readPrefix(o,c)}:{},write:i?(o,c)=>e.write(o,c):wa,stat:o=>e.stat(o)})}function Df(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",s=r.allowRemove!==!1,o=s&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:n,file:c=>wf(e.file(c),n,{allowRemove:s}),directory:c=>Df(e.directory(c),n,{allowRemove:s}),create:i?(c,u)=>e.create(c,u):wa,remove:o?(c,u)=>e.remove(c,u):Sf,stat:c=>e.stat(c),list:(c,u)=>e.list(c,u)})}function wa(){return Promise.reject(p("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Sf(){return Promise.reject(p("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const fp=new Set(["REQUEST_CANCELLED","REQUEST_TIMEOUT","RUNTIME_DESTROYED","USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","USER_DATA_PERMISSION_STATE_INVALID","USER_DATA_SOURCE_NOT_LINKED","USER_DATA_SOURCE_LOGIN_REQUIRED","USER_GAME_DATA_UNAVAILABLE","USER_GAME_DATA_INVALID_RESPONSE","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"]),hp={REQUEST_CANCELLED:"文件操作已取消",REQUEST_TIMEOUT:"文件操作超时",RUNTIME_DESTROYED:"小程序已关闭",USER_DATA_PERMISSION_STORAGE_UNAVAILABLE:"无法读取本地用户数据许可",USER_DATA_PERMISSION_STATE_INVALID:"本地用户数据许可状态异常,已停止访问",USER_DATA_SOURCE_NOT_LINKED:"请先在小黑盒关联对应游戏账号",USER_DATA_SOURCE_LOGIN_REQUIRED:"请先在小黑盒更新游戏来源登录",USER_GAME_DATA_UNAVAILABLE:"游戏资料暂不可用,请稍后重试",USER_GAME_DATA_INVALID_RESPONSE:"游戏资料响应异常,请稍后重试",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 sn(e){const t=Rc(e),r=t&&fp.has(t)?p(t,hp[t]??"文件操作失败"):p("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Gt(e){try{return e()}catch(t){throw sn(t)}}function Rc(e){try{if(!le(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const vu=1024;class Lc{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new Lc(void 0,this.miniProgramDetail)}dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareFile(t,r,n),[s]=this.registerMany([i]);return Ci(i.handle,{kind:"file",handleId:s})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const s=Gt(()=>{if(!Array.isArray(t))throw p("FILE_IO_FAILED","Host 返回了无效文件选择结果");const c=t.length;if(i!==void 0&&c>i)throw p("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+c>vu)throw p("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const u=[];for(let d=0;d<c;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw p("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");u.push(this.prepareFile(t[d],r,n))}return u}),o=this.registerMany(s);return s.map((c,u)=>Ci(c.handle,{kind:"file",handleId:o[u]}))}revokeFiles(t){for(const r of t)this.handles.get(r)?.handle.kind==="file"&&this.handles.delete(r)}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[s]=this.registerMany([i]);return xu(i.handle,{kind:"directory",handleId:s})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Dr(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!Dr(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}isUserDataDownloadRef(t){return!Dr(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="download"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Ep(t);if("handleId"in r){const o=this.readDirect(r.handleId,"file");return{ref:r,...o}}const n=this.resolveRoot(r.root),i=ui(r.relativePath);Yo(n.origin,i);const s=this.prepareFile(Gt(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...s}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=gp(t);if("handleId"in r){const o=this.readDirect(r.handleId,"directory");return{ref:r,...o}}const n=this.resolveRoot(r.root),i=r.relativePath==="."?".":ui(r.relativePath);Yo(n.origin,i);const s=this.prepareDirectory(i==="."?n.hostHandle:Gt(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...s}}describeFile(t,r){return Bu(t),Ci(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Gt(()=>{if(!Array.isArray(r))throw p("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw p("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const s=[];for(let o=0;o<i;o+=1){if(!Object.prototype.hasOwnProperty.call(r,o))throw p("FILE_IO_FAILED","Host 返回了稀疏目录列表");const c=r[o];t.origin==="sandbox"&&le(c)&&typeof c.name=="string"&&Of(c.name)||s.push(this.describeListedEntry(t,c))}return this.assertCanonicalDetail(),s})}describeListedEntry(t,r){return Gt(()=>{if(le(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Ci(n.handle,ku(t.ref,n.handle.name))}if(le(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return xu(n.handle,mp(t.ref,n.handle.name))}throw p("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=pi(r);Yo(t.origin,n);const i=this.prepareFile(Gt(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:ku(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw p("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Gt(()=>{Bu(t);const i=n??t.mode;return Uu(t.mode,i),{handle:wf(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Gt(()=>{_p(t,i);const s=n??t.mode;return Uu(t.mode,s),{handle:Df(t,s,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>vu)throw p("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const s=Cc();if(!this.handles.has(s)&&!r.has(s))return r.add(s),s}throw p("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,s)=>this.handles.set(n[s],i)),n}readDirect(t,r){if(!pp(t))throw p("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw p("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw p("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw At("files.sandbox");return this.prepareDirectory(Gt(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw p("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw At("files")}}function ui(e){if(!yc(e))throw p("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Yo(e,t){if(e==="sandbox"&&Of(t))throw p("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function Of(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function pi(e,t="文件名"){const r=ui(e);if(r.includes("/"))throw p("INVALID_PARAMS",`${t} 只能是 basename`);return r}function ku(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:ui(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function mp(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:ui(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Ci(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function xu(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Uu(e,t){if(t==="readwrite"&&e!=="readwrite")throw p("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Ep(e){return Dr(e)||Mf(),e}function gp(e){return Yl(e)||Mf(),e}function Mf(){throw p("INVALID_PARAMS","文件引用不合法")}function pp(e){return/^[0-9a-f]{32}$/.test(e)}function Tp(e){return le(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"}function Bu(e){if(!Tp(e))throw p("FILE_IO_FAILED","Host 返回了无效 File handle");pi(e.name,"Host File name")}function _p(e,t=!1){if(!le(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 p("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw p("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&pi(e.name,"Host Directory name")}const Ap=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Ip=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),bp=new Set(["range","if-range","a-im"]),yp=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"]),Np=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Ri={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class wp{constructor(t){this.signal=t}phase="initial";transition(t){if(Ri[t]<=Ri[this.phase])throw p("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Ri[this.phase]<Ri.committed&&this.signal.aborted)throw Lf()}normalizeHostError(t,r){return this.throwIfCancelled(),vc(t,r,this.signal)}}async function Cf(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw At("network.download");const s=Re(r.operationContext,t.signal),o=new wp(s.signal);o.transition("target"),o.throwIfCancelled();let c;try{c=await Mp(e,i,s)}catch(l){throw o.normalizeHostError(l,"file")}o.throwIfCancelled();let u;o.transition("open");try{u=await n.network.open(e.request,s)}catch(l){throw o.normalizeHostError(l,"network")}let d=!1;try{o.throwIfCancelled(),o.transition("validate");const l=Rp(u);Lp(u,l);const f=Pp(u.status,l);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw p("FILE_TOO_LARGE","下载响应超过 maxBytes");o.throwIfCancelled();const h=Cp(e,c,l,i);let _=0;const g=Sp(f.expectedBytes,e.maxBytes);qo(t,Qo(0,f));const b={...s,onProgress(L){!Number.isSafeInteger(L)||L<_||g!==void 0&&L>g||(_=L,qo(t,Qo(_,f)))}};o.transition("transfer"),d=!0;let N;try{N=await n.files.writeResource(h.hostHandle,u.body,{mode:h.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...f.expectedBytes===void 0?{}:{expectedBytes:f.expectedBytes}},b)}catch(L){throw o.normalizeHostError(L,"transfer")}o.transition("committed"),_=Dp(N,f,_,e.maxBytes),qo(t,Qo(_,f));const y=i.describeFile(h.handle,h.ref);return o.transition("completed"),y}finally{d||Op(n.network,u.body)}}function Dp(e,t,r,n){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=n===void 0?r:Math.min(r,n);try{const s=e?.committedBytes;if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=i&&(n===void 0||s<=n))return s}catch{}return i}function Sp(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Op(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Mp(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Da(i.handle.mode),await Fp(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Da(n.handle.mode),await zp(n.handle,r),{kind:"directory",...n}}function Cp(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=kp(e,r),s=n.deriveFile(t,i);return Da(s.handle.mode),{...s,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Rp(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 p("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!le(e.headers))throw p("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!Ap.has(r)||!Array.isArray(n)||n.length===0)throw p("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw p("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Lp(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw p("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:Hp(t,Ip)});if((t["content-range"]?.length??0)>0)throw p("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Pp(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw p("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw p("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw p("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,s=i!==void 0&&Number.isSafeInteger(i)?i:void 0,o=vp(t["content-encoding"]),c=e===204||e===205?0:n.length===0&&o?s:void 0,u=c!==void 0;return{...c===void 0?{}:{expectedBytes:c},...u?{total:c}:{},lengthComputable:u}}function vp(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Qo(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function qo(e,t){try{e.postProgress(t)}catch{}}function kp(e,t){const r=t["content-disposition"]??[];for(const i of r){const s=xp(i);if(s&&qi(s))return s}for(const i of r){const s=Up(i);if(s&&qi(s))return s}if(e.suggestedName!==void 0)return Pc(e.suggestedName);const n=Bp(e.url);return n&&qi(n)?n:"download.bin"}function xp(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 Up(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 Bp(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Pc(e){try{pi(e,"suggestedName")}catch{throw p("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!qi(e))throw p("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function qi(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Np.test(e))}function Hp(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Fp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Rf()}catch(r){throw vc(r,"file",t.signal)}}async function zp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Rf()}catch(r){throw vc(r,"file",t.signal)}}function Da(e){if(e!=="readwrite")throw p("FILE_ACCESS_DENIED","下载目标只允许读取")}const jp={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 vc(e,t,r){if(r.aborted)return Lf();const n=Vp(e);if(n&&yp.has(n)){const s=p(n,jp[n]??"下载失败");return Object.defineProperty(s,"cause",{value:e,enumerable:!1}),s}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?p("DOWNLOAD_TIMEOUT","下载网络请求超时"):p("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?p("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):p("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function Vp(e){return le(e)&&typeof e.code=="string"?e.code:void 0}function Rf(){return p("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Lf(){return p("DOWNLOAD_CANCELLED","下载已取消")}function Gp(e){if(!e)return;const t=Object.keys(e).find(r=>bp.has(r.trim().toLowerCase()));if(t)throw p("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Hu=8*1024*1024,Yp=32*1024*1024;function kc(e){const t=new Map;let r=0;const n={signal:new AbortController().signal,lifecycle:"cleanup"},i=c=>c.remove(n).catch(()=>{}),s=async c=>{const u=t.get(c);u&&(t.delete(c),r-=u.size,await i(u.target))};e.signal.addEventListener("abort",()=>{for(const c of t.keys())s(c)},{once:!0});const o=c=>{if(e.signal.aborted||c.signal.aborted)throw p("DOWNLOAD_CANCELLED","存档下载已取消")};return{release:s,sizeOf:c=>t.get(c)?.size,async download(c,u,d){const l=c.file;if(!l||typeof l.file_id!="string"||typeof l.name!="string"||typeof l.size_bytes!="number"||!Number.isSafeInteger(l.size_bytes)||l.size_bytes<0||typeof c.download_url!="string"||typeof c.expires_at!="number"||!Number.isSafeInteger(c.expires_at))throw p("INVALID_RESPONSE","存档下载描述无效");if(l.size_bytes>Hu)throw p("FILE_TOO_LARGE","存档文件超过 8 MiB");const f={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:c.download_url},timeout:6e4};if(!hf(f)||new URL(c.download_url).pathname!==`/cloud_archive/${l.file_id}.zip`||c.expires_at<=Date.now())throw p("INVALID_RESPONSE","存档下载地址无效");o(d);const h=Math.min(Hu,Yp-r);if(h<=0)throw p("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达上限");const _=e.files.sandbox.file(`.hb-game-saves/${Cc()}.zip`);if(!_.remove)throw p("REQUEST_UNSUPPORTED","宿主不支持私有存档清理");r+=h;let g=!1;try{await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},d),await _.create({recursive:!0,exclusive:!0},d);const b=e.registry.createTransferScope();try{const A=b.registerFile(_,"game-save","readwrite");await Cf({request:f,url:new URL(c.download_url),to:A.ref,targetKind:"file",maxBytes:h},{...d,trustedUserGesture:!1,postEvent:()=>{},postProgress:()=>{}},{transfer:e.transfer,fileRegistry:b,operationContext:d})}finally{b.dispose()}o(d);const N=(await _.stat(d)).size;if(!Number.isSafeInteger(N)||N<0||N>h)throw p("FILE_TOO_LARGE","存档实际大小超过限额");await u(d),o(d);const y=async()=>{throw p("FILE_ACCESS_DENIED","存档文件只读")},L={kind:"file",mode:"read",name:l.name,create:y,write:y,async read(A){o(A),await u(A);const U=await _.read(A);try{if(o(A),await u(A),U.byteLength!==N)throw p("INVALID_RESPONSE","私有存档副本长度不匹配");return U}catch(Q){throw U.fill(0),Q}},async stat(A){return o(A),await u(A),await _.stat(A),o(A),await u(A),{kind:"file",size:N,...typeof l.modified_at=="number"&&Number.isSafeInteger(l.modified_at)?{modifiedAt:l.modified_at}:{}}}};return r-=h-N,t.set(L,{target:_,size:N}),g=!0,L}finally{g||(r-=h,await i(_))}}}}const Qp=/^(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 qp(e){if(!e?.minimumSdkVersion)throw Me("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=br(e.minimumSdkVersion),r=e.sdkVersion?br(e.sdkVersion):void 0;if(!t)throw Me("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw Me("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=br("0.6.0");if(!r){if(Wi(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw Me("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0&&e.allowPublicPrerelease!==!0)throw Me("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(Wi(r,t)<0)throw Me("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Wi(r,br("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Wp(e,t){if(typeof t!="string"||!br(t))throw Me("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw Me("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function xc(e,t){const r=br(e),n=br(t);if(!(!r||!n))return Wi(r,n)}function br(e){const t=Qp.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 Wi(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],s=t.prerelease[n];if(i===void 0||s===void 0)return i===s?0:i===void 0?-1:1;if(i!==s)return typeof i=="number"&&typeof s=="string"?-1:typeof i=="string"&&typeof s=="number"?1:i<s?-1:1}return 0}function $p(e){return{[Xn]:async(t,r)=>{const n=Re(e.operationContext,r.signal);if(Oe(n.signal),t!==void 0)throw p("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw p("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const s=e.presentation.showAppreciation;if(!s)throw p("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await be(()=>s({name:i.name,author:i.author},n),n.signal)}}}function Hr(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Fu(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function Pf(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,s=new Map,o=new Set,c=new Set;let u=!1;function d(b,N){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:b,type:N})).catch(()=>{})}catch{}}function l(b){const N=r.get(b);if(!N)throw new Error("Unknown runtime cache scope");return N}function f(b,N){return b.flatMap((y,L)=>{const A=JSON.stringify(b.slice(0,L+1));return[JSON.stringify([A]),JSON.stringify([A,N])]})}function h(b,N){return JSON.stringify(f(b,N).map(y=>n.get(y)??0))}async function _(b,N){const y=l(b),L=JSON.stringify([JSON.stringify(y),...N?[N]:[]]),A=(n.get(L)??0)+1;n.set(L,A),i.add(L);for(const U of c)U(y,N);if(!e.store){i.delete(L),d(N??"*","invalidation");return}try{await e.store.invalidate(y,N)}catch(U){throw d(N??"*","storage_error"),U}n.get(L)===A&&i.delete(L),d(N??"*","invalidation")}function g(b){if(u)throw new Error("Runtime cache manager disposed");const N=s.get(b.namespace);if(N){if(N.sourceCodec!==b.codec||N.definition.codec.version!==b.codec.version||JSON.stringify(N.definition.policy)!==JSON.stringify(b.policy))throw new Error("Conflicting runtime cache namespace");return N.cache}if(!b.namespace||!b.codec.version)throw new Error("Invalid runtime cache definition");const y=Object.freeze({...b.policy}),L=Object.freeze({version:b.codec.version,encode:b.codec.encode.bind(b.codec),decode:b.codec.decode.bind(b.codec),validate:b.codec.validate.bind(b.codec),clone:b.codec.clone.bind(b.codec)}),A=b.namespace;for(const v of[y.ttlMs,y.memoryMaxEntries,y.diskMaxEntries,y.diskMaxBytes,y.maxEntryBytes])if(!Number.isFinite(v)||v<0)throw new Error("Invalid runtime cache policy");const U=new Map,Q=new Map,C=new Map;let P=!1;function M(v,R,q){if(u||P||v.aborted||h(R,A)!==q)throw Hr()}function V(v){return y.ttlMs>0&&y.persistence==="memory-and-disk"&&!!e.store&&!f(v,A).some(R=>i.has(R))}function z(v,R,q){const D=t();return v.envelopeVersion===1&&JSON.stringify(v.address)===JSON.stringify(R)&&Fu(v.revisions,q)&&v.payload.byteLength<=y.maxEntryBytes&&Number.isFinite(v.cachedAt)&&Number.isFinite(v.expiresAt)&&v.cachedAt<=D&&v.cachedAt>=0&&v.expiresAt>v.cachedAt&&Math.min(v.expiresAt,v.cachedAt+y.ttlMs)>D}function te(v,R,q,D,W){if(!(y.ttlMs<=0||y.memoryMaxEntries<1)){for(const[$,m]of U)Math.min(m.entry.expiresAt,m.entry.cachedAt+y.ttlMs)<=t()&&U.delete($);for(U.delete(v);U.size>=Math.floor(y.memoryMaxEntries);){const $=U.keys().next();if($.done)break;U.delete($.value)}U.set(v,{entry:R,value:q,epoch:D,persistent:W})}}async function x(v,R,q,D){const W={namespace:A,codecVersion:L.version,scopeIds:R,key:v.key},$=JSON.stringify(W);let m=[],w=V(R);if(w)try{m=await e.store.readRevisions(R,A)}catch{w=!1,d(A,"storage_error")}M(D.signal,R,q);async function B(){if(!w)return!0;try{return Fu(m,await e.store.readRevisions(R,A))}catch{return w=!1,d(A,"storage_error"),!1}}const K=U.get($);if(y.ttlMs>0&&K&&K.epoch===q&&z(K.entry,W,m)&&K.persistent===w&&await B())return M(D.signal,R,q),d(A,"memory_hit"),K.value;if(U.delete($),w){let ue,Te;try{ue=await e.store.read(W,y.maxEntryBytes),ue&&z(ue,W,m)?Te=L.decode(ue.payload):ue=void 0}catch{ue=void 0,d(A,"storage_error")}if(M(D.signal,R,q),ue&&await B())return M(D.signal,R,q),te($,ue,Te,q,!0),d(A,"disk_hit"),Te}d(A,"miss");const ce=L.validate(await v.load(D.signal));M(D.signal,R,q);const pe=L.clone(ce);if(!await B()&&w)throw Hr();if(M(D.signal,R,q),y.ttlMs>0){const ue=t();let Te;try{Te=L.encode(pe)}catch{return pe}const we={envelopeVersion:1,address:W,revisions:w?m:[],cachedAt:ue,expiresAt:ue+y.ttlMs,payload:Te};if(w&&Te.byteLength<=y.maxEntryBytes){let Ae=!0,Ie=!1;try{Ae=await e.store.publish(we,y),Ie=Ae}catch{d(A,"storage_error")}if(M(D.signal,R,q),!Ae)throw Hr();Ie&&d(A,"published")}M(D.signal,R,q),te($,we,pe,q,w)}return pe}async function Y(v){if(u||P||v.signal?.aborted)return Promise.reject(Hr());const R=l(v.scope),q=h(R,A);let D;if(V(R)){const w=new AbortController;C.set(w,R);const B=()=>w.abort();v.signal?.addEventListener("abort",B,{once:!0});let K=()=>{};try{D=await Promise.race([e.store.readRevisions(R,A),new Promise((ce,pe)=>{const ue=()=>pe(Hr());w.signal.addEventListener("abort",ue,{once:!0}),K=()=>w.signal.removeEventListener("abort",ue)})])}catch{w.signal.aborted||d(A,"storage_error")}finally{K(),C.delete(w),v.signal?.removeEventListener("abort",B)}}M(v.signal??new AbortController().signal,R,q);const W=JSON.stringify([R,v.key,q,D]);let $=Q.get(W);if($?.controller.signal.aborted&&($=void 0),!$){const w=new AbortController;$={ids:R,controller:w,waiters:0,promise:Promise.resolve(void 0)};const B=$;B.promise=x(v,R,q,w).finally(()=>{Q.get(W)===B&&Q.delete(W)}),Q.set(W,B)}const m=$;return m.waiters+=1,new Promise((w,B)=>{let K=!1;function ce(ue){K||(K=!0,v.signal?.removeEventListener("abort",pe),m.controller.signal.removeEventListener("abort",pe),m.waiters-=1,m.waiters===0&&m.controller.abort(),ue())}function pe(){ce(()=>B(Hr()))}v.signal?.addEventListener("abort",pe,{once:!0}),m.controller.signal.addEventListener("abort",pe,{once:!0}),m.promise.then(ue=>ce(()=>{try{M(v.signal??new AbortController().signal,R,q),w(L.clone(ue))}catch(Te){B(Te)}}),ue=>ce(()=>B(ue)))})}function j(v,R){if(R&&R!==A)return;const q=D=>v.every((W,$)=>D[$]===W);for(const[D,W]of U)q(W.entry.address.scopeIds)&&U.delete(D);for(const[D,W]of Q)q(W.ids)&&(W.controller.abort(),Q.delete(D));for(const[D,W]of C)q(W)&&D.abort()}function H(){if(!P){P=!0,U.clear();for(const v of C.keys())v.abort();C.clear();for(const v of Q.values())v.controller.abort();Q.clear(),o.delete(H),c.delete(j),s.get(A)?.cache===F&&s.delete(A)}}const F={read:Y,invalidateScope:v=>_(v,A),dispose:H};return o.add(H),c.add(j),s.set(A,{definition:{namespace:A,codec:L,policy:y},sourceCodec:b.codec,cache:F}),F}return{createScope(b,N){if(u||!b)throw new Error("Invalid runtime cache scope");const y=Object.freeze({});return r.set(y,[...N?l(N):[],b]),y},register:g,invalidateScope:b=>_(b),dispose(){if(!u){u=!0;for(const b of[...o])b();s.clear(),n.clear(),i.clear()}}}}function Kp(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 Zp=".hb-runtime-cache-v1",Xp=1e3,Wo=64*1024,Fr=1e3,Jp=2048,bn=32*1024*1024,eT=1024,$i=new TextEncoder,zu=new TextDecoder("utf-8",{fatal:!0});function yn(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Li(e){const t=await globalThis.crypto.subtle.digest("SHA-256",$i.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Rt(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ju(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function tT(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function Vu(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function rT(e,t){const r=e.sandbox.directory(Zp),n=r.directory("revisions"),i=r.directory("entries");for(const x of[r,n,i,i.directory("capability-check")])Vu(x,["directory","file","create","stat","list","remove"]),Vu(x.file("capability-check"),["create","stat","read","write","remove"]);const s=new AbortController,o=()=>s.abort();t.signal.aborted?o():t.signal.addEventListener("abort",o,{once:!0});const c={...t,signal:s.signal};let u=Promise.resolve(),d;function l(x){d=x,s.abort(),t.signal.removeEventListener("abort",o)}function f(x){if(tT(x))throw l(x),x}function h(){if(d)throw d;if(c.signal.aborted)throw yn()}function _(x,Y=c.signal){const j=u.then(()=>{if(Y.aborted)throw d??yn();return h(),x()},()=>{if(Y.aborted)throw d??yn();return h(),x()}).catch(R=>{throw f(R),R});if(u=j.catch(()=>{}),Y.aborted)return Promise.reject(d??yn());let H=()=>{};const F=new Promise((R,q)=>{const D=()=>q(d??yn());Y.addEventListener("abort",D,{once:!0}),H=()=>Y.removeEventListener("abort",D)}),v=setTimeout(()=>{l(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},Xp);return Promise.race([j,F]).finally(()=>{clearTimeout(v),H()})}async function g(){h(),await n.create({recursive:!0,exclusive:!1},c),h(),await i.create({recursive:!0,exclusive:!1},c),h()}async function b(x,Y){const j=n.file(`${await Li([x,Y??null])}.revision`);await y(j);let H=!1;try{await j.create({recursive:!1,exclusive:!0},c),H=!0}catch(R){f(R),h()}if(H){const R=ju();return await j.write($i.encode(R),c),h(),R}const F=await j.stat(c);if(F.size<1||F.size>128)throw new Error("缓存 revision 文件损坏");const v=zu.decode(await j.read(c));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(v))throw new Error("缓存 revision 文件损坏");return h(),v}async function N(x){const Y=await x.list({limit:Fr},c);if(Y.length>=Fr)throw new Error("缓存目录超过治理上限");return Y}async function y(x){try{await x.stat(c);return}catch(j){if(!Pi(j))throw j}if((await N(n)).length>=Fr-1)throw new Error("缓存 metadata 超过治理上限")}async function L(x,Y){await g();const j=[];for(let H=0;H<x.length;H+=1){const F=x.slice(0,H+1);j.push(await b(F),await b(F,Y))}return j}async function A(x){return r.directory(`entries/${await Li([x.namespace,x.codecVersion,x.scopeIds])}`)}async function U(x){return(await A(x)).file(`${await Li(x.key)}.cache`)}async function Q(x,Y){const j=await x.stat(c);if(j.size<5||j.size>Y+Wo+4)throw new Error("缓存条目超过大小限制");const H=await x.read(c);if(h(),H.length!==j.size)throw new Error("缓存条目读取不完整");const F=new DataView(H.buffer,H.byteOffset,H.byteLength).getUint32(0);if(F<1||F>Wo||F+4>H.length)throw new Error("缓存信封损坏");const v=JSON.parse(zu.decode(H.subarray(4,F+4))),R=H.slice(F+4);if(v.envelopeVersion!==1||!v.address||!Array.isArray(v.address.scopeIds)||!v.address.scopeIds.every(q=>typeof q=="string")||typeof v.address.namespace!="string"||typeof v.address.codecVersion!="string"||typeof v.address.key!="string"||!Array.isArray(v.revisions)||v.revisions.length!==v.address.scopeIds.length*2||!v.revisions.every(q=>typeof q=="string"&&q.length>0)||!Number.isSafeInteger(v.cachedAt)||!Number.isSafeInteger(v.expiresAt)||v.cachedAt<0||v.expiresAt<=v.cachedAt||v.payloadBytes!==R.length||R.length>Y)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:v.address,revisions:v.revisions,cachedAt:v.cachedAt,expiresAt:v.expiresAt,payload:R}}async function C(x){if(!x.remove)throw new Error("Host 不支持缓存文件删除");await x.remove(c)}async function P(x){try{if((await x.file.stat(c)).size!==x.size)return!1;const Y=await Q(x.file,bn);return!Rt(Y.address,x.entry.address)||!Rt(Y.revisions,x.entry.revisions)||Y.cachedAt!==x.entry.cachedAt||Y.expiresAt!==x.entry.expiresAt||!Rt(await M(Y.payload),await M(x.entry.payload))?!1:(await C(x.file),!0)}catch(Y){if(Pi(Y))return!0;throw Y}}async function M(x){const Y=await globalThis.crypto.subtle.digest("SHA-256",x);return Array.from(new Uint8Array(Y),j=>j.toString(16).padStart(2,"0")).join("")}async function V(){const x=await N(n);let Y=0;for(const v of x)if(v.kind==="file"&&(Y+=(await v.stat(c)).size,Y>bn))throw new Error("缓存扫描超过字节上限");const j=[];let H=0,F=Y;for(const v of await N(i)){if(v.kind!=="directory")throw new Error("缓存目录结构损坏");for(const R of await N(v)){if(R.kind!=="file"||++H>Jp)throw new Error("缓存文件超过治理上限");const q=(await R.stat(c)).size;if(F+=q,F>bn)throw new Error("缓存扫描超过字节上限");try{const D=await Q(R,bn);j.push({file:R,entry:D,size:(await R.stat(c)).size,bucketName:v.name})}catch(D){f(D),h(),Pi(D)||await C(R)}}}return{entries:j,metadataBytes:Y}}async function z(){for(const x of await N(i))if(x.kind==="directory"&&x.remove&&(await N(x)).length===0)try{await x.remove({recursive:!1},c)}catch(Y){f(Y),h()}}function te(x){const{payload:Y,...j}=x,H=$i.encode(JSON.stringify({...j,payloadBytes:Y.length}));if(H.length>Wo)throw new Error("缓存信封过大");const F=new Uint8Array(4+H.length+Y.length);return new DataView(F.buffer).setUint32(0,H.length),F.set(H,4),F.set(Y,H.length+4),F}return{readRevisions:(x,Y)=>_(()=>L(x,Y)),read:(x,Y)=>_(async()=>{h();const j=await U(x);let H;try{H=await Q(j,Y)}catch(F){if(h(),Pi(F))return;throw F}if(!(!Rt(H.address,x)||H.expiresAt<=Date.now())&&Rt(H.revisions,await L(x.scopeIds,x.namespace)))return H}),publish:(x,Y)=>_(async()=>{h();const{address:j}=x;if(!Rt(x.revisions,await L(j.scopeIds,j.namespace)))return!1;const H=te(x);if(x.payload.length>Y.maxEntryBytes||H.length>Y.diskMaxBytes||Y.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await g();const F=await A(j),v=await U(j),R=await V(),q=[],D=new Map;for(const m of R.entries){if(m.bucketName===F.name&&m.file.name===v.name)continue;const w=JSON.stringify([m.entry.address.scopeIds,m.entry.address.namespace]);let B=D.get(w);if(B||(B=await L(m.entry.address.scopeIds,m.entry.address.namespace),D.set(w,B)),m.entry.expiresAt<=Date.now()||!Rt(m.entry.revisions,B)){if(!await P(m))throw new Error("缓存治理期间条目已变化")}else q.push(m)}q.sort((m,w)=>m.entry.cachedAt-w.entry.cachedAt);function W(){const m=q.filter(w=>w.bucketName===F.name);return q.length+1>eT||H.length+R.metadataBytes+q.reduce((w,B)=>w+B.size,0)>bn||m.length+1>Math.min(Y.diskMaxEntries,Fr-1)||H.length+m.reduce((w,B)=>w+B.size,0)>Y.diskMaxBytes}for(;W();){const m=q.filter(K=>K.bucketName===F.name),B=m.length+1>Math.min(Y.diskMaxEntries,Fr-1)||H.length+m.reduce((K,ce)=>K+ce.size,0)>Y.diskMaxBytes?m[0]:q[0];if(!B||!await P(B))throw new Error("缓存容量不足或条目已变化");q.splice(q.indexOf(B),1)}await z();const $=await N(i);if(!$.some(m=>m.name===F.name)&&$.length>=Fr-1)throw new Error("缓存目录超过治理上限");if(await F.create({recursive:!0,exclusive:!1},c),!Rt(x.revisions,await L(j.scopeIds,j.namespace)))return!1;try{await v.create({recursive:!1,exclusive:!0},c)}catch(m){f(m),await v.stat(c)}return await v.write(H,c),h(),Rt(x.revisions,await L(j.scopeIds,j.namespace))}),invalidate:(x,Y)=>_(async()=>{await g();const j=n.file(`${await Li([x,Y??null])}.revision`);await y(j);try{await j.create({recursive:!1,exclusive:!0},c)}catch(H){f(H),await j.stat(c)}await j.write($i.encode(ju()),c),h();try{const{entries:H}=await V();for(const F of H){if(Y!==void 0&&F.entry.address.namespace!==Y||!x.every((R,q)=>F.entry.address.scopeIds[q]===R))continue;const v=await L(F.entry.address.scopeIds,F.entry.address.namespace);Rt(F.entry.revisions,v)||await P(F)}await z()}catch(H){f(H),h()}})}}function Pi(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const nT="RATE_LIMITED_BY_RUNTIME",iT="RATE_LIMITED",vf=20,kf=40,xf=150,Uf=20,Bf=1e4,Hf=45e3,Ff=1,sT=300*1e3,oT=64;function zr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function aT(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function cT(e={}){const t=e.now??Date.now,r=aT(e.coalesceWindowMs,xf),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,zr(e.budget?.ratePerSecond,vf)),burst:Math.max(1,Math.floor(zr(e.budget?.burst,kf)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(zr(e.loopDetection?.maxCalls,Uf))),windowMs:Math.max(1,Math.floor(zr(e.loopDetection?.windowMs,Bf)))},s=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(zr(e.circuitBreaker?.failureThreshold,Ff))),openMs:Math.max(1,Math.floor(zr(e.circuitBreaker?.openMs,Hf)))},o=new Map,c=new Map,u=new Set,d=new Map,l=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},f={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let h=!1;function _(P){try{e.onReport?.(P)}catch{}}function g(P,M){if(!i)return{exceeded:!1,count:0};const V=c.get(P)??[],z=M-i.windowMs;let te=0;for(;te<V.length&&V[te]<=z;)te+=1;te>0&&V.splice(0,te);const x=V.length>=i.maxCalls;return x||(V.push(M),V.length>i.maxCalls+1&&V.splice(0,V.length-(i.maxCalls+1))),c.set(P,V),{exceeded:x,count:V.length}}function b(P){if(!n)return!0;const M=Math.max(0,P-l.updatedAt)/1e3;return l.tokens=Math.min(n.burst,l.tokens+M*n.ratePerSecond),l.updatedAt=P,l.tokens<1?!1:(l.tokens-=1,!0)}function N(P){if(!n)return 0;const M=Math.max(0,P-l.updatedAt)/1e3,V=Math.min(n.burst,l.tokens+M*n.ratePerSecond);return Math.max(0,Math.ceil((1-V)/n.ratePerSecond*1e3))}function y(P,M,V,z,te){if(!s)return;const x=d.get(M),Y=(x?.open?0:x?.failures??0)+1;if(Y<s.failureThreshold){d.set(M,{open:!1,openedAt:0,openMs:0,failures:Y});return}const j=Math.min(Math.max(s.openMs,z),sT);d.set(M,{open:!0,openedAt:te,openMs:j,failures:Y}),f.circuitOpened+=1,_({type:"circuit_opened",capability:P,endpointId:M,status:V,openMs:j,timestamp:te})}function L(P){const M=d.get(P);M&&!M.open&&d.delete(P)}function A(P){for(const[M,V]of o)!V.pending&&V.expiresAt<=P&&o.delete(M);for(;o.size>=oT;){const M=[...o].find(([,V])=>!V.pending);if(!M)break;o.delete(M[0])}}function U(P,M){if(P===void 0)return;const V=o.get(P);V?.promise===M&&(V.pending=!1)}function Q(P,M){if(P===void 0)return;o.get(P)?.promise===M&&o.delete(P)}async function C(P){if(h)return P.load();const M=t();if(s){const x=d.get(P.endpointId);if(x?.open){const Y=x.openedAt+x.openMs-M;if(Y>0)throw f.circuitRejected+=1,_({type:"circuit_rejected",capability:P.capability,endpointId:P.endpointId,retryAfterMs:Y,timestamp:M}),lT("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:P.endpointId,retryAfterMs:Y});d.delete(P.endpointId)}}const V=g(P.endpointId,M);V.exceeded&&i?u.has(P.endpointId)||(u.add(P.endpointId),_({type:"loop_detected",capability:P.capability,endpointId:P.endpointId,count:V.count,windowMs:i.windowMs,timestamp:M})):u.delete(P.endpointId);const z=r>0?P.coalesceKey:void 0;if(z!==void 0){const x=o.get(z);if(x&&(x.pending||x.expiresAt>M))return f.coalesced+=1,_({type:"coalesced",capability:P.capability,endpointId:P.endpointId,timestamp:M}),x.promise;x&&o.delete(z)}if(V.exceeded&&i)throw f.loopRejected+=1,Gu("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:P.capability,endpointId:P.endpointId,count:V.count,windowMs:i.windowMs});if(!b(M)){f.budgetRejected+=1;const x=N(M);throw _({type:"budget_exhausted",capability:P.capability,endpointId:P.endpointId,retryAfterMs:x,timestamp:M}),Gu("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:P.capability,endpointId:P.endpointId,retryAfterMs:x})}z!==void 0&&A(M);const te=P.load().then(x=>(U(z,te),L(P.endpointId),x),x=>{Q(z,te);const Y=uT(x);throw Y!==void 0&&y(P.capability,P.endpointId,Y,dT(x),M),x});return z!==void 0&&o.set(z,{endpointId:P.endpointId,promise:te,expiresAt:M+r,pending:!0}),te}return{execute:C,invalidateCoalescing(P){if(P===void 0){o.clear();return}for(const[M,V]of o)P.includes(V.endpointId)&&o.delete(M)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,P])=>P.open).map(([P])=>P)}},dispose(){h||(h=!0,o.clear(),c.clear(),u.clear(),d.clear())}}}function uT(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 dT(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 Gu(e,t){return{code:nT,message:e,data:t}}function lT(e,t){return{code:iT,message:e,data:t}}const zf=3e4,jf=6e4,Sa=1440*60*1e3;function fT(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??zf)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??jf)):0,steamGameListTtlMs:t?hT(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:vf,burst:kf},coalesceWindowMs:r?.coalesceWindowMs??xf,loopDetection:r?.loopDetection??{maxCalls:Uf,windowMs:Bf},circuitBreaker:r?.circuitBreaker??{failureThreshold:Ff,openMs:Hf}}}}function hT(e){return e===void 0||!Number.isFinite(e)?Sa:Math.max(0,Math.floor(e))}function Vf(e){return typeof e=="object"&&e!==null}function Gf(e,t){const r=e.data;if(!Vf(r))throw new Error(t);if(r.status!=="ok")throw new Error(typeof r.msg=="string"&&r.msg?r.msg:t);return r.result}function Ue(e,t){const r=e.data;if(!Vf(r)||typeof r.status!="string")throw new Error(t);return r}const Yf={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},mT={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 Ue(e,"工坊小程序详情加载失败")}};function Ti(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function ET(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function gT(e){const t=Ue(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=ET(r.consent_challenge)),{...t,result:n}}const pT={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=>({...Ti(e.runtimeContext),challenge:e.challenge}),parse:e=>Ue(e,"小程序授权取消接口响应异常")},TT={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=>Ti(e.runtimeContext),parse:e=>Ue(e,"小程序授权撤销接口响应异常")},_T={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=>Ti(e.runtimeContext),parse(e){const t=Ue(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}:{}}}}},AT={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=>({...Ti(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>gT(e)},IT={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=>({...Ti(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=Ue(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},bT=64;function Qf(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??bT)),n=e.now??Date.now,i=new Map,s=new Map;let o=0,c=!1;function u(f){for(const[h,_]of i)_.expiresAt<=f&&i.delete(h)}function d(f,h,_){if(c||t<=0||_!==o)return;const g=n();for(u(g),i.delete(f);i.size>=r;){const b=i.keys().next();if(b.done)break;i.delete(b.value)}i.set(f,{expiresAt:g+t,value:h})}function l(f,h){if(c)return h();if(t>0){const N=i.get(f);if(N&&N.expiresAt>n())return Promise.resolve(N.value);N&&i.delete(f)}const _=s.get(f);if(_)return _;const g=o,b=h().then(N=>(d(f,N,g),N)).finally(()=>{s.get(f)===b&&s.delete(f)});return s.set(f,b),b}return{read:l,invalidate(){o+=1,i.clear(),s.clear()},dispose(){c||(c=!0,o+=1,i.clear(),s.clear())},get size(){return i.size}}}function yT(e,t){return t?e?"server":"local":"legacy"}function NT(e,t){if(e==="local")throw p("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const wT=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],DT=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),ST=/authorization|cookie|pkey|password|secret|token/i,qf=/authorization|cookie|pkey|token|password|secret/i;function Lt(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function OT(e){for(const t of Object.keys(e))if(!DT.has(t))throw new qe(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of wT)if(Object.prototype.hasOwnProperty.call(e,t)&&Lt(e,t)!==void 0)throw new qe(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Lt(e,"bodyEncoding")!==void 0&&Lt(e,"bodyEncoding")!=="json"&&Lt(e,"bodyEncoding")!=="form")throw new qe("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Lt(e,"failurePresentation")!==void 0&&Lt(e,"failurePresentation")!=="none")throw new qe("endpoint failurePresentation 必须为 none");if(Lt(e,"auth")!==void 0&&Lt(e,"auth")!=="none"&&Lt(e,"auth")!=="optional"&&Lt(e,"auth")!=="required")throw new qe("endpoint auth 必须为 none、optional 或 required")}function qs(e){if(Array.isArray(e))return e.map(qs);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))ST.test(n)||(r[n]=qs(i));return r}function Yu(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))qf.test(r)||(t[r]=n);return t}function MT(e){if(!e)return;const t=Object.keys(e).find(r=>qf.test(r));if(t)throw new qe(`endpoint 禁止声明 credential-bearing header: ${t}`)}class _i 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,Object.defineProperty(this,"responseData",{value:t.responseData,enumerable:!1}),t.retryAfterMs!==void 0&&(this.retryAfterMs=t.retryAfterMs),Object.setPrototypeOf(this,new.target.prototype)}}const Qu=1440*60*1e3,CT=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function RT(e,t=Date.now){if(!e)return;const r=Object.entries(e).find(([o])=>o.trim().toLowerCase()==="retry-after")?.[1];if(typeof r!="string"||!r.trim())return;const n=r.trim();if(/^\d+$/.test(n)){const o=Number(n)*1e3;return o>0?Math.min(o,Qu):void 0}if(!CT.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const s=i-t();return s>0?Math.min(s,Qu):void 0}function LT(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 Wf(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class on extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Wf(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Ai extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Wf(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function PT(e,t,r,n,i,s,o,c){return{config:{auth:e.auth,body:qs(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:o.credentials,headers:Yu(s),method:e.method,metadata:{endpointId:e.id},query:qs(n),timeout:e.timeout,url:r},data:c.data,headers:Yu(c.headers)||{},status:c.status,statusText:c.statusText}}async function Do(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(OT(t),typeof t.id!="string"||!t.id)throw new qe("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new qe("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new qe("endpoint path 必须为非空字符串");const s=t.query?await t.query(r):void 0,o=t.body?await t.body(r):void 0,c=t.headers?await t.headers(r):void 0;MT(c);const u=async()=>{let f;try{f=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,...s===void 0?{}:{params:s},...o===void 0?{}:{data:o},...c===void 0?{}:{headers:c},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(_){throw _ instanceof qe?_:new on({endpointId:t.id,cause:_})}if(f.status<200||f.status>=300)throw new _i({endpointId:t.id,status:f.status,responseData:f.data,retryAfterMs:RT(f.headers)});const h=PT(t,r,i,s,o,c,n,f);if(t.parse)try{return await t.parse(h,r)}catch(_){throw new Ai({endpointId:t.id,cause:_})}return h.data},d=n.gate;if(!d)return u();const l=LT(t,s,o,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...l===void 0?{}:{coalesceKey:l},load:u})}const vT=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),kT=new Set(nn),Uc="steam_account",$f=new Set(nn.filter(e=>e!==Uc)),xT=1e3;function UT(e){const t=new Set,r=Qf({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??zf))}),n=new Set;let i=0,s=!1,o=Promise.resolve(),c;const u=e.steamAccount===!0,d=e.userDataMode??yT(e.networkEnabled===!0,u),l=e.requestPolicyEnabled!==!1,f=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function h(){if(!u&&!e.authorizationContext)return{};if(!e.authorizationContext)throw p("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let R;try{R=await e.authorizationContext.get(e.operationContext)}catch(D){throw Ma(D)?$o(D.code,D.message,D):$o("REQUEST_FAILED","读取 Runtime auth context 失败",D)}if(R.steamAccount!==u||R.userDataMode!==d)throw p("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const q=R.token.trim();if(!q)throw p("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:q}}const _=e.account.onChange(R=>{if(g(),b("heybox_app_login_change",R?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),R&&e.account.getAccountKey){const q=i;Q().then(D=>{!s&&i===q&&b("heybox_app_login_change",D)}).catch(()=>{})}});function g(){i+=1,c?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function b(R,q){R==="user_info_authorization_change"&&VT(q)&&r.invalidate();for(const D of t)try{D(R,q)}catch{}}function N(){const R=e.identity.get()?.miniProgramId?.trim();if(!R)throw p("INVALID_STATE","当前能力缺少 canonical 小程序身份");return R}function y(){if(s||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function L(){y();let R;try{R=await e.account.getCurrentUserId(e.operationContext)}catch(q){throw Ku(q,e.operationContext.signal,"读取小黑盒账号失败")}return typeof R=="string"&&R.trim()?R.trim():void 0}async function A(R,q){const D=await L();if(i!==q||D!==R)throw p("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function U(R,q,D=N()){if(!e.account.getAccountKey)throw p("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let W;try{W=await e.account.getAccountKey(D,R,e.operationContext)}catch{throw y(),p("REQUEST_FAILED","读取本地账号标识失败")}if(await A(R,q),N()!==D)throw p("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof W!="string"||!W.trim())throw p("INVALID_RESPONSE","Host 返回了无效的账号标识");return W}async function Q(){const R=N(),q=i,D=await L();if(y(),i!==q)throw p("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return D?{isHeyboxAppLoggedIn:!0,accountKey:await U(D,q,R)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function C(R){y();try{await e.account.ensureAuthenticated({trustedUserGesture:R,reason:"runtime_auth",signal:e.operationContext.signal})}catch(D){throw Ku(D,e.operationContext.signal,"小黑盒登录失败")}const q=await L();if(!q)throw p("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return q}async function P(R,q,D=e.operationContext.signal){try{if(D.aborted)throw Oa();return await jT(Do(e.network,R,q,{...e.operationContext,credentials:"heybox-session",signal:D,...f?{gate:f}:{}}),D)}catch(W){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):W instanceof qe?p("REQUEST_UNSUPPORTED",W.message):W instanceof Ai?p("INVALID_RESPONSE","授权接口响应不合法"):W instanceof on?p("REQUEST_FAILED","授权请求失败"):W instanceof _i?l&&(W.status===403||W.status===429)?p("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:W.status,...W.retryAfterMs===void 0?{}:{retryAfterMs:W.retryAfterMs}}):p("REQUEST_FAILED",W.message):Ma(W)?W:p("REQUEST_FAILED","授权请求失败")}}async function M(R,q){await P(pT,{runtimeContext:{miniProgramId:R,...await h()},challenge:q}).catch(()=>{})}function V(R){const q=async()=>{const W=Wu(e.operationContext.signal);c=W;try{return await R(W.signal)}finally{c===W&&(c=void 0),W.abort()}},D=o.then(q,q);return o=D.then(()=>{},()=>{}),D}async function z(R,q,D,W,$){if(!D)throw await M(R,q.challenge),p("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await M(R,q.challenge),p("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return V(async m=>{await A(W,$);const w=await te(R,q.displayedScopes,m);await A(W,$);let B;try{B=await e.authPresentation.confirmAuthorization({miniProgramId:R,scopes:q.displayedScopes,...w,signal:m})}catch(ce){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await A(W,$),await M(R,q.challenge),$o("REQUEST_FAILED","授权确认界面执行失败",ce))}if(await A(W,$),B.status!=="granted")throw await M(R,q.challenge),p("AUTHORIZATION_CANCELLED","用户取消授权");const K=FT(B.grantedScopes,q.displayedScopes,u);if(!K.includes("identity"))throw await M(R,q.challenge),p("AUTHORIZATION_CANCELLED","用户拒绝授权");return K})}async function te(R,q,D){const W=Wu(D),$=setTimeout(()=>W.abort(),xT);try{const m=zT(e.miniProgramPresentation),[w,B]=await Promise.all([m?Promise.resolve(m):x(R,W.signal),q.includes("profile")?Y(W.signal):Promise.resolve(void 0)]);return{...w?{miniProgram:w}:{},...B?{userProfile:B}:{}}}finally{clearTimeout($),W.abort()}}async function x(R,q){try{const D=e.identity.get()?.version?.trim(),W=await P(mT,{mini_program_id:R,...D?{miniprogram_version:D}:{}},q),$=jr(W,"小程序公开资料"),m=$r($.name),w=$r($.icon_url);return m||w?{...m?{name:m}:{},...w?{avatarUrl:w}:{}}:void 0}catch{return}}async function Y(R){try{const q=await P(Yf,void 0,R),D=jr(q,"账号基础信息"),W=$r(D.display_username),$=$r(D.display_avatar);return W||$?{...W?{nickname:W}:{},...$?{avatar:$}:{}}:void 0}catch{return}}async function j(R,q){if(NT(d,"auth.login"),!u&&R.includes(Uc))throw p("INVALID_PARAMS","auth.login 参数不合法");const D=N(),W=await C(q),$=i,m=await P(AT,{runtimeContext:{miniProgramId:D,...await h()},scopes:R});await A(W,$);const w=jr(m,"小程序登录"),B=$u(w,"loginCode"),K=$u(w,"consentChallenge");if(B===K)throw p("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let ce;if(B)ce=qu(w.loginCode,u);else{const ue=BT(w.consentChallenge,u),Te=await z(D,ue,q,W,$);await A(W,$);const we=await P(IT,{runtimeContext:{miniProgramId:D,...await h()},challenge:ue.challenge,selectedScopes:Te});if(await A(W,$),ce=qu(jr(we,"小程序登录确认"),u),ce.scopes.some(Ae=>!Te.includes(Ae)))throw p("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ue of ce.scopes)n.add(ue);r.invalidate();const pe=e.account.getAccountKey?await U(W,$,D):void 0;return b("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...pe===void 0?{}:{accountKey:pe}}),b("user_info_authorization_change",Ko(n,u)),{...ce,...pe===void 0?{}:{accountKey:pe}}}async function H(R,q){const D=i,W=await P(_T,{runtimeContext:{miniProgramId:q,...await h()}});await A(R,D);const $=HT(jr(W,"用户本地身份"),u);for(const m of u?nn:$f)n.add(m);return b("user_info_authorization_change",Ko(n,u)),$}function F(R){y();const q=N(),D=`${R}\0${q}\0${i}\0${u}`;return r.read(D,()=>H(R,q))}async function v(R){if(!R)throw p("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const q=N(),D=i,W=await L();if(!W)throw p("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const $=await P(TT,{runtimeContext:{miniProgramId:q,...await h()}});await A(W,D),jr($,"用户授权撤销"),g(),b("user_info_authorization_change",{identity:"denied",profile:"denied",...u?{steam_account:"denied"}:{}})}return{getAccountState:Q,login:j,async confirmGameSaves(R){if(!R)throw p("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw p("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const q=N(),D=await C(R),W=i;await V(async $=>{await A(D,W);const m=await te(q,["identity"],$),w=await e.authPresentation.confirmAuthorization({miniProgramId:q,scopes:["identity","game_saves"],...m,signal:$});if(await A(D,W),w.status!=="granted"||!w.grantedScopes.includes("game_saves")||!w.grantedScopes.includes("identity"))throw p("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:F,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Ko(n,u),revoke:v,onEvent(R){return t.add(R),()=>t.delete(R)},dispose(){s||(s=!0,g(),r.dispose(),_(),t.clear())}}}function $o(e,t,r){const n=p(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function jr(e,t){if(!le(e))throw p("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":vT.has(r)?r:"REQUEST_FAILED";throw p(n,r)}if(!le(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function qu(e,t){if(!le(e))throw p("INVALID_RESPONSE","login code 必须是对象");const r=Ws(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 p("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function BT(e,t){if(!le(e))throw p("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Ws(e.requestedScopes,"challenge requestedScopes",t),n=Ws(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 p("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function HT(e,t){if(!le(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw p("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw p("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 FT(e,t,r){const n=Ws(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw p("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function $r(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function zT(e){const t=$r(e?.name),r=$r(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Wu(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 jT(e,t){return t.aborted?Promise.reject(Oa()):new Promise((r,n)=>{let i=!1;const s=c=>{i||(i=!0,t.removeEventListener("abort",o),c())},o=()=>s(()=>n(Oa()));t.addEventListener("abort",o,{once:!0}),e.then(c=>s(()=>r(c)),c=>s(()=>n(c)))})}function Oa(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Ws(e,t,r){const n=r?kT:$f;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw p("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Ko(e,t){const r=t?nn:nn.filter(n=>n!==Uc);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function $u(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function VT(e){return le(e)?Object.values(e).some(t=>t==="denied"):!1}function Ma(e){return le(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Ku(e,t,r){return t.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Ma(e)?e:p("REQUEST_FAILED",r)}const GT=new Set(nn);function YT(e){return{[ls]:async t=>{if(t!==void 0)throw p("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[fs]:async(t,r)=>e.authorization.login(QT(t),r.trustedUserGesture)}}function QT(e){if(e===void 0)return["identity"];if(!le(e)||Object.keys(e).some(t=>t!=="scopes"))throw Zu();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!GT.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Zu();return[...e.scopes]}function Zu(){return p("INVALID_PARAMS","auth.login 参数不合法")}const qT={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 Ue(e,"排行榜记录删除接口响应异常")}},WT={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 Ue(e,"当前排行榜记录接口响应异常")}},$T={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 Ue(e,"排行榜信息接口响应异常")}},KT={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 Ue(e,"排行榜列表接口响应异常")}},ZT={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 Ue(e,"排行榜提交接口响应异常")}},XT={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 Ii(e,t,r){e.assertUsable();const n={request:async(i,s)=>(e.assertUsable(),e.network.request(i,s))};try{return await be(()=>Do(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(Zs(i)||Pn(i,"REQUEST_UNSUPPORTED")||Pn(i,"RATE_LIMITED")||Pn(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof qe)throw ne("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof on&&Pn(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof _i){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw ne("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw ne("UNAUTHORIZED","当前用户未登录");const s=JT(i.responseData);if(Se(s)&&typeof s.status=="string"&&s.status!=="ok"){const o=Se(s.result)?Yt(s.result.error_code):void 0;if(s.status==="login"||s.status==="relogin"||$s(s.result)||$s(s)||o&&/^[A-Z][A-Z0-9_]+$/.test(o))throw Kf(s,e.subject)}throw ne("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof on?Ks(e.subject):i instanceof Ai?Ne(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):Ne(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function Je(e,t,r){if(!Se(e)||typeof e.status!="string")throw Ne(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Kf(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw Ne(`${t} 响应缺少 result`);return e.result}function bi(e,t){try{return e.onChange(t)}catch(r){if(Pn(r,mf))return()=>{};throw r}}function Kf(e,t){if(e.status==="login"||e.status==="relogin")throw ne("UNAUTHORIZED",Yt(e.msg)||"当前用户未登录");if(Se(e.result)){const i=Yt(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw ne(i,Yt(e.result.message)||Yt(e.msg)||`${t}请求失败`)}const r=$s(e.result)??$s(e),n=Yt(r?.user_message)||Yt(e.msg)||Yt(r?.developer_message)||`${t}请求失败`;throw r?ne(e_(r),n,{status:e.status,sbe:r}):ne("HEYBOX_API_ERROR",n,{status:e.status})}function JT(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function $s(e){return Se(e)&&Se(e.sbe)?e.sbe:void 0}function e_(e){const t=Yt(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 XT[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 Se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Pn(e,t){return Se(e)&&e.code===t}function ne(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function Ne(e){return ne("INVALID_RESPONSE",e)}function Ks(e){return ne("REQUEST_FAILED",`${e}请求失败`)}function Zs(e){return e instanceof Error&&e.name==="AbortError"}const t_="default",mr="排行榜",r_=/^[A-Za-z0-9_-]{1,64}$/,n_=300*1e3,i_=250,s_=3;class o_{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=bi(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(ZT,{miniProgramId:n,...t});this.assertAccountGeneration(r);const s=Je(i,Wt,mr);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),Zo(s,Wt)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Nn("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const s=await this.request(KT,{miniProgramId:r,...t}),o=Je(s,wt,mr);if(!Se(o)||!Array.isArray(o.entries)||typeof o.has_more!="boolean")throw Ne(`${wt} 返回值不合法`);if(o.cursor!==void 0&&o.cursor!==null&&typeof o.cursor!="string")throw Ne(`${wt} 返回的 cursor 必须是字符串`);return{entries:o.entries.map(c=>Zo(c,wt)),...typeof o.cursor=="string"&&o.cursor?{cursor:o.cursor}:{},hasMore:o.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId(),i=await this.requireCurrentUser(r),s=this.createBucketKey(n,t.key),o=Nn("current",i);return this.read(s,"current",o,async()=>{const c=await this.request(WT,{miniProgramId:n,...t}),u=Je(c,ar,mr);if(!Se(u))throw Ne(`${ar} 返回值必须是对象`);return u.entry===void 0||u.entry===null?void 0:Zo(u.entry,ar)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(qT,{miniProgramId:n,...t});this.assertAccountGeneration(r);const s=Je(i,Rr,mr);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Se(s)||typeof s.deleted!="boolean")throw Ne(`${Rr} 返回的 deleted 必须是布尔值`);return{deleted:s.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Nn("info"),async()=>{const i=await this.request($T,{miniProgramId:r,...t}),s=Je(i,Ut,mr);if(!Se(s)||typeof s.key!="string"||!r_.test(s.key))throw Ne(`${Ut} 返回的 key 不合法`);if(t.key!==void 0&&s.key!==t.key)throw Ne(`${Ut} 返回的 key 与请求不一致`);if(s.order!=="asc"&&s.order!=="desc")throw Ne(`${Ut} 返回的 order 必须是 asc 或 desc`);if(typeof s.rank_limit!="number"||!Number.isInteger(s.rank_limit)||s.rank_limit<0)throw Ne(`${Ut} 返回的 rankLimit 必须是非负整数`);return{key:s.key,order:s.order,rankLimit:s.rank_limit}})}read(t,r,n,i){this.assertUsable();const s=this.getOrCreateBucket(t),o=s?.caches[r],c=o?.get(n);if(c&&c.expiresAt>Date.now())return Promise.resolve(c.value);o?.delete(n);const u=Nn(t,n),d=this.inflight.get(u);if(d)return d.promise;const l=this.accountGeneration,f=s?.generation,h=i().then(_=>(this.assertAccountGeneration(l),s&&o&&s.generation===f&&(r==="list"?o.size>=i_&&o.delete(o.keys().next().value):o.clear(),o.set(n,{expiresAt:Date.now()+n_,value:_})),_)).finally(()=>{this.inflight.get(u)?.promise===h&&this.inflight.delete(u),s&&this.removeEmptyBucket(t,s)});return this.inflight.set(u,{bucketKey:t,promise:h}),h}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=s_)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)Xu(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){Xu(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 be(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw Zs(n)?n:Ks(mr)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ne("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ne("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Nn(t,r??t_)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ne("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return Ii({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:mr,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(Oe(this.options.operationContext.signal),this.disposed)throw ne("INVALID_STATE","Cloud capability 已释放")}}function a_(e){return new o_(e)}function Zo(e,t){if(!Se(e))throw Ne(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw Ne(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw Ne(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw Ne(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw Ne(`${t} 返回的 score 必须是有限数字`);if(!Se(e.extra))throw Ne(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw Ne(`${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 Xu(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Nn(...e){return JSON.stringify(e)}const c_={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 Ue(e,"云端存储删除接口响应异常")}},Ju={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 Ue(e,"云端存储读取接口响应异常")}},ed={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 Ue(e,"云端存储 key 列表接口响应异常")}},u_={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:String(e.expectedVersion),expected_revision:e.expectedRevision}},parse(e,t){return Ue(e,"云端存储写入接口响应异常")}},Er="云端存储",d_=3e4,l_=128,f_=500;class h_{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=bi(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(o=>o.key===t).at(-1);if(n)return n.kind==="set"?n.value:void 0;const i=this.keyGenerations.get(t)??0,s=await this.readStored(t,r,!1);return this.assertAccountGeneration(r),(this.keyGenerations.get(t)??0)!==i?this.getItem(t):(this.blockedKeys.delete(t),s.found?s.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=Je(await this.request(ed,{}),Lr,Er);if(this.assertAccountGeneration(t),!Se(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw Ne("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((s,o)=>{const c=this.queues.get(r)??[],u=c.at(-1);if(t==="set"&&u?.kind==="set"&&u.generation===this.accountGeneration&&u.readyAt>Date.now())u.value=n,u.waiters.push({resolve:s,reject:o});else{const d={kind:t,key:r,value:n,generation:this.accountGeneration,readyAt:Date.now()+(t==="set"?f_:0),waiters:[{resolve:s,reject:o}]};c.push(d),this.unfinished.add(d)}this.queues.set(r,c),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=Je(await this.request(c_,{key:t}),rn,Er);if(this.assertAccountGeneration(r.generation),!Se(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw Ne("删除结果不合法");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 Ne("云存储版本超出安全整数范围");const s=Je(await this.request(u_,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),tn,Er);if(this.assertAccountGeneration(r.generation),!Se(s)||s.success!==!0)throw Ne("云存储写入结果不合法");const o=td({...s,found:!0,value:r.value});if(o.version!==i.version+1||i.found&&o.revision!==i.revision)throw Ne("写入版本凭证不匹配");this.writeCache(t,o)}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 s of this.queues.get(t)??[])this.finish(s,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 s=this.inflight.get(t);if(s)return s;const o=this.keyGenerations.get(t)??0,c=this.request(Ju,{key:t}).then(u=>{this.assertAccountGeneration(r);const d=td(Je(u,en,Er));return(this.keyGenerations.get(t)??0)===o&&this.writeCache(t,d),d}).finally(()=>{this.inflight.get(t)===c&&this.inflight.delete(t)});return this.inflight.set(t,c),c}writeCache(t,r){this.cache.delete(t),this.cache.size>=l_&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+d_,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([Ju.id,ed.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(ne("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(ne("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 be(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw Zs(s)?s:Ks(Er)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),ne("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),ne("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw ne("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ne("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ne("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw ne("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await be(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw Zs(o)?o:Ks(Er)}this.assertAccountGeneration(n);const s=i.token.trim();if(!s||i.expiresAt<=Date.now())throw ne("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return Ii({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Er,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:s})}assertUsable(){if(Oe(this.options.operationContext.signal),this.disposed)throw ne("INVALID_STATE","Cloud capability 已释放")}}function m_(e){return new h_(e)}function td(e){if(!Se(e))throw Ne("云存储读取结果必须是对象");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 Ne("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw Ne("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const E_=/^[A-Za-z0-9_-]{1,64}$/,rd=20,g_=100,nd=2048,p_=/^[A-Za-z0-9_-]{1,128}$/,id=16*1024;function T_(e){const t=a_(e),r=m_(e);return{handlers:{[Wt]:async i=>t.submit(__(i)),[wt]:async i=>t.getList(A_(i)),[ar]:async i=>t.getCurrentUserEntry(Xo(i,ar)),[Rr]:async i=>t.deleteCurrentUserEntry(Xo(i,Rr)),[Ut]:async i=>t.getInfo(Xo(i,Ut)),[en]:async i=>r.getItem(sd(i,en)),[tn]:async i=>{const{key:s,value:o}=I_(i);return r.setItem(s,o)},[rn]:async i=>r.removeItem(sd(i,rn)),[Lr]:async i=>(y_(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function __(e){const t=Tn(e,Wt,!1);if(_n(t,["key","score","extra"],Wt),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw dt("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Bc(t.key,Wt),score:t.score,...t.extra===void 0?{}:{extra:N_(t.extra)}}}function A_(e){if(e===void 0)return{limit:rd};const t=Tn(e,wt,!0);_n(t,["key","limit","cursor"],wt);const r=t.limit===void 0?rd:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>g_)throw dt("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw dt("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Bc(t.key,wt),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Xo(e,t){if(e===void 0)return{};const r=Tn(e,t,!0);return _n(r,["key"],t),Bc(r.key,t)}function sd(e,t){const r=Tn(e,t,!1);return _n(r,["key"],t),Zf(r.key,t)}function I_(e){const t=tn,r=Tn(e,t,!1);_n(r,["key","value"],t);const n=Zf(r.key,t);if(typeof r.value!="string")throw dt("INVALID_PARAMS",`${t} value 必须是字符串`);if(b_(r.value))throw dt("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>id)throw dt("INVALID_PARAMS",`${t} value 不能超过 ${id} 字节`);return{key:n,value:r.value}}function b_(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=55296&&r<=56319){const n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return!0;t++}else if(r>=56320&&r<=57343)return!0}return!1}function y_(e){const t=Tn(e,Lr,!0);_n(t,[],Lr)}function Zf(e,t){if(typeof e!="string"||!p_.test(e))throw dt("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function Tn(e,t,r){if(e===void 0&&r)return{};if(!Xf(e))throw dt("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function _n(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw dt("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Bc(e,t){if(e===void 0)return{};if(typeof e!="string"||!E_.test(e))throw dt("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function N_(e){if(!Xf(e))throw dt("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw dt("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw dt("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>nd)throw dt("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${nd} 字节`);return e}function Xf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dt(e,t){return{code:e,message:t}}const w_={auth:"optional",channel:"api",id:"heybox.user_miniprogram.runtime.game_saves.post",method:"POST",path:"/user_miniprogram/runtime/game_saves",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return Ue(e,"游戏存档接口响应异常")}},D_=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function Ca(e,t=0){return t>64?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e)&&(!Number.isInteger(e)||Number.isSafeInteger(e)):Array.isArray(e)?e.every(r=>Ca(r,t+1)):Se(e)&&Object.values(e).every(r=>Ca(r,t+1))}function S_(e,t){const r=D_.get(t);if(!r||Se(e)&&e.status==="unsupported")return{status:"unsupported"};if(Se(e)&&e.game===r){if(e.status==="empty")return{status:"empty"};if(e.status==="failed"&&["UNAUTHORIZED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED"].includes(String(e.error_code)))throw ne(String(e.error_code),"账号或授权已变化");if(e.status==="ready"&&Se(e.data)&&Ca(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function Jf(e){const t=new Map,r=new Map,n=u=>u.resource?`hb_runtime_game_save_resource_sync_v1_${[u.miniProgramId,u.userId,u.resource].map(encodeURIComponent).join(":")}`:`hb_runtime_game_save_sync_v1_${[u.miniProgramId,u.userId,u.gameId].map(encodeURIComponent).join(":")}`;async function i(u,d,l){const f=n(u),h=r.get(f)??Promise.resolve();let _;const g=new Promise(N=>{_=N}),b=h.then(()=>g);r.set(f,b);try{return await be(()=>h,d.signal),Oe(d.signal),e?.withLock?await e.withLock(f,l):await l()}finally{_(),r.get(f)===b&&b.then(()=>{r.get(f)===b&&r.delete(f)})}}async function s(u,d,l=!1){const f=n(u);if(!l&&t.has(f)||!e)return t.get(f);try{const h=await be(()=>e.getRaw(f,d),d.signal);if(!h)return;const _=JSON.parse(h);if(!_||typeof _!="object")return;const g=_;return g.version!==1||g.miniProgramId!==u.miniProgramId||g.userId!==u.userId||g.gameId!==u.gameId||(u.resource?g.resource!==u.resource:typeof g.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(g.accountId))||typeof g.taskId!="string"||(u.resource?g.taskId.length<1||g.taskId.length>128:!/^[1-9][0-9]{0,19}$/.test(g.taskId))?void 0:(l||t.set(f,g),g)}catch(h){if(Oe(d.signal),l)throw h;return t.get(f)}}async function o(u,d,l){Oe(l.signal);const f=n(u),h=d?{...u,version:1,taskId:d}:void 0;if(t.set(f,h),!!e)try{await be(()=>e.setRaw(f,h?JSON.stringify(h):"",l),l.signal)}catch{Oe(l.signal)}}async function c(u,d,l){await i(u,l,async()=>{const f=n(u),h=t.get(f),_=h?.taskId===d&&h.accountId===u.accountId;let g;try{g=await s(u,l,!0)}catch{Oe(l.signal),_&&t.set(f,void 0);return}g?.taskId===d&&g.accountId===u.accountId?(await o(u,void 0,l),h&&!_&&t.set(f,h)):_&&t.set(f,g)})}return{run:i,async get(u,d){const l=await s(u,d);if(l&&l.accountId!==u.accountId){t.delete(n(u));return}return l?.taskId},set:o,remove:c,clear(u){for(const d of t.values())d&&c(d,d.taskId,u).catch(()=>{})}}}const O_=2e3,M_=5*6e4;function C_(e){const t=Jf(e.storage);let r=0,n=!1,i;const s=e.fileDownloads??(e.files&&e.transfer?kc({files:e.files,transfer:e.transfer,registry:e.fileRegistry,signal:e.operationContext.signal}):void 0),o=new Set,c=new Map,u={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},d=M=>s?.release(M)??Promise.resolve(),l=new Set;let f=new AbortController,h;const _=()=>{f.abort(),f=new AbortController,h=void 0},g=(M=!0)=>{M&&t.clear(u),r++,_();for(const V of l)V.abort();for(const V of o)d(V).catch(()=>{});o.clear(),c.clear()},b=bi(e.account,M=>{i&&M!==i&&(g(),i=void 0)}),N=e.authorization.onEvent(()=>g());function y(M,V,z,te){if(L(z),te.signal.aborted||!M.account_id||!e.presentation?.showSteamLoginRequired)return;const x=`${M.account_id}:${M.game_id}:${M.task_id??"sync"}`;if(h!==x){h=x;try{e.presentation.showSteamLoginRequired({userId:V,accountId:M.account_id},Re(e.operationContext,f.signal))}catch{}}}function L(M){if(n||e.operationContext.signal.aborted)throw ne("RUNTIME_DESTROYED","小程序已关闭");if(M!==r)throw ne("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function A(M,V,z){if(L(V),await e.account.getCurrentUserId(z)!==M)throw g(),ne("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");L(V)}async function U(M,V,z,te){if(await A(V,z,te),!e.authorizationContext)throw ne("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const x=await e.authorizationContext.get(te);if(!x.token||x.expiresAt<=Date.now())throw ne("UNAUTHORIZED","小程序运行上下文已过期");const Y=await Ii({network:e.network,operationContext:te,subject:"游戏存档",assertUsable:()=>L(z),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},w_,{...M,runtime_auth_context_token:x.token});if(await A(V,z,te),Y.status==="failed"&&Se(Y.result)&&Y.result.error_code==="RECENT_SAVE_AVAILABLE")throw ne("RECENT_SAVE_AVAILABLE",typeof Y.msg=="string"&&Y.msg?Y.msg:"已有近期存档,请直接查询使用");const j=Je(Y,M.action,"游戏存档");if(!Se(j))throw ne("INVALID_RESPONSE","存档响应不合法");return j}async function Q(M,V,z){const te=R_(M,V),x=r;if(L(x),M==="file"&&(!e.transfer||!e.files))throw ne("METHOD_FORBIDDEN","宿主不支持存档文件读取");const Y=new AbortController;l.add(Y);let j=!1;const H=M==="sync"?setTimeout(()=>{j=!0,Y.abort()},M_):void 0,F=Re(Re(e.operationContext,z.signal),Y.signal);try{const v=await e.account.getCurrentUserId(F);if(!v)throw ne("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==v)throw g(),ne("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=v,M==="sync"||M==="parsed"){if(M==="sync"&&_(),!te.account_id){const $=await U({action:"check",game_id:te.game_id},v,x,F);te.account_id=di($.account_id)}if(M==="sync")return await C(te,v,x,F)}const R=await U({action:M,...te},v,x,F);if(M==="list")return L_(R);if(M==="parsed")return S_(R.parsed_data,te.game_id);if(eh(R.file).fileId!==te.file_id)throw ne("INVALID_RESPONSE","文件标识不匹配");if(!s)throw ne("REQUEST_UNSUPPORTED","宿主不支持存档下载");const D=await s.download(R,async $=>{try{L(x),await U({action:"check",game_id:te.game_id,account_id:te.account_id},v,x,$)}catch(m){const w=Se(m)?String(m.code):"";throw["RUNTIME_DESTROYED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED","UNAUTHORIZED"].includes(w)?(g(),ne("FILE_ACCESS_REVOKED","游戏存档授权已失效")):m}},F);let W=!1;try{if(await A(v,x,F),L(x),F.signal.aborted)throw ne("DOWNLOAD_CANCELLED","存档下载已取消");const $=e.fileRegistry.registerFile(D,"game-save","read");return o.add(D),c.set(Cc(),{file:D,sizeBytes:s.sizeOf(D)}),W=!0,$}finally{W||await s.release(D)}}catch(v){throw j?ne("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):v}finally{H!==void 0&&clearTimeout(H),l.delete(Y)}}async function C(M,V,z,te){const x=e.identity.get()?.miniProgramId;if(!x)throw ne("INVALID_STATE","小程序身份尚未确认");const Y={miniProgramId:x,userId:V,gameId:M.game_id,accountId:M.account_id},j=F=>U({action:"status",...M,task_id:F},V,z,te);let H;try{const F=await t.run(Y,te,async()=>{await A(V,z,te);const R=await t.get(Y,te);if(R){H=R;try{return{taskId:R,status:await j(R)}}catch(D){if(!Se(D)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(D.code)))throw D;await t.set(Y,void 0,te),H=void 0}}const q=await U({action:"sync",...M},V,z,te);return H=di(q.task_id),await t.set(Y,H,te),await A(V,z,te),{taskId:H,status:void 0}});H=F.taskId;let v=F.status;for(;;){if(L(z),te.signal.aborted)throw ne("REQUEST_CANCELLED","已停止等待存档同步");if(v??=await j(H),v.state==="succeeded"||v.state==="failed"){if(await t.remove(Y,H,te),await A(V,z,te),v.state==="succeeded")return{state:"succeeded"};throw ne(v.error_code?Xs(v.error_code):"SYNC_FAILED",v.message?Xs(v.message):"存档同步失败")}if(v.state!=="syncing"&&v.state!=="uploading")throw ne("INVALID_RESPONSE","同步状态不合法");v=void 0,await P_(O_,te.signal)}}catch(F){if(Se(F)){const v=String(F.code);v==="STEAM_LOGIN_REQUIRED"&&y({...M,task_id:H},V,z,te),H&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(v)&&await t.remove(Y,H,u)}throw F}}return{handlers:{"gameSaves.list":(M,V)=>Q("list",M,V),"gameSaves.sync":(M,V)=>Q("sync",M,V),"gameSaves.readParsedData":(M,V)=>Q("parsed",M,V),"gameSaves.getFile":(M,V)=>Q("file",M,V)},diagnostics:{async getSnapshot(){const M=r;return i&&await A(i,M,e.operationContext),L(M),Array.from(c,([V,z])=>({id:V,name:z.file.name,sizeBytes:z.sizeBytes}))},async readFile(M,V){const z=r;L(z);const te=c.get(M);if(!te)throw ne("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const x=Re(e.operationContext,V);x.signal.throwIfAborted();const Y=await te.file.read(x);try{return x.signal.throwIfAborted(),L(z),{name:te.file.name,bytes:Y}}catch(j){throw Y.fill(0),j}}},allowsRead(M,V){return["file.readBytes","file.readText","file.stat","file.exists"].includes(M)&&Se(V)&&e.fileRegistry.isGameSaveRef(V.target)},dispose(){n||(n=!0,g(!1),b(),N())}}}function R_(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!Se(t)||Object.keys(t).some(i=>!r.includes(i)))throw ne("INVALID_PARAMS","存档参数不合法");const n=vn(t.gameId);if(Number(n)>2147483647)throw ne("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:vn(t.accountId)}:{},...e==="file"?{save_id:vn(t.saveId),file_id:vn(t.fileId)}:{}}}function vn(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw ne("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function di(e){try{return vn(e)}catch{throw ne("INVALID_RESPONSE","服务端存档标识无效")}}function Xs(e){if(typeof e!="string")throw ne("INVALID_RESPONSE","服务端存档字段无效");return e}function Ra(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw ne("INVALID_RESPONSE","服务端存档数值无效");return e}function eh(e){if(!Se(e))throw ne("INVALID_RESPONSE","存档文件信息无效");return{fileId:di(e.file_id),name:Xs(e.name),originalPath:Xs(e.original_path),sizeBytes:Ra(e.size_bytes),modifiedAt:Ra(e.modified_at)}}function L_(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw ne("INVALID_RESPONSE","存档列表无效");return{accountId:di(e.account_id),saves:e.saves.map(t=>{if(!Se(t)||!Array.isArray(t.files)||t.files.length>200)throw ne("INVALID_RESPONSE","存档文件列表无效");return{saveId:di(t.save_id),createdAt:Ra(t.created_at),files:t.files.map(eh)}})}}function P_(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(s),t.removeEventListener("abort",i),n(ne("REQUEST_CANCELLED","已停止等待存档同步"))},s=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}function th(e,t){return{auth:"optional",channel:"api",id:e,method:"GET",path:t,query(r){return{...r}},parse(r){return Gf(r,"赛事中心接口响应异常")}}}function rh(e,t){return{auth:"optional",bodyEncoding:"form",body(r){return{...r.body}},channel:"api",id:e,method:"POST",path:t,query(r){return r.query?{...r.query}:void 0},parse(r){return Gf(r,"赛事中心接口响应异常")}}}const v_=th("heybox.bbs.app.link.tree.get","/bbs/app/link/tree"),k_=th("heybox.bbs.app.comment.sub.comments.get","/bbs/app/comment/sub/comments"),x_=rh("heybox.bbs.app.comment.support.post","/bbs/app/comment/support"),U_=rh("heybox.bbs.app.comment.delete.post","/bbs/app/comment/delete");function So(e){return Ue(e,"社区评论响应异常")}const od={...v_,parse:So},B_={...k_,parse:So},H_={...x_,parse:So},F_={...U_,parse:So},z_={auth:"optional",channel:"api",id:"heybox.user_miniprogram.post.favorite",method:"POST",path:"/bbs/app/link/favour",bodyEncoding:"form",failurePresentation:"none",body:e=>({link_id:e.targetId,favour_type:e.enabled?1:0}),parse:e=>Ue(e,"社区操作响应异常")},j_={auth:"optional",channel:"api",id:"heybox.user_miniprogram.post.like",method:"POST",path:"/bbs/app/profile/award/link",bodyEncoding:"form",failurePresentation:"none",body:e=>({link_id:e.targetId,award_type:e.enabled?1:0}),parse:e=>Ue(e,"社区操作响应异常")},V_={auth:"optional",channel:"api",id:"heybox.user_miniprogram.runtime.post.read",method:"POST",path:"/user_miniprogram/runtime/post",bodyEncoding:"form",failurePresentation:"none",body:e=>({...e}),parse:e=>Ue(e,"关联帖子响应异常")},G_=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),He="�";var E;(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z"})(E||(E={}));const at={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function nh(e){return e>=55296&&e<=57343}function Y_(e){return e>=56320&&e<=57343}function Q_(e,t){return(e-55296)*1024+9216+t}function ih(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function sh(e){return e>=64976&&e<=65007||G_.has(e)}var G;(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text"})(G||(G={}));const q_=65536;class W_{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=q_,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,r){const{line:n,col:i,offset:s}=this,o=i+r,c=s+r;return{code:t,startLine:n,endLine:n,startCol:o,endCol:o,startOffset:c,endOffset:c}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(t){if(this.pos!==this.html.length-1){const r=this.html.charCodeAt(this.pos+1);if(Y_(r))return this.pos++,this._addGap(),Q_(t,r)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,E.EOF;return this._err(G.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(t,r){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=!1,this.lastChunkWritten=r}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(t,r){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(r)return this.html.startsWith(t,this.pos);for(let n=0;n<t.length;n++)if((this.html.charCodeAt(this.pos+n)|32)!==t.charCodeAt(n))return!1;return!0}peek(t){const r=this.pos+t;if(r>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,E.EOF;const n=this.html.charCodeAt(r);return n===E.CARRIAGE_RETURN?E.LINE_FEED:n}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,E.EOF;let t=this.html.charCodeAt(this.pos);return t===E.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,E.LINE_FEED):t===E.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,nh(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===E.LINE_FEED||t===E.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){ih(t)?this._err(G.controlCharacterInInputStream):sh(t)&&this._err(G.noncharacterInInputStream)}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}}var Ce;(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION"})(Ce||(Ce={}));function oh(e,t){for(let r=e.attrs.length-1;r>=0;r--)if(e.attrs[r].name===t)return e.attrs[r].value;return null}const $_=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏઑඡ༉༦ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲϏϢϸontourIntegraìȹoɴ\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲy;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱còJTabcdfgorstרׯؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ߂ߐĀiyޱrc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣসে্ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४ĀnrࢃgleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpwਖਛgȀLRlr৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼અઋp;椅y;䐜Ādl੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑඞcy;䐊cute;䅃ƀaeyહાron;䅇dil;䅅;䐝ƀgswે૰ativeƀMTV૨ediumSpace;怋hiĀcn૦ëeryThiîtedĀGLଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷreak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪௫ఄ಄ದൡඅ櫬Āoungruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater;EFGLSTஶஷ扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨setĀ;Eೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂෛ෧ขภยา฿ไlig;䅒cute耻Ó䃓Āiyීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲcr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬืde耻Õ䃕es;樷ml耻Ö䃖erĀBP๋Āar๐๓r;怾acĀek๚;揞et;掴arenthesis;揜ҀacfhilorsງຊຏຒດຝະrtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ檻cedesȀ;EST່້扺qual;檯lantEqual;扼ilde;找me;怳Ādpuct;戏ortionĀ;aȥl;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL憒ar;懥eftArrow;懄eiling;按oǵ\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄቕቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHcቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗ĀeiቻDzኀ\0ኇefore;戴a;䎘ĀcnኘkSpace;쀀 Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtèa;䎖r;愨pf;愤cr;쀀𝒵ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒;Eaeiopᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;eᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;eᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰᝃᝈ០៦ᠹᡐᜍ᥈ᥰot;櫭ĀcrᛶkȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;tbrk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯᝳ;䎲;愶een;扬r;쀀𝔟gcostuvwឍឝឳេ៕៛ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀakoᠦᠵĀcn៲ᠣkƀlst֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ;敛;敘;攘;攔;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģbar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;elƀ;bhᥨᥩᥫ䁜;槅sub;柈ŬᥴlĀ;e怢t»pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭒\0᯽\0ᰌƀcprᦲute;䄇̀;abcdsᦿᧀᧄ᧕᧙戩nd;橄rcup;橉Āau᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r;Ecefms᩠ᩢᩫ᪤᪪旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ\0\0aĀ;t䀬;䁀ƀ;fl戁îᅠeĀmxent»eóɍǧ\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯delprvw᭠᭬᭷ᮂᮬᯔarrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;pᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰻᰿ᱝᱩᱵᲞᲬᲷᴍᵻᶑᶫᶻ᷆᷍ròar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂᳖᳜᳠mƀ;oș᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄĀDoḆᴴoôĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»ṺƀaeiἒἚls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧\0耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₥₰₴⃰℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽ƀ;qsؾٌlanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqrⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0proør;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼ròòΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonóquigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roøurĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨íistĀ;sடr;쀀𝔫ȀEest⩦⩹⩼ƀ;qs⩭ƀ;qs⩴lanôií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast⭕⭚⭟lleìl;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖchimpqu⮽⯍⯙⬄⯤⯯Ȁ;cerല⯆ഷ⯉uå;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭ååഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñĀ;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;cⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācrir;榿;쀀𝔬ͯ\0\0\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕⶥⶨrò᪀Āirⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔǒr;榷rp;榹;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ\0\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ脀¶;l䂶leìЃɩ\0\0m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳ᤈ⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t⾴ïrel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⋢⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔ABHabcdefhilmnoprstuxけさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstwガクシスゼゾダッデナp;極Ā;fゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ìâヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘rrowĀ;tㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowóarpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓ròaòՑ;怏oustĀ;a㈞掱che»mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì耻䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;qኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫwar;椪lig耻ß䃟㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rëƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproøim»ኬsðኞĀas㚺㚮ðrn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈadempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xôheadĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roðtré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜtré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),K_=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function Z_(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=K_.get(e))!==null&&t!==void 0?t:e}var We;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"})(We||(We={}));const X_=32;var ir;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(ir||(ir={}));function La(e){return e>=We.ZERO&&e<=We.NINE}function J_(e){return e>=We.UPPER_A&&e<=We.UPPER_F||e>=We.LOWER_A&&e<=We.LOWER_F}function eA(e){return e>=We.UPPER_A&&e<=We.UPPER_Z||e>=We.LOWER_A&&e<=We.LOWER_Z||La(e)}function tA(e){return e===We.EQUALS||eA(e)}var Qe;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(Qe||(Qe={}));var qt;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(qt||(qt={}));class rA{constructor(t,r,n){this.decodeTree=t,this.emitCodePoint=r,this.errors=n,this.state=Qe.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=qt.Strict}startEntity(t){this.decodeMode=t,this.state=Qe.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(t,r){switch(this.state){case Qe.EntityStart:return t.charCodeAt(r)===We.NUM?(this.state=Qe.NumericStart,this.consumed+=1,this.stateNumericStart(t,r+1)):(this.state=Qe.NamedEntity,this.stateNamedEntity(t,r));case Qe.NumericStart:return this.stateNumericStart(t,r);case Qe.NumericDecimal:return this.stateNumericDecimal(t,r);case Qe.NumericHex:return this.stateNumericHex(t,r);case Qe.NamedEntity:return this.stateNamedEntity(t,r)}}stateNumericStart(t,r){return r>=t.length?-1:(t.charCodeAt(r)|X_)===We.LOWER_X?(this.state=Qe.NumericHex,this.consumed+=1,this.stateNumericHex(t,r+1)):(this.state=Qe.NumericDecimal,this.stateNumericDecimal(t,r))}addToNumericResult(t,r,n,i){if(r!==n){const s=n-r;this.result=this.result*Math.pow(i,s)+Number.parseInt(t.substr(r,s),i),this.consumed+=s}}stateNumericHex(t,r){const n=r;for(;r<t.length;){const i=t.charCodeAt(r);if(La(i)||J_(i))r+=1;else return this.addToNumericResult(t,n,r,16),this.emitNumericEntity(i,3)}return this.addToNumericResult(t,n,r,16),-1}stateNumericDecimal(t,r){const n=r;for(;r<t.length;){const i=t.charCodeAt(r);if(La(i))r+=1;else return this.addToNumericResult(t,n,r,10),this.emitNumericEntity(i,2)}return this.addToNumericResult(t,n,r,10),-1}emitNumericEntity(t,r){var n;if(this.consumed<=r)return(n=this.errors)===null||n===void 0||n.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===We.SEMI)this.consumed+=1;else if(this.decodeMode===qt.Strict)return 0;return this.emitCodePoint(Z_(this.result),this.consumed),this.errors&&(t!==We.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,r){const{decodeTree:n}=this;let i=n[this.treeIndex],s=(i&ir.VALUE_LENGTH)>>14;for(;r<t.length;r++,this.excess++){const o=t.charCodeAt(r);if(this.treeIndex=nA(n,i,this.treeIndex+Math.max(1,s),o),this.treeIndex<0)return this.result===0||this.decodeMode===qt.Attribute&&(s===0||tA(o))?0:this.emitNotTerminatedNamedEntity();if(i=n[this.treeIndex],s=(i&ir.VALUE_LENGTH)>>14,s!==0){if(o===We.SEMI)return this.emitNamedEntityData(this.treeIndex,s,this.consumed+this.excess);this.decodeMode!==qt.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var t;const{result:r,decodeTree:n}=this,i=(n[r]&ir.VALUE_LENGTH)>>14;return this.emitNamedEntityData(r,i,this.consumed),(t=this.errors)===null||t===void 0||t.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,r,n){const{decodeTree:i}=this;return this.emitCodePoint(r===1?i[t]&~ir.VALUE_LENGTH:i[t+1],n),r===3&&this.emitCodePoint(i[t+2],n),n}end(){var t;switch(this.state){case Qe.NamedEntity:return this.result!==0&&(this.decodeMode!==qt.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Qe.NumericDecimal:return this.emitNumericEntity(0,2);case Qe.NumericHex:return this.emitNumericEntity(0,3);case Qe.NumericStart:return(t=this.errors)===null||t===void 0||t.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Qe.EntityStart:return 0}}}function nA(e,t,r,n){const i=(t&ir.BRANCH_LENGTH)>>7,s=t&ir.JUMP_TABLE;if(i===0)return s!==0&&n===s?r:-1;if(s){const u=n-s;return u<0||u>=i?-1:e[r+u]-1}let o=r,c=o+i-1;for(;o<=c;){const u=o+c>>>1,d=e[u];if(d<n)o=u+1;else if(d>n)c=u-1;else return e[u+i]}return-1}var ee;(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/"})(ee||(ee={}));var Or;(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size"})(Or||(Or={}));var _t;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"})(_t||(_t={}));var k;(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp"})(k||(k={}));var a;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP"})(a||(a={}));const iA=new Map([[k.A,a.A],[k.ADDRESS,a.ADDRESS],[k.ANNOTATION_XML,a.ANNOTATION_XML],[k.APPLET,a.APPLET],[k.AREA,a.AREA],[k.ARTICLE,a.ARTICLE],[k.ASIDE,a.ASIDE],[k.B,a.B],[k.BASE,a.BASE],[k.BASEFONT,a.BASEFONT],[k.BGSOUND,a.BGSOUND],[k.BIG,a.BIG],[k.BLOCKQUOTE,a.BLOCKQUOTE],[k.BODY,a.BODY],[k.BR,a.BR],[k.BUTTON,a.BUTTON],[k.CAPTION,a.CAPTION],[k.CENTER,a.CENTER],[k.CODE,a.CODE],[k.COL,a.COL],[k.COLGROUP,a.COLGROUP],[k.DD,a.DD],[k.DESC,a.DESC],[k.DETAILS,a.DETAILS],[k.DIALOG,a.DIALOG],[k.DIR,a.DIR],[k.DIV,a.DIV],[k.DL,a.DL],[k.DT,a.DT],[k.EM,a.EM],[k.EMBED,a.EMBED],[k.FIELDSET,a.FIELDSET],[k.FIGCAPTION,a.FIGCAPTION],[k.FIGURE,a.FIGURE],[k.FONT,a.FONT],[k.FOOTER,a.FOOTER],[k.FOREIGN_OBJECT,a.FOREIGN_OBJECT],[k.FORM,a.FORM],[k.FRAME,a.FRAME],[k.FRAMESET,a.FRAMESET],[k.H1,a.H1],[k.H2,a.H2],[k.H3,a.H3],[k.H4,a.H4],[k.H5,a.H5],[k.H6,a.H6],[k.HEAD,a.HEAD],[k.HEADER,a.HEADER],[k.HGROUP,a.HGROUP],[k.HR,a.HR],[k.HTML,a.HTML],[k.I,a.I],[k.IMG,a.IMG],[k.IMAGE,a.IMAGE],[k.INPUT,a.INPUT],[k.IFRAME,a.IFRAME],[k.KEYGEN,a.KEYGEN],[k.LABEL,a.LABEL],[k.LI,a.LI],[k.LINK,a.LINK],[k.LISTING,a.LISTING],[k.MAIN,a.MAIN],[k.MALIGNMARK,a.MALIGNMARK],[k.MARQUEE,a.MARQUEE],[k.MATH,a.MATH],[k.MENU,a.MENU],[k.META,a.META],[k.MGLYPH,a.MGLYPH],[k.MI,a.MI],[k.MO,a.MO],[k.MN,a.MN],[k.MS,a.MS],[k.MTEXT,a.MTEXT],[k.NAV,a.NAV],[k.NOBR,a.NOBR],[k.NOFRAMES,a.NOFRAMES],[k.NOEMBED,a.NOEMBED],[k.NOSCRIPT,a.NOSCRIPT],[k.OBJECT,a.OBJECT],[k.OL,a.OL],[k.OPTGROUP,a.OPTGROUP],[k.OPTION,a.OPTION],[k.P,a.P],[k.PARAM,a.PARAM],[k.PLAINTEXT,a.PLAINTEXT],[k.PRE,a.PRE],[k.RB,a.RB],[k.RP,a.RP],[k.RT,a.RT],[k.RTC,a.RTC],[k.RUBY,a.RUBY],[k.S,a.S],[k.SCRIPT,a.SCRIPT],[k.SEARCH,a.SEARCH],[k.SECTION,a.SECTION],[k.SELECT,a.SELECT],[k.SOURCE,a.SOURCE],[k.SMALL,a.SMALL],[k.SPAN,a.SPAN],[k.STRIKE,a.STRIKE],[k.STRONG,a.STRONG],[k.STYLE,a.STYLE],[k.SUB,a.SUB],[k.SUMMARY,a.SUMMARY],[k.SUP,a.SUP],[k.TABLE,a.TABLE],[k.TBODY,a.TBODY],[k.TEMPLATE,a.TEMPLATE],[k.TEXTAREA,a.TEXTAREA],[k.TFOOT,a.TFOOT],[k.TD,a.TD],[k.TH,a.TH],[k.THEAD,a.THEAD],[k.TITLE,a.TITLE],[k.TR,a.TR],[k.TRACK,a.TRACK],[k.TT,a.TT],[k.U,a.U],[k.UL,a.UL],[k.SVG,a.SVG],[k.VAR,a.VAR],[k.WBR,a.WBR],[k.XMP,a.XMP]]);function Oo(e){var t;return(t=iA.get(e))!==null&&t!==void 0?t:a.UNKNOWN}const re=a,sA={[ee.HTML]:new Set([re.ADDRESS,re.APPLET,re.AREA,re.ARTICLE,re.ASIDE,re.BASE,re.BASEFONT,re.BGSOUND,re.BLOCKQUOTE,re.BODY,re.BR,re.BUTTON,re.CAPTION,re.CENTER,re.COL,re.COLGROUP,re.DD,re.DETAILS,re.DIR,re.DIV,re.DL,re.DT,re.EMBED,re.FIELDSET,re.FIGCAPTION,re.FIGURE,re.FOOTER,re.FORM,re.FRAME,re.FRAMESET,re.H1,re.H2,re.H3,re.H4,re.H5,re.H6,re.HEAD,re.HEADER,re.HGROUP,re.HR,re.HTML,re.IFRAME,re.IMG,re.INPUT,re.LI,re.LINK,re.LISTING,re.MAIN,re.MARQUEE,re.MENU,re.META,re.NAV,re.NOEMBED,re.NOFRAMES,re.NOSCRIPT,re.OBJECT,re.OL,re.P,re.PARAM,re.PLAINTEXT,re.PRE,re.SCRIPT,re.SECTION,re.SELECT,re.SOURCE,re.STYLE,re.SUMMARY,re.TABLE,re.TBODY,re.TD,re.TEMPLATE,re.TEXTAREA,re.TFOOT,re.TH,re.THEAD,re.TITLE,re.TR,re.TRACK,re.UL,re.WBR,re.XMP]),[ee.MATHML]:new Set([re.MI,re.MO,re.MN,re.MS,re.MTEXT,re.ANNOTATION_XML]),[ee.SVG]:new Set([re.TITLE,re.FOREIGN_OBJECT,re.DESC]),[ee.XLINK]:new Set,[ee.XML]:new Set,[ee.XMLNS]:new Set},Pa=new Set([re.H1,re.H2,re.H3,re.H4,re.H5,re.H6]);k.STYLE,k.SCRIPT,k.XMP,k.IFRAME,k.NOEMBED,k.NOFRAMES,k.PLAINTEXT;var T;(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND"})(T||(T={}));const ut={DATA:T.DATA,RCDATA:T.RCDATA,RAWTEXT:T.RAWTEXT,SCRIPT_DATA:T.SCRIPT_DATA,PLAINTEXT:T.PLAINTEXT,CDATA_SECTION:T.CDATA_SECTION};function oA(e){return e>=E.DIGIT_0&&e<=E.DIGIT_9}function kn(e){return e>=E.LATIN_CAPITAL_A&&e<=E.LATIN_CAPITAL_Z}function aA(e){return e>=E.LATIN_SMALL_A&&e<=E.LATIN_SMALL_Z}function Zt(e){return aA(e)||kn(e)}function ad(e){return Zt(e)||oA(e)}function vi(e){return e+32}function ah(e){return e===E.SPACE||e===E.LINE_FEED||e===E.TABULATION||e===E.FORM_FEED}function cd(e){return ah(e)||e===E.SOLIDUS||e===E.GREATER_THAN_SIGN}function cA(e){return e===E.NULL?G.nullCharacterReference:e>1114111?G.characterReferenceOutsideUnicodeRange:nh(e)?G.surrogateCharacterReference:sh(e)?G.noncharacterCharacterReference:ih(e)||e===E.CARRIAGE_RETURN?G.controlCharacterReference:null}class uA{constructor(t,r){this.options=t,this.handler=r,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,this.state=T.DATA,this.returnState=T.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new W_(r),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new rA($_,(n,i)=>{this.preprocessor.pos=this.entityStartPos+i-1,this._flushCodePointConsumedAsCharacterReference(n)},r.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(G.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:n=>{this._err(G.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+n)},validateNumericCharacterReference:n=>{const i=cA(n);i&&this._err(i,1)}}:void 0)}_err(t,r=0){var n,i;(i=(n=this.handler).onParseError)===null||i===void 0||i.call(n,this.preprocessor.getError(t,r))}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;const t=this._consume();this._ensureHibernation()||this._callState(t)}this.inLoop=!1}}pause(){this.paused=!0}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,!this.inLoop&&(this._runParsingLoop(),this.paused||t?.())}write(t,r,n){this.active=!0,this.preprocessor.write(t,r),this._runParsingLoop(),this.paused||n?.()}insertHtmlAtCurrentPos(t){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop()}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0):!1}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let r=0;r<t;r++)this.preprocessor.advance()}_consumeSequenceIfMatch(t,r){return this.preprocessor.startsWith(t,r)?(this._advanceBy(t.length-1),!0):!1}_createStartTagToken(){this.currentToken={type:Ce.START_TAG,tagName:"",tagID:a.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:Ce.END_TAG,tagName:"",tagID:a.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(t){this.currentToken={type:Ce.COMMENT,data:"",location:this.getCurrentLocation(t)}}_createDoctypeToken(t){this.currentToken={type:Ce.DOCTYPE,name:t,forceQuirks:!1,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(t,r){this.currentCharacterToken={type:t,chars:r,location:this.currentLocation}}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var t,r;const n=this.currentToken;if(oh(n,this.currentAttr.name)===null){if(n.attrs.push(this.currentAttr),n.location&&this.currentLocation){const i=(t=(r=n.location).attrs)!==null&&t!==void 0?t:r.attrs=Object.create(null);i[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(G.duplicateAttribute)}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset)}prepareToken(t){this._emitCurrentCharacterToken(t.location),this.currentToken=null,t.location&&(t.location.endLine=this.preprocessor.line,t.location.endCol=this.preprocessor.col+1,t.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){const t=this.currentToken;this.prepareToken(t),t.tagID=Oo(t.tagName),t.type===Ce.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(G.endTagWithAttributes),t.selfClosing&&this._err(G.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk()}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case Ce.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Ce.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Ce.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null}}_emitEOFToken(){const t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:Ce.EOF,location:t}),this.active=!1}_appendCharToCurrentCharacterToken(t,r){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=r;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,r)}_emitCodePoint(t){const r=ah(t)?Ce.WHITESPACE_CHARACTER:t===E.NULL?Ce.NULL_CHARACTER:Ce.CHARACTER;this._appendCharToCurrentCharacterToken(r,String.fromCodePoint(t))}_emitChars(t){this._appendCharToCurrentCharacterToken(Ce.CHARACTER,t)}_startCharacterReference(){this.returnState=this.state,this.state=T.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?qt.Attribute:qt.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===T.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===T.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===T.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t)}_callState(t){switch(this.state){case T.DATA:{this._stateData(t);break}case T.RCDATA:{this._stateRcdata(t);break}case T.RAWTEXT:{this._stateRawtext(t);break}case T.SCRIPT_DATA:{this._stateScriptData(t);break}case T.PLAINTEXT:{this._statePlaintext(t);break}case T.TAG_OPEN:{this._stateTagOpen(t);break}case T.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case T.TAG_NAME:{this._stateTagName(t);break}case T.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case T.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case T.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case T.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case T.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case T.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case T.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case T.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case T.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case T.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case T.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case T.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case T.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case T.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case T.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case T.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case T.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case T.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case T.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case T.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case T.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case T.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case T.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case T.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case T.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case T.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case T.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case T.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case T.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case T.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case T.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case T.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case T.BOGUS_COMMENT:{this._stateBogusComment(t);break}case T.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case T.COMMENT_START:{this._stateCommentStart(t);break}case T.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case T.COMMENT:{this._stateComment(t);break}case T.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case T.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case T.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case T.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case T.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case T.COMMENT_END:{this._stateCommentEnd(t);break}case T.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case T.DOCTYPE:{this._stateDoctype(t);break}case T.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case T.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case T.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case T.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case T.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case T.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case T.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case T.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case T.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case T.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case T.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case T.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case T.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case T.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case T.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case T.CDATA_SECTION:{this._stateCdataSection(t);break}case T.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case T.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case T.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case T.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case E.LESS_THAN_SIGN:{this.state=T.TAG_OPEN;break}case E.AMPERSAND:{this._startCharacterReference();break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitCodePoint(t);break}case E.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRcdata(t){switch(t){case E.AMPERSAND:{this._startCharacterReference();break}case E.LESS_THAN_SIGN:{this.state=T.RCDATA_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(He);break}case E.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRawtext(t){switch(t){case E.LESS_THAN_SIGN:{this.state=T.RAWTEXT_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(He);break}case E.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptData(t){switch(t){case E.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(He);break}case E.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(He);break}case E.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateTagOpen(t){if(Zt(t))this._createStartTagToken(),this.state=T.TAG_NAME,this._stateTagName(t);else switch(t){case E.EXCLAMATION_MARK:{this.state=T.MARKUP_DECLARATION_OPEN;break}case E.SOLIDUS:{this.state=T.END_TAG_OPEN;break}case E.QUESTION_MARK:{this._err(G.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=T.BOGUS_COMMENT,this._stateBogusComment(t);break}case E.EOF:{this._err(G.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(G.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=T.DATA,this._stateData(t)}}_stateEndTagOpen(t){if(Zt(t))this._createEndTagToken(),this.state=T.TAG_NAME,this._stateTagName(t);else switch(t){case E.GREATER_THAN_SIGN:{this._err(G.missingEndTagName),this.state=T.DATA;break}case E.EOF:{this._err(G.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(G.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=T.BOGUS_COMMENT,this._stateBogusComment(t)}}_stateTagName(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=T.BEFORE_ATTRIBUTE_NAME;break}case E.SOLIDUS:{this.state=T.SELF_CLOSING_START_TAG;break}case E.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentTagToken();break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.tagName+=He;break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:r.tagName+=String.fromCodePoint(kn(t)?vi(t):t)}}_stateRcdataLessThanSign(t){t===E.SOLIDUS?this.state=T.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=T.RCDATA,this._stateRcdata(t))}_stateRcdataEndTagOpen(t){Zt(t)?(this.state=T.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=T.RCDATA,this._stateRcdata(t))}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();const r=this.currentToken;switch(r.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=T.BEFORE_ATTRIBUTE_NAME,!1;case E.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=T.SELF_CLOSING_START_TAG,!1;case E.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=T.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=T.RCDATA,this._stateRcdata(t))}_stateRawtextLessThanSign(t){t===E.SOLIDUS?this.state=T.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=T.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagOpen(t){Zt(t)?(this.state=T.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=T.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=T.RAWTEXT,this._stateRawtext(t))}_stateScriptDataLessThanSign(t){switch(t){case E.SOLIDUS:{this.state=T.SCRIPT_DATA_END_TAG_OPEN;break}case E.EXCLAMATION_MARK:{this.state=T.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=T.SCRIPT_DATA,this._stateScriptData(t)}}_stateScriptDataEndTagOpen(t){Zt(t)?(this.state=T.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=T.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=T.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStart(t){t===E.HYPHEN_MINUS?(this.state=T.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=T.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStartDash(t){t===E.HYPHEN_MINUS?(this.state=T.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=T.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscaped(t){switch(t){case E.HYPHEN_MINUS:{this.state=T.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(He);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataEscapedDash(t){switch(t){case E.HYPHEN_MINUS:{this.state=T.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.state=T.SCRIPT_DATA_ESCAPED,this._emitChars(He);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=T.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedDashDash(t){switch(t){case E.HYPHEN_MINUS:{this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case E.GREATER_THAN_SIGN:{this.state=T.SCRIPT_DATA,this._emitChars(">");break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.state=T.SCRIPT_DATA_ESCAPED,this._emitChars(He);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=T.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedLessThanSign(t){t===E.SOLIDUS?this.state=T.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Zt(t)?(this._emitChars("<"),this.state=T.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=T.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagOpen(t){Zt(t)?(this.state=T.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=T.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=T.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(at.SCRIPT,!1)&&cd(this.preprocessor.peek(at.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r<at.SCRIPT.length;r++)this._emitCodePoint(this._consume());this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=T.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscaped(t){switch(t){case E.HYPHEN_MINUS:{this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(He);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDash(t){switch(t){case E.HYPHEN_MINUS:{this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(He);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case E.HYPHEN_MINUS:{this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case E.GREATER_THAN_SIGN:{this.state=T.SCRIPT_DATA,this._emitChars(">");break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(He);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedLessThanSign(t){t===E.SOLIDUS?(this.state=T.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(at.SCRIPT,!1)&&cd(this.preprocessor.peek(at.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r<at.SCRIPT.length;r++)this._emitCodePoint(this._consume());this.state=T.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateBeforeAttributeName(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.SOLIDUS:case E.GREATER_THAN_SIGN:case E.EOF:{this.state=T.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case E.EQUALS_SIGN:{this._err(G.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=T.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=T.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateAttributeName(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:case E.SOLIDUS:case E.GREATER_THAN_SIGN:case E.EOF:{this._leaveAttrName(),this.state=T.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case E.EQUALS_SIGN:{this._leaveAttrName(),this.state=T.BEFORE_ATTRIBUTE_VALUE;break}case E.QUOTATION_MARK:case E.APOSTROPHE:case E.LESS_THAN_SIGN:{this._err(G.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.name+=He;break}default:this.currentAttr.name+=String.fromCodePoint(kn(t)?vi(t):t)}}_stateAfterAttributeName(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.SOLIDUS:{this.state=T.SELF_CLOSING_START_TAG;break}case E.EQUALS_SIGN:{this.state=T.BEFORE_ATTRIBUTE_VALUE;break}case E.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentTagToken();break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=T.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateBeforeAttributeValue(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.QUOTATION_MARK:{this.state=T.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case E.APOSTROPHE:{this.state=T.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case E.GREATER_THAN_SIGN:{this._err(G.missingAttributeValue),this.state=T.DATA,this.emitCurrentTagToken();break}default:this.state=T.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t)}}_stateAttributeValueDoubleQuoted(t){switch(t){case E.QUOTATION_MARK:{this.state=T.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case E.AMPERSAND:{this._startCharacterReference();break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=He;break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueSingleQuoted(t){switch(t){case E.APOSTROPHE:{this.state=T.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case E.AMPERSAND:{this._startCharacterReference();break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=He;break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueUnquoted(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this._leaveAttrValue(),this.state=T.BEFORE_ATTRIBUTE_NAME;break}case E.AMPERSAND:{this._startCharacterReference();break}case E.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=T.DATA,this.emitCurrentTagToken();break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=He;break}case E.QUOTATION_MARK:case E.APOSTROPHE:case E.LESS_THAN_SIGN:case E.EQUALS_SIGN:case E.GRAVE_ACCENT:{this._err(G.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAfterAttributeValueQuoted(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this._leaveAttrValue(),this.state=T.BEFORE_ATTRIBUTE_NAME;break}case E.SOLIDUS:{this._leaveAttrValue(),this.state=T.SELF_CLOSING_START_TAG;break}case E.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=T.DATA,this.emitCurrentTagToken();break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this._err(G.missingWhitespaceBetweenAttributes),this.state=T.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateSelfClosingStartTag(t){switch(t){case E.GREATER_THAN_SIGN:{const r=this.currentToken;r.selfClosing=!0,this.state=T.DATA,this.emitCurrentTagToken();break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this._err(G.unexpectedSolidusInTag),this.state=T.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateBogusComment(t){const r=this.currentToken;switch(t){case E.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentComment(r);break}case E.EOF:{this.emitCurrentComment(r),this._emitEOFToken();break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.data+=He;break}default:r.data+=String.fromCodePoint(t)}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(at.DASH_DASH,!0)?(this._createCommentToken(at.DASH_DASH.length+1),this.state=T.COMMENT_START):this._consumeSequenceIfMatch(at.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(at.DOCTYPE.length+1),this.state=T.DOCTYPE):this._consumeSequenceIfMatch(at.CDATA_START,!0)?this.inForeignNode?this.state=T.CDATA_SECTION:(this._err(G.cdataInHtmlContent),this._createCommentToken(at.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=T.BOGUS_COMMENT):this._ensureHibernation()||(this._err(G.incorrectlyOpenedComment),this._createCommentToken(2),this.state=T.BOGUS_COMMENT,this._stateBogusComment(t))}_stateCommentStart(t){switch(t){case E.HYPHEN_MINUS:{this.state=T.COMMENT_START_DASH;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptClosingOfEmptyComment),this.state=T.DATA;const r=this.currentToken;this.emitCurrentComment(r);break}default:this.state=T.COMMENT,this._stateComment(t)}}_stateCommentStartDash(t){const r=this.currentToken;switch(t){case E.HYPHEN_MINUS:{this.state=T.COMMENT_END;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptClosingOfEmptyComment),this.state=T.DATA,this.emitCurrentComment(r);break}case E.EOF:{this._err(G.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="-",this.state=T.COMMENT,this._stateComment(t)}}_stateComment(t){const r=this.currentToken;switch(t){case E.HYPHEN_MINUS:{this.state=T.COMMENT_END_DASH;break}case E.LESS_THAN_SIGN:{r.data+="<",this.state=T.COMMENT_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.data+=He;break}case E.EOF:{this._err(G.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+=String.fromCodePoint(t)}}_stateCommentLessThanSign(t){const r=this.currentToken;switch(t){case E.EXCLAMATION_MARK:{r.data+="!",this.state=T.COMMENT_LESS_THAN_SIGN_BANG;break}case E.LESS_THAN_SIGN:{r.data+="<";break}default:this.state=T.COMMENT,this._stateComment(t)}}_stateCommentLessThanSignBang(t){t===E.HYPHEN_MINUS?this.state=T.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=T.COMMENT,this._stateComment(t))}_stateCommentLessThanSignBangDash(t){t===E.HYPHEN_MINUS?this.state=T.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=T.COMMENT_END_DASH,this._stateCommentEndDash(t))}_stateCommentLessThanSignBangDashDash(t){t!==E.GREATER_THAN_SIGN&&t!==E.EOF&&this._err(G.nestedComment),this.state=T.COMMENT_END,this._stateCommentEnd(t)}_stateCommentEndDash(t){const r=this.currentToken;switch(t){case E.HYPHEN_MINUS:{this.state=T.COMMENT_END;break}case E.EOF:{this._err(G.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="-",this.state=T.COMMENT,this._stateComment(t)}}_stateCommentEnd(t){const r=this.currentToken;switch(t){case E.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentComment(r);break}case E.EXCLAMATION_MARK:{this.state=T.COMMENT_END_BANG;break}case E.HYPHEN_MINUS:{r.data+="-";break}case E.EOF:{this._err(G.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="--",this.state=T.COMMENT,this._stateComment(t)}}_stateCommentEndBang(t){const r=this.currentToken;switch(t){case E.HYPHEN_MINUS:{r.data+="--!",this.state=T.COMMENT_END_DASH;break}case E.GREATER_THAN_SIGN:{this._err(G.incorrectlyClosedComment),this.state=T.DATA,this.emitCurrentComment(r);break}case E.EOF:{this._err(G.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="--!",this.state=T.COMMENT,this._stateComment(t)}}_stateDoctype(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=T.BEFORE_DOCTYPE_NAME;break}case E.GREATER_THAN_SIGN:{this.state=T.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case E.EOF:{this._err(G.eofInDoctype),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingWhitespaceBeforeDoctypeName),this.state=T.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t)}}_stateBeforeDoctypeName(t){if(kn(t))this._createDoctypeToken(String.fromCharCode(vi(t))),this.state=T.DOCTYPE_NAME;else switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.NULL:{this._err(G.unexpectedNullCharacter),this._createDoctypeToken(He),this.state=T.DOCTYPE_NAME;break}case E.GREATER_THAN_SIGN:{this._err(G.missingDoctypeName),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=T.DATA;break}case E.EOF:{this._err(G.eofInDoctype),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=T.DOCTYPE_NAME}}_stateDoctypeName(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=T.AFTER_DOCTYPE_NAME;break}case E.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentDoctype(r);break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.name+=He;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.name+=String.fromCodePoint(kn(t)?vi(t):t)}}_stateAfterDoctypeName(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentDoctype(r);break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(at.PUBLIC,!1)?this.state=T.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(at.SYSTEM,!1)?this.state=T.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(G.invalidCharacterSequenceAfterDoctypeName),r.forceQuirks=!0,this.state=T.BOGUS_DOCTYPE,this._stateBogusDoctype(t))}}_stateAfterDoctypePublicKeyword(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=T.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case E.QUOTATION_MARK:{this._err(G.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=T.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{this._err(G.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=T.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case E.GREATER_THAN_SIGN:{this._err(G.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=T.DATA,this.emitCurrentDoctype(r);break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypePublicIdentifier),r.forceQuirks=!0,this.state=T.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypePublicIdentifier(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.QUOTATION_MARK:{r.publicId="",this.state=T.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{r.publicId="",this.state=T.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case E.GREATER_THAN_SIGN:{this._err(G.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=T.DATA,this.emitCurrentDoctype(r);break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypePublicIdentifier),r.forceQuirks=!0,this.state=T.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypePublicIdentifierDoubleQuoted(t){const r=this.currentToken;switch(t){case E.QUOTATION_MARK:{this.state=T.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.publicId+=He;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=T.DATA;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.publicId+=String.fromCodePoint(t)}}_stateDoctypePublicIdentifierSingleQuoted(t){const r=this.currentToken;switch(t){case E.APOSTROPHE:{this.state=T.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.publicId+=He;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=T.DATA;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.publicId+=String.fromCodePoint(t)}}_stateAfterDoctypePublicIdentifier(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=T.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case E.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentDoctype(r);break}case E.QUOTATION_MARK:{this._err(G.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{this._err(G.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=T.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=T.DATA;break}case E.QUOTATION_MARK:{r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=T.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateAfterDoctypeSystemKeyword(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=T.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case E.QUOTATION_MARK:{this._err(G.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{this._err(G.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case E.GREATER_THAN_SIGN:{this._err(G.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=T.DATA,this.emitCurrentDoctype(r);break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=T.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypeSystemIdentifier(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.QUOTATION_MARK:{r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case E.GREATER_THAN_SIGN:{this._err(G.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=T.DATA,this.emitCurrentDoctype(r);break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=T.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypeSystemIdentifierDoubleQuoted(t){const r=this.currentToken;switch(t){case E.QUOTATION_MARK:{this.state=T.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.systemId+=He;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=T.DATA;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.systemId+=String.fromCodePoint(t)}}_stateDoctypeSystemIdentifierSingleQuoted(t){const r=this.currentToken;switch(t){case E.APOSTROPHE:{this.state=T.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.systemId+=He;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=T.DATA;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.systemId+=String.fromCodePoint(t)}}_stateAfterDoctypeSystemIdentifier(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=T.DATA;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=T.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBogusDoctype(t){const r=this.currentToken;switch(t){case E.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=T.DATA;break}case E.NULL:{this._err(G.unexpectedNullCharacter);break}case E.EOF:{this.emitCurrentDoctype(r),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case E.RIGHT_SQUARE_BRACKET:{this.state=T.CDATA_SECTION_BRACKET;break}case E.EOF:{this._err(G.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateCdataSectionBracket(t){t===E.RIGHT_SQUARE_BRACKET?this.state=T.CDATA_SECTION_END:(this._emitChars("]"),this.state=T.CDATA_SECTION,this._stateCdataSection(t))}_stateCdataSectionEnd(t){switch(t){case E.GREATER_THAN_SIGN:{this.state=T.DATA;break}case E.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=T.CDATA_SECTION,this._stateCdataSection(t)}}_stateCharacterReference(){let t=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(t<0)if(this.preprocessor.lastChunkWritten)t=this.entityDecoder.end();else{this.active=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=!0;return}t===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(E.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&ad(this.preprocessor.peek(1))?T.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(t){ad(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===E.SEMICOLON&&this._err(G.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t))}}const ch=new Set([a.DD,a.DT,a.LI,a.OPTGROUP,a.OPTION,a.P,a.RB,a.RP,a.RT,a.RTC]),ud=new Set([...ch,a.CAPTION,a.COLGROUP,a.TBODY,a.TD,a.TFOOT,a.TH,a.THEAD,a.TR]),Js=new Set([a.APPLET,a.CAPTION,a.HTML,a.MARQUEE,a.OBJECT,a.TABLE,a.TD,a.TEMPLATE,a.TH]),dA=new Set([...Js,a.OL,a.UL]),lA=new Set([...Js,a.BUTTON]),dd=new Set([a.ANNOTATION_XML,a.MI,a.MN,a.MO,a.MS,a.MTEXT]),ld=new Set([a.DESC,a.FOREIGN_OBJECT,a.TITLE]),fA=new Set([a.TR,a.TEMPLATE,a.HTML]),hA=new Set([a.TBODY,a.TFOOT,a.THEAD,a.TEMPLATE,a.HTML]),mA=new Set([a.TABLE,a.TEMPLATE,a.HTML]),EA=new Set([a.TD,a.TH]);class gA{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,r,n){this.treeAdapter=r,this.handler=n,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=a.UNKNOWN,this.current=t}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===a.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===ee.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(t,r){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=r,this.currentTagId=r,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,r,!0)}pop(){const t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!0)}replace(t,r){const n=this._indexOf(t);this.items[n]=r,n===this.stackTop&&(this.current=r)}insertAfter(t,r,n){const i=this._indexOf(t)+1;this.items.splice(i,0,r),this.tagIDs.splice(i,0,n),this.stackTop++,i===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,i===this.stackTop)}popUntilTagNamePopped(t){let r=this.stackTop+1;do r=this.tagIDs.lastIndexOf(t,r-1);while(r>0&&this.treeAdapter.getNamespaceURI(this.items[r])!==ee.HTML);this.shortenToLength(Math.max(r,0))}shortenToLength(t){for(;this.stackTop>=t;){const r=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(r,this.stackTop<t)}}popUntilElementPopped(t){const r=this._indexOf(t);this.shortenToLength(Math.max(r,0))}popUntilPopped(t,r){const n=this._indexOfTagNames(t,r);this.shortenToLength(Math.max(n,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(Pa,ee.HTML)}popUntilTableCellPopped(){this.popUntilPopped(EA,ee.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(t,r){for(let n=this.stackTop;n>=0;n--)if(t.has(this.tagIDs[n])&&this.treeAdapter.getNamespaceURI(this.items[n])===r)return n;return-1}clearBackTo(t,r){const n=this._indexOfTagNames(t,r);this.shortenToLength(n+1)}clearBackToTableContext(){this.clearBackTo(mA,ee.HTML)}clearBackToTableBodyContext(){this.clearBackTo(hA,ee.HTML)}clearBackToTableRowContext(){this.clearBackTo(fA,ee.HTML)}remove(t){const r=this._indexOf(t);r>=0&&(r===this.stackTop?this.pop():(this.items.splice(r,1),this.tagIDs.splice(r,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===a.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){const r=this._indexOf(t)-1;return r>=0?this.items[r]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===a.HTML}hasInDynamicScope(t,r){for(let n=this.stackTop;n>=0;n--){const i=this.tagIDs[n];switch(this.treeAdapter.getNamespaceURI(this.items[n])){case ee.HTML:{if(i===t)return!0;if(r.has(i))return!1;break}case ee.SVG:{if(ld.has(i))return!1;break}case ee.MATHML:{if(dd.has(i))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,Js)}hasInListItemScope(t){return this.hasInDynamicScope(t,dA)}hasInButtonScope(t){return this.hasInDynamicScope(t,lA)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){const r=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case ee.HTML:{if(Pa.has(r))return!0;if(Js.has(r))return!1;break}case ee.SVG:{if(ld.has(r))return!1;break}case ee.MATHML:{if(dd.has(r))return!1;break}}}return!0}hasInTableScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===ee.HTML)switch(this.tagIDs[r]){case t:return!0;case a.TABLE:case a.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===ee.HTML)switch(this.tagIDs[t]){case a.TBODY:case a.THEAD:case a.TFOOT:return!0;case a.TABLE:case a.HTML:return!1}return!0}hasInSelectScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===ee.HTML)switch(this.tagIDs[r]){case t:return!0;case a.OPTION:case a.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&ch.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&ud.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&ud.has(this.currentTagId);)this.pop()}}const Jo=3;var xt;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"})(xt||(xt={}));const fd={type:xt.Marker};class pA{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(t,r){const n=[],i=r.length,s=this.treeAdapter.getTagName(t),o=this.treeAdapter.getNamespaceURI(t);for(let c=0;c<this.entries.length;c++){const u=this.entries[c];if(u.type===xt.Marker)break;const{element:d}=u;if(this.treeAdapter.getTagName(d)===s&&this.treeAdapter.getNamespaceURI(d)===o){const l=this.treeAdapter.getAttrList(d);l.length===i&&n.push({idx:c,attrs:l})}}return n}_ensureNoahArkCondition(t){if(this.entries.length<Jo)return;const r=this.treeAdapter.getAttrList(t),n=this._getNoahArkConditionCandidates(t,r);if(n.length<Jo)return;const i=new Map(r.map(o=>[o.name,o.value]));let s=0;for(let o=0;o<n.length;o++){const c=n[o];c.attrs.every(u=>i.get(u.name)===u.value)&&(s+=1,s>=Jo&&this.entries.splice(c.idx,1))}}insertMarker(){this.entries.unshift(fd)}pushElement(t,r){this._ensureNoahArkCondition(t),this.entries.unshift({type:xt.Element,element:t,token:r})}insertElementAfterBookmark(t,r){const n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:xt.Element,element:t,token:r})}removeEntry(t){const r=this.entries.indexOf(t);r!==-1&&this.entries.splice(r,1)}clearToLastMarker(){const t=this.entries.indexOf(fd);t===-1?this.entries.length=0:this.entries.splice(0,t+1)}getElementEntryInScopeWithTagName(t){const r=this.entries.find(n=>n.type===xt.Marker||this.treeAdapter.getTagName(n.element)===t);return r&&r.type===xt.Element?r:null}getElementEntry(t){return this.entries.find(r=>r.type===xt.Element&&r.element===t)}}const Xt={createDocument(){return{nodeName:"#document",mode:_t.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return{nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,r){return{nodeName:e,tagName:e,attrs:r,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return{nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return{nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,r){const n=e.childNodes.indexOf(r);e.childNodes.splice(n,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent(e){return e.content},setDocumentType(e,t,r,n){const i=e.childNodes.find(s=>s.nodeName==="#documentType");if(i)i.name=t,i.publicId=r,i.systemId=n;else{const s={nodeName:"#documentType",name:t,publicId:r,systemId:n,parentNode:null};Xt.appendChild(e,s)}},setDocumentMode(e,t){e.mode=t},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){const t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){const r=e.childNodes[e.childNodes.length-1];if(Xt.isTextNode(r)){r.value+=t;return}}Xt.appendChild(e,Xt.createTextNode(t))},insertTextBefore(e,t,r){const n=e.childNodes[e.childNodes.indexOf(r)-1];n&&Xt.isTextNode(n)?n.value+=t:Xt.insertBefore(e,Xt.createTextNode(t),r)},adoptAttributes(e,t){const r=new Set(e.attrs.map(n=>n.name));for(let n=0;n<t.length;n++)r.has(t[n].name)||e.attrs.push(t[n])},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName==="#text"},isCommentNode(e){return e.nodeName==="#comment"},isDocumentTypeNode(e){return e.nodeName==="#documentType"},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,"tagName")},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t}}},uh="html",TA="about:legacy-compat",_A="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",dh=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],AA=[...dh,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],IA=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),lh=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],bA=[...lh,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function hd(e,t){return t.some(r=>e.startsWith(r))}function yA(e){return e.name===uh&&e.publicId===null&&(e.systemId===null||e.systemId===TA)}function NA(e){if(e.name!==uh)return _t.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===_A)return _t.QUIRKS;let{publicId:r}=e;if(r!==null){if(r=r.toLowerCase(),IA.has(r))return _t.QUIRKS;let n=t===null?AA:dh;if(hd(r,n))return _t.QUIRKS;if(n=t===null?lh:bA,hd(r,n))return _t.LIMITED_QUIRKS}return _t.NO_QUIRKS}const md={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},wA="definitionurl",DA="definitionURL",SA=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),OA=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:ee.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:ee.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:ee.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:ee.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:ee.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:ee.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:ee.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:ee.XML}],["xml:space",{prefix:"xml",name:"space",namespace:ee.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:ee.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:ee.XMLNS}]]),MA=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),CA=new Set([a.B,a.BIG,a.BLOCKQUOTE,a.BODY,a.BR,a.CENTER,a.CODE,a.DD,a.DIV,a.DL,a.DT,a.EM,a.EMBED,a.H1,a.H2,a.H3,a.H4,a.H5,a.H6,a.HEAD,a.HR,a.I,a.IMG,a.LI,a.LISTING,a.MENU,a.META,a.NOBR,a.OL,a.P,a.PRE,a.RUBY,a.S,a.SMALL,a.SPAN,a.STRONG,a.STRIKE,a.SUB,a.SUP,a.TABLE,a.TT,a.U,a.UL,a.VAR]);function RA(e){const t=e.tagID;return t===a.FONT&&e.attrs.some(({name:n})=>n===Or.COLOR||n===Or.SIZE||n===Or.FACE)||CA.has(t)}function fh(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===wA){e.attrs[t].name=DA;break}}function hh(e){for(let t=0;t<e.attrs.length;t++){const r=SA.get(e.attrs[t].name);r!=null&&(e.attrs[t].name=r)}}function Hc(e){for(let t=0;t<e.attrs.length;t++){const r=OA.get(e.attrs[t].name);r&&(e.attrs[t].prefix=r.prefix,e.attrs[t].name=r.name,e.attrs[t].namespace=r.namespace)}}function LA(e){const t=MA.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=Oo(e.tagName))}function PA(e,t){return t===ee.MATHML&&(e===a.MI||e===a.MO||e===a.MN||e===a.MS||e===a.MTEXT)}function vA(e,t,r){if(t===ee.MATHML&&e===a.ANNOTATION_XML){for(let n=0;n<r.length;n++)if(r[n].name===Or.ENCODING){const i=r[n].value.toLowerCase();return i===md.TEXT_HTML||i===md.APPLICATION_XML}}return t===ee.SVG&&(e===a.FOREIGN_OBJECT||e===a.DESC||e===a.TITLE)}function kA(e,t,r,n){return(!n||n===ee.HTML)&&vA(e,t,r)||(!n||n===ee.MATHML)&&PA(e,t)}const xA="hidden",UA=8,BA=3;var I;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"})(I||(I={}));const HA={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},mh=new Set([a.TABLE,a.TBODY,a.TFOOT,a.THEAD,a.TR]),Ed={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:Xt,onParseError:null};class FA{constructor(t,r,n=null,i=null){this.fragmentContext=n,this.scriptHandler=i,this.currentToken=null,this.stopped=!1,this.insertionMode=I.INITIAL,this.originalInsertionMode=I.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...Ed,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=r??this.treeAdapter.createDocument(),this.tokenizer=new uA(this.options,this),this.activeFormattingElements=new pA(this.treeAdapter),this.fragmentContextID=n?Oo(this.treeAdapter.getTagName(n)):a.UNKNOWN,this._setContextModes(n??this.document,this.fragmentContextID),this.openElements=new gA(this.document,this.treeAdapter,this)}static parse(t,r){const n=new this(r);return n.tokenizer.write(t,!0),n.document}static getFragmentParser(t,r){const n={...Ed,...r};t??(t=n.treeAdapter.createElement(k.TEMPLATE,ee.HTML,[]));const i=n.treeAdapter.createElement("documentmock",ee.HTML,[]),s=new this(n,i,t);return s.fragmentContextID===a.TEMPLATE&&s.tmplInsertionModeStack.unshift(I.IN_TEMPLATE),s._initTokenizerForFragmentParsing(),s._insertFakeRootElement(),s._resetInsertionMode(),s._findFormInFragmentContext(),s}getFragment(){const t=this.treeAdapter.getFirstChild(this.document),r=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,r),r}_err(t,r,n){var i;if(!this.onParseError)return;const s=(i=t.location)!==null&&i!==void 0?i:HA,o={code:r,startLine:s.startLine,startCol:s.startCol,startOffset:s.startOffset,endLine:n?s.startLine:s.endLine,endCol:n?s.startCol:s.endCol,endOffset:n?s.startOffset:s.endOffset};this.onParseError(o)}onItemPush(t,r,n){var i,s;(s=(i=this.treeAdapter).onItemPush)===null||s===void 0||s.call(i,t),n&&this.openElements.stackTop>0&&this._setContextModes(t,r)}onItemPop(t,r){var n,i;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(i=(n=this.treeAdapter).onItemPop)===null||i===void 0||i.call(n,t,this.openElements.current),r){let s,o;this.openElements.stackTop===0&&this.fragmentContext?(s=this.fragmentContext,o=this.fragmentContextID):{current:s,currentTagId:o}=this.openElements,this._setContextModes(s,o)}}_setContextModes(t,r){const n=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===ee.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&t!==void 0&&r!==void 0&&!this._isIntegrationPoint(r,t)}_switchToTextParsing(t,r){this._insertElement(t,ee.HTML),this.tokenizer.state=r,this.originalInsertionMode=this.insertionMode,this.insertionMode=I.TEXT}switchToPlaintextParsing(){this.insertionMode=I.TEXT,this.originalInsertionMode=I.IN_BODY,this.tokenizer.state=ut.PLAINTEXT}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===k.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==ee.HTML))switch(this.fragmentContextID){case a.TITLE:case a.TEXTAREA:{this.tokenizer.state=ut.RCDATA;break}case a.STYLE:case a.XMP:case a.IFRAME:case a.NOEMBED:case a.NOFRAMES:case a.NOSCRIPT:{this.tokenizer.state=ut.RAWTEXT;break}case a.SCRIPT:{this.tokenizer.state=ut.SCRIPT_DATA;break}case a.PLAINTEXT:{this.tokenizer.state=ut.PLAINTEXT;break}}}_setDocumentType(t){const r=t.name||"",n=t.publicId||"",i=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,r,n,i),t.location){const o=this.treeAdapter.getChildNodes(this.document).find(c=>this.treeAdapter.isDocumentTypeNode(c));o&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location)}}_attachElementToTree(t,r){if(this.options.sourceCodeLocationInfo){const n=r&&{...r,startTag:r};this.treeAdapter.setNodeSourceCodeLocation(t,n)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else{const n=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(n??this.document,t)}}_appendElement(t,r){const n=this.treeAdapter.createElement(t.tagName,r,t.attrs);this._attachElementToTree(n,t.location)}_insertElement(t,r){const n=this.treeAdapter.createElement(t.tagName,r,t.attrs);this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID)}_insertFakeElement(t,r){const n=this.treeAdapter.createElement(t,ee.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,r)}_insertTemplate(t){const r=this.treeAdapter.createElement(t.tagName,ee.HTML,t.attrs),n=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(r,n),this._attachElementToTree(r,t.location),this.openElements.push(r,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,null)}_insertFakeRootElement(){const t=this.treeAdapter.createElement(k.HTML,ee.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,a.HTML)}_appendCommentNode(t,r){const n=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(r,n),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,t.location)}_insertCharacters(t){let r,n;if(this._shouldFosterParentOnInsertion()?({parent:r,beforeElement:n}=this._findFosterParentingLocation(),n?this.treeAdapter.insertTextBefore(r,t.chars,n):this.treeAdapter.insertText(r,t.chars)):(r=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(r,t.chars)),!t.location)return;const i=this.treeAdapter.getChildNodes(r),s=n?i.lastIndexOf(n):i.length,o=i[s-1];if(this.treeAdapter.getNodeSourceCodeLocation(o)){const{endLine:u,endCol:d,endOffset:l}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(o,{endLine:u,endCol:d,endOffset:l})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location)}_adoptNodes(t,r){for(let n=this.treeAdapter.getFirstChild(t);n;n=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(n),this.treeAdapter.appendChild(r,n)}_setEndLocation(t,r){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&r.location){const n=r.location,i=this.treeAdapter.getTagName(t),s=r.type===Ce.END_TAG&&i===r.tagName?{endTag:{...n},endLine:n.endLine,endCol:n.endCol,endOffset:n.endOffset}:{endLine:n.startLine,endCol:n.startCol,endOffset:n.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,s)}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return!1;let r,n;return this.openElements.stackTop===0&&this.fragmentContext?(r=this.fragmentContext,n=this.fragmentContextID):{current:r,currentTagId:n}=this.openElements,t.tagID===a.SVG&&this.treeAdapter.getTagName(r)===k.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(r)===ee.MATHML?!1:this.tokenizer.inForeignNode||(t.tagID===a.MGLYPH||t.tagID===a.MALIGNMARK)&&n!==void 0&&!this._isIntegrationPoint(n,r,ee.HTML)}_processToken(t){switch(t.type){case Ce.CHARACTER:{this.onCharacter(t);break}case Ce.NULL_CHARACTER:{this.onNullCharacter(t);break}case Ce.COMMENT:{this.onComment(t);break}case Ce.DOCTYPE:{this.onDoctype(t);break}case Ce.START_TAG:{this._processStartTag(t);break}case Ce.END_TAG:{this.onEndTag(t);break}case Ce.EOF:{this.onEof(t);break}case Ce.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,r,n){const i=this.treeAdapter.getNamespaceURI(r),s=this.treeAdapter.getAttrList(r);return kA(t,i,s,n)}_reconstructActiveFormattingElements(){const t=this.activeFormattingElements.entries.length;if(t){const r=this.activeFormattingElements.entries.findIndex(i=>i.type===xt.Marker||this.openElements.contains(i.element)),n=r===-1?t-1:r-1;for(let i=n;i>=0;i--){const s=this.activeFormattingElements.entries[i];this._insertElement(s.token,this.treeAdapter.getNamespaceURI(s.element)),s.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=I.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(a.P),this.openElements.popUntilTagNamePopped(a.P)}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case a.TR:{this.insertionMode=I.IN_ROW;return}case a.TBODY:case a.THEAD:case a.TFOOT:{this.insertionMode=I.IN_TABLE_BODY;return}case a.CAPTION:{this.insertionMode=I.IN_CAPTION;return}case a.COLGROUP:{this.insertionMode=I.IN_COLUMN_GROUP;return}case a.TABLE:{this.insertionMode=I.IN_TABLE;return}case a.BODY:{this.insertionMode=I.IN_BODY;return}case a.FRAMESET:{this.insertionMode=I.IN_FRAMESET;return}case a.SELECT:{this._resetInsertionModeForSelect(t);return}case a.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case a.HTML:{this.insertionMode=this.headElement?I.AFTER_HEAD:I.BEFORE_HEAD;return}case a.TD:case a.TH:{if(t>0){this.insertionMode=I.IN_CELL;return}break}case a.HEAD:{if(t>0){this.insertionMode=I.IN_HEAD;return}break}}this.insertionMode=I.IN_BODY}_resetInsertionModeForSelect(t){if(t>0)for(let r=t-1;r>0;r--){const n=this.openElements.tagIDs[r];if(n===a.TEMPLATE)break;if(n===a.TABLE){this.insertionMode=I.IN_SELECT_IN_TABLE;return}}this.insertionMode=I.IN_SELECT}_isElementCausesFosterParenting(t){return mh.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){const r=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case a.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(r)===ee.HTML)return{parent:this.treeAdapter.getTemplateContent(r),beforeElement:null};break}case a.TABLE:{const n=this.treeAdapter.getParentNode(r);return n?{parent:n,beforeElement:r}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){const r=this._findFosterParentingLocation();r.beforeElement?this.treeAdapter.insertBefore(r.parent,t,r.beforeElement):this.treeAdapter.appendChild(r.parent,t)}_isSpecialElement(t,r){const n=this.treeAdapter.getNamespaceURI(t);return sA[n].has(r)}onCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){gb(this,t);return}switch(this.insertionMode){case I.INITIAL:{wn(this,t);break}case I.BEFORE_HTML:{Hn(this,t);break}case I.BEFORE_HEAD:{Fn(this,t);break}case I.IN_HEAD:{zn(this,t);break}case I.IN_HEAD_NO_SCRIPT:{jn(this,t);break}case I.AFTER_HEAD:{Vn(this,t);break}case I.IN_BODY:case I.IN_CAPTION:case I.IN_CELL:case I.IN_TEMPLATE:{gh(this,t);break}case I.TEXT:case I.IN_SELECT:case I.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case I.IN_TABLE:case I.IN_TABLE_BODY:case I.IN_ROW:{ea(this,t);break}case I.IN_TABLE_TEXT:{bh(this,t);break}case I.IN_COLUMN_GROUP:{eo(this,t);break}case I.AFTER_BODY:{to(this,t);break}case I.AFTER_AFTER_BODY:{Ki(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){Eb(this,t);return}switch(this.insertionMode){case I.INITIAL:{wn(this,t);break}case I.BEFORE_HTML:{Hn(this,t);break}case I.BEFORE_HEAD:{Fn(this,t);break}case I.IN_HEAD:{zn(this,t);break}case I.IN_HEAD_NO_SCRIPT:{jn(this,t);break}case I.AFTER_HEAD:{Vn(this,t);break}case I.TEXT:{this._insertCharacters(t);break}case I.IN_TABLE:case I.IN_TABLE_BODY:case I.IN_ROW:{ea(this,t);break}case I.IN_COLUMN_GROUP:{eo(this,t);break}case I.AFTER_BODY:{to(this,t);break}case I.AFTER_AFTER_BODY:{Ki(this,t);break}}}onComment(t){if(this.skipNextNewLine=!1,this.currentNotInHTML){va(this,t);return}switch(this.insertionMode){case I.INITIAL:case I.BEFORE_HTML:case I.BEFORE_HEAD:case I.IN_HEAD:case I.IN_HEAD_NO_SCRIPT:case I.AFTER_HEAD:case I.IN_BODY:case I.IN_TABLE:case I.IN_CAPTION:case I.IN_COLUMN_GROUP:case I.IN_TABLE_BODY:case I.IN_ROW:case I.IN_CELL:case I.IN_SELECT:case I.IN_SELECT_IN_TABLE:case I.IN_TEMPLATE:case I.IN_FRAMESET:case I.AFTER_FRAMESET:{va(this,t);break}case I.IN_TABLE_TEXT:{Dn(this,t);break}case I.AFTER_BODY:{qA(this,t);break}case I.AFTER_AFTER_BODY:case I.AFTER_AFTER_FRAMESET:{WA(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case I.INITIAL:{$A(this,t);break}case I.BEFORE_HEAD:case I.IN_HEAD:case I.IN_HEAD_NO_SCRIPT:case I.AFTER_HEAD:{this._err(t,G.misplacedDoctype);break}case I.IN_TABLE_TEXT:{Dn(this,t);break}}}onStartTag(t){this.skipNextNewLine=!1,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,G.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?pb(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case I.INITIAL:{wn(this,t);break}case I.BEFORE_HTML:{KA(this,t);break}case I.BEFORE_HEAD:{XA(this,t);break}case I.IN_HEAD:{Mt(this,t);break}case I.IN_HEAD_NO_SCRIPT:{tI(this,t);break}case I.AFTER_HEAD:{nI(this,t);break}case I.IN_BODY:{rt(this,t);break}case I.IN_TABLE:{an(this,t);break}case I.IN_TABLE_TEXT:{Dn(this,t);break}case I.IN_CAPTION:{JI(this,t);break}case I.IN_COLUMN_GROUP:{jc(this,t);break}case I.IN_TABLE_BODY:{Ro(this,t);break}case I.IN_ROW:{Lo(this,t);break}case I.IN_CELL:{rb(this,t);break}case I.IN_SELECT:{wh(this,t);break}case I.IN_SELECT_IN_TABLE:{ib(this,t);break}case I.IN_TEMPLATE:{ob(this,t);break}case I.AFTER_BODY:{cb(this,t);break}case I.IN_FRAMESET:{ub(this,t);break}case I.AFTER_FRAMESET:{lb(this,t);break}case I.AFTER_AFTER_BODY:{hb(this,t);break}case I.AFTER_AFTER_FRAMESET:{mb(this,t);break}}}onEndTag(t){this.skipNextNewLine=!1,this.currentToken=t,this.currentNotInHTML?Tb(this,t):this._endTagOutsideForeignContent(t)}_endTagOutsideForeignContent(t){switch(this.insertionMode){case I.INITIAL:{wn(this,t);break}case I.BEFORE_HTML:{ZA(this,t);break}case I.BEFORE_HEAD:{JA(this,t);break}case I.IN_HEAD:{eI(this,t);break}case I.IN_HEAD_NO_SCRIPT:{rI(this,t);break}case I.AFTER_HEAD:{iI(this,t);break}case I.IN_BODY:{Co(this,t);break}case I.TEXT:{VI(this,t);break}case I.IN_TABLE:{li(this,t);break}case I.IN_TABLE_TEXT:{Dn(this,t);break}case I.IN_CAPTION:{eb(this,t);break}case I.IN_COLUMN_GROUP:{tb(this,t);break}case I.IN_TABLE_BODY:{ka(this,t);break}case I.IN_ROW:{Nh(this,t);break}case I.IN_CELL:{nb(this,t);break}case I.IN_SELECT:{Dh(this,t);break}case I.IN_SELECT_IN_TABLE:{sb(this,t);break}case I.IN_TEMPLATE:{ab(this,t);break}case I.AFTER_BODY:{Oh(this,t);break}case I.IN_FRAMESET:{db(this,t);break}case I.AFTER_FRAMESET:{fb(this,t);break}case I.AFTER_AFTER_BODY:{Ki(this,t);break}}}onEof(t){switch(this.insertionMode){case I.INITIAL:{wn(this,t);break}case I.BEFORE_HTML:{Hn(this,t);break}case I.BEFORE_HEAD:{Fn(this,t);break}case I.IN_HEAD:{zn(this,t);break}case I.IN_HEAD_NO_SCRIPT:{jn(this,t);break}case I.AFTER_HEAD:{Vn(this,t);break}case I.IN_BODY:case I.IN_TABLE:case I.IN_CAPTION:case I.IN_COLUMN_GROUP:case I.IN_TABLE_BODY:case I.IN_ROW:case I.IN_CELL:case I.IN_SELECT:case I.IN_SELECT_IN_TABLE:{Ah(this,t);break}case I.TEXT:{GI(this,t);break}case I.IN_TABLE_TEXT:{Dn(this,t);break}case I.IN_TEMPLATE:{Sh(this,t);break}case I.AFTER_BODY:case I.IN_FRAMESET:case I.AFTER_FRAMESET:case I.AFTER_AFTER_BODY:case I.AFTER_AFTER_FRAMESET:{zc(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,t.chars.charCodeAt(0)===E.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1)}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case I.IN_HEAD:case I.IN_HEAD_NO_SCRIPT:case I.AFTER_HEAD:case I.TEXT:case I.IN_COLUMN_GROUP:case I.IN_SELECT:case I.IN_SELECT_IN_TABLE:case I.IN_FRAMESET:case I.AFTER_FRAMESET:{this._insertCharacters(t);break}case I.IN_BODY:case I.IN_CAPTION:case I.IN_CELL:case I.IN_TEMPLATE:case I.AFTER_BODY:case I.AFTER_AFTER_BODY:case I.AFTER_AFTER_FRAMESET:{Eh(this,t);break}case I.IN_TABLE:case I.IN_TABLE_BODY:case I.IN_ROW:{ea(this,t);break}case I.IN_TABLE_TEXT:{Ih(this,t);break}}}}function zA(e,t){let r=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return r?e.openElements.contains(r.element)?e.openElements.hasInScope(t.tagID)||(r=null):(e.activeFormattingElements.removeEntry(r),r=null):_h(e,t),r}function jA(e,t){let r=null,n=e.openElements.stackTop;for(;n>=0;n--){const i=e.openElements.items[n];if(i===t.element)break;e._isSpecialElement(i,e.openElements.tagIDs[n])&&(r=i)}return r||(e.openElements.shortenToLength(Math.max(n,0)),e.activeFormattingElements.removeEntry(t)),r}function VA(e,t,r){let n=t,i=e.openElements.getCommonAncestor(t);for(let s=0,o=i;o!==r;s++,o=i){i=e.openElements.getCommonAncestor(o);const c=e.activeFormattingElements.getElementEntry(o),u=c&&s>=BA;!c||u?(u&&e.activeFormattingElements.removeEntry(c),e.openElements.remove(o)):(o=GA(e,c),n===t&&(e.activeFormattingElements.bookmark=c),e.treeAdapter.detachNode(n),e.treeAdapter.appendChild(o,n),n=o)}return n}function GA(e,t){const r=e.treeAdapter.getNamespaceURI(t.element),n=e.treeAdapter.createElement(t.token.tagName,r,t.token.attrs);return e.openElements.replace(t.element,n),t.element=n,n}function YA(e,t,r){const n=e.treeAdapter.getTagName(t),i=Oo(n);if(e._isElementCausesFosterParenting(i))e._fosterParentElement(r);else{const s=e.treeAdapter.getNamespaceURI(t);i===a.TEMPLATE&&s===ee.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,r)}}function QA(e,t,r){const n=e.treeAdapter.getNamespaceURI(r.element),{token:i}=r,s=e.treeAdapter.createElement(i.tagName,n,i.attrs);e._adoptNodes(t,s),e.treeAdapter.appendChild(t,s),e.activeFormattingElements.insertElementAfterBookmark(s,i),e.activeFormattingElements.removeEntry(r),e.openElements.remove(r.element),e.openElements.insertAfter(t,s,i.tagID)}function Fc(e,t){for(let r=0;r<UA;r++){const n=zA(e,t);if(!n)break;const i=jA(e,n);if(!i)break;e.activeFormattingElements.bookmark=n;const s=VA(e,i,n.element),o=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(s),o&&YA(e,o,s),QA(e,i,n)}}function va(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function qA(e,t){e._appendCommentNode(t,e.openElements.items[0])}function WA(e,t){e._appendCommentNode(t,e.document)}function zc(e,t){if(e.stopped=!0,t.location){const r=e.fragmentContext?0:2;for(let n=e.openElements.stackTop;n>=r;n--)e._setEndLocation(e.openElements.items[n],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const n=e.openElements.items[0],i=e.treeAdapter.getNodeSourceCodeLocation(n);if(i&&!i.endTag&&(e._setEndLocation(n,t),e.openElements.stackTop>=1)){const s=e.openElements.items[1],o=e.treeAdapter.getNodeSourceCodeLocation(s);o&&!o.endTag&&e._setEndLocation(s,t)}}}}function $A(e,t){e._setDocumentType(t);const r=t.forceQuirks?_t.QUIRKS:NA(t);yA(t)||e._err(t,G.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,r),e.insertionMode=I.BEFORE_HTML}function wn(e,t){e._err(t,G.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,_t.QUIRKS),e.insertionMode=I.BEFORE_HTML,e._processToken(t)}function KA(e,t){t.tagID===a.HTML?(e._insertElement(t,ee.HTML),e.insertionMode=I.BEFORE_HEAD):Hn(e,t)}function ZA(e,t){const r=t.tagID;(r===a.HTML||r===a.HEAD||r===a.BODY||r===a.BR)&&Hn(e,t)}function Hn(e,t){e._insertFakeRootElement(),e.insertionMode=I.BEFORE_HEAD,e._processToken(t)}function XA(e,t){switch(t.tagID){case a.HTML:{rt(e,t);break}case a.HEAD:{e._insertElement(t,ee.HTML),e.headElement=e.openElements.current,e.insertionMode=I.IN_HEAD;break}default:Fn(e,t)}}function JA(e,t){const r=t.tagID;r===a.HEAD||r===a.BODY||r===a.HTML||r===a.BR?Fn(e,t):e._err(t,G.endTagWithoutMatchingOpenElement)}function Fn(e,t){e._insertFakeElement(k.HEAD,a.HEAD),e.headElement=e.openElements.current,e.insertionMode=I.IN_HEAD,e._processToken(t)}function Mt(e,t){switch(t.tagID){case a.HTML:{rt(e,t);break}case a.BASE:case a.BASEFONT:case a.BGSOUND:case a.LINK:case a.META:{e._appendElement(t,ee.HTML),t.ackSelfClosing=!0;break}case a.TITLE:{e._switchToTextParsing(t,ut.RCDATA);break}case a.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,ut.RAWTEXT):(e._insertElement(t,ee.HTML),e.insertionMode=I.IN_HEAD_NO_SCRIPT);break}case a.NOFRAMES:case a.STYLE:{e._switchToTextParsing(t,ut.RAWTEXT);break}case a.SCRIPT:{e._switchToTextParsing(t,ut.SCRIPT_DATA);break}case a.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=I.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(I.IN_TEMPLATE);break}case a.HEAD:{e._err(t,G.misplacedStartTagForHeadElement);break}default:zn(e,t)}}function eI(e,t){switch(t.tagID){case a.HEAD:{e.openElements.pop(),e.insertionMode=I.AFTER_HEAD;break}case a.BODY:case a.BR:case a.HTML:{zn(e,t);break}case a.TEMPLATE:{vr(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function vr(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==a.TEMPLATE&&e._err(t,G.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(a.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,G.endTagWithoutMatchingOpenElement)}function zn(e,t){e.openElements.pop(),e.insertionMode=I.AFTER_HEAD,e._processToken(t)}function tI(e,t){switch(t.tagID){case a.HTML:{rt(e,t);break}case a.BASEFONT:case a.BGSOUND:case a.HEAD:case a.LINK:case a.META:case a.NOFRAMES:case a.STYLE:{Mt(e,t);break}case a.NOSCRIPT:{e._err(t,G.nestedNoscriptInHead);break}default:jn(e,t)}}function rI(e,t){switch(t.tagID){case a.NOSCRIPT:{e.openElements.pop(),e.insertionMode=I.IN_HEAD;break}case a.BR:{jn(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function jn(e,t){const r=t.type===Ce.EOF?G.openElementsLeftAfterEof:G.disallowedContentInNoscriptInHead;e._err(t,r),e.openElements.pop(),e.insertionMode=I.IN_HEAD,e._processToken(t)}function nI(e,t){switch(t.tagID){case a.HTML:{rt(e,t);break}case a.BODY:{e._insertElement(t,ee.HTML),e.framesetOk=!1,e.insertionMode=I.IN_BODY;break}case a.FRAMESET:{e._insertElement(t,ee.HTML),e.insertionMode=I.IN_FRAMESET;break}case a.BASE:case a.BASEFONT:case a.BGSOUND:case a.LINK:case a.META:case a.NOFRAMES:case a.SCRIPT:case a.STYLE:case a.TEMPLATE:case a.TITLE:{e._err(t,G.abandonedHeadElementChild),e.openElements.push(e.headElement,a.HEAD),Mt(e,t),e.openElements.remove(e.headElement);break}case a.HEAD:{e._err(t,G.misplacedStartTagForHeadElement);break}default:Vn(e,t)}}function iI(e,t){switch(t.tagID){case a.BODY:case a.HTML:case a.BR:{Vn(e,t);break}case a.TEMPLATE:{vr(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function Vn(e,t){e._insertFakeElement(k.BODY,a.BODY),e.insertionMode=I.IN_BODY,Mo(e,t)}function Mo(e,t){switch(t.type){case Ce.CHARACTER:{gh(e,t);break}case Ce.WHITESPACE_CHARACTER:{Eh(e,t);break}case Ce.COMMENT:{va(e,t);break}case Ce.START_TAG:{rt(e,t);break}case Ce.END_TAG:{Co(e,t);break}case Ce.EOF:{Ah(e,t);break}}}function Eh(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function gh(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function sI(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function oI(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(r,t.attrs))}function aI(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&r&&(e.treeAdapter.detachNode(r),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,ee.HTML),e.insertionMode=I.IN_FRAMESET)}function cI(e,t){e.openElements.hasInButtonScope(a.P)&&e._closePElement(),e._insertElement(t,ee.HTML)}function uI(e,t){e.openElements.hasInButtonScope(a.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&Pa.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,ee.HTML)}function dI(e,t){e.openElements.hasInButtonScope(a.P)&&e._closePElement(),e._insertElement(t,ee.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function lI(e,t){const r=e.openElements.tmplCount>0;(!e.formElement||r)&&(e.openElements.hasInButtonScope(a.P)&&e._closePElement(),e._insertElement(t,ee.HTML),r||(e.formElement=e.openElements.current))}function fI(e,t){e.framesetOk=!1;const r=t.tagID;for(let n=e.openElements.stackTop;n>=0;n--){const i=e.openElements.tagIDs[n];if(r===a.LI&&i===a.LI||(r===a.DD||r===a.DT)&&(i===a.DD||i===a.DT)){e.openElements.generateImpliedEndTagsWithExclusion(i),e.openElements.popUntilTagNamePopped(i);break}if(i!==a.ADDRESS&&i!==a.DIV&&i!==a.P&&e._isSpecialElement(e.openElements.items[n],i))break}e.openElements.hasInButtonScope(a.P)&&e._closePElement(),e._insertElement(t,ee.HTML)}function hI(e,t){e.openElements.hasInButtonScope(a.P)&&e._closePElement(),e._insertElement(t,ee.HTML),e.tokenizer.state=ut.PLAINTEXT}function mI(e,t){e.openElements.hasInScope(a.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(a.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML),e.framesetOk=!1}function EI(e,t){const r=e.activeFormattingElements.getElementEntryInScopeWithTagName(k.A);r&&(Fc(e,t),e.openElements.remove(r.element),e.activeFormattingElements.removeEntry(r)),e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function gI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function pI(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(a.NOBR)&&(Fc(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,ee.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function TI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function _I(e,t){e.treeAdapter.getDocumentMode(e.document)!==_t.QUIRKS&&e.openElements.hasInButtonScope(a.P)&&e._closePElement(),e._insertElement(t,ee.HTML),e.framesetOk=!1,e.insertionMode=I.IN_TABLE}function ph(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ee.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function Th(e){const t=oh(e,Or.TYPE);return t!=null&&t.toLowerCase()===xA}function AI(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ee.HTML),Th(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function II(e,t){e._appendElement(t,ee.HTML),t.ackSelfClosing=!0}function bI(e,t){e.openElements.hasInButtonScope(a.P)&&e._closePElement(),e._appendElement(t,ee.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function yI(e,t){t.tagName=k.IMG,t.tagID=a.IMG,ph(e,t)}function NI(e,t){e._insertElement(t,ee.HTML),e.skipNextNewLine=!0,e.tokenizer.state=ut.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=I.TEXT}function wI(e,t){e.openElements.hasInButtonScope(a.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,ut.RAWTEXT)}function DI(e,t){e.framesetOk=!1,e._switchToTextParsing(t,ut.RAWTEXT)}function gd(e,t){e._switchToTextParsing(t,ut.RAWTEXT)}function SI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===I.IN_TABLE||e.insertionMode===I.IN_CAPTION||e.insertionMode===I.IN_TABLE_BODY||e.insertionMode===I.IN_ROW||e.insertionMode===I.IN_CELL?I.IN_SELECT_IN_TABLE:I.IN_SELECT}function OI(e,t){e.openElements.currentTagId===a.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML)}function MI(e,t){e.openElements.hasInScope(a.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,ee.HTML)}function CI(e,t){e.openElements.hasInScope(a.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(a.RTC),e._insertElement(t,ee.HTML)}function RI(e,t){e._reconstructActiveFormattingElements(),fh(t),Hc(t),t.selfClosing?e._appendElement(t,ee.MATHML):e._insertElement(t,ee.MATHML),t.ackSelfClosing=!0}function LI(e,t){e._reconstructActiveFormattingElements(),hh(t),Hc(t),t.selfClosing?e._appendElement(t,ee.SVG):e._insertElement(t,ee.SVG),t.ackSelfClosing=!0}function pd(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML)}function rt(e,t){switch(t.tagID){case a.I:case a.S:case a.B:case a.U:case a.EM:case a.TT:case a.BIG:case a.CODE:case a.FONT:case a.SMALL:case a.STRIKE:case a.STRONG:{gI(e,t);break}case a.A:{EI(e,t);break}case a.H1:case a.H2:case a.H3:case a.H4:case a.H5:case a.H6:{uI(e,t);break}case a.P:case a.DL:case a.OL:case a.UL:case a.DIV:case a.DIR:case a.NAV:case a.MAIN:case a.MENU:case a.ASIDE:case a.CENTER:case a.FIGURE:case a.FOOTER:case a.HEADER:case a.HGROUP:case a.DIALOG:case a.DETAILS:case a.ADDRESS:case a.ARTICLE:case a.SEARCH:case a.SECTION:case a.SUMMARY:case a.FIELDSET:case a.BLOCKQUOTE:case a.FIGCAPTION:{cI(e,t);break}case a.LI:case a.DD:case a.DT:{fI(e,t);break}case a.BR:case a.IMG:case a.WBR:case a.AREA:case a.EMBED:case a.KEYGEN:{ph(e,t);break}case a.HR:{bI(e,t);break}case a.RB:case a.RTC:{MI(e,t);break}case a.RT:case a.RP:{CI(e,t);break}case a.PRE:case a.LISTING:{dI(e,t);break}case a.XMP:{wI(e,t);break}case a.SVG:{LI(e,t);break}case a.HTML:{sI(e,t);break}case a.BASE:case a.LINK:case a.META:case a.STYLE:case a.TITLE:case a.SCRIPT:case a.BGSOUND:case a.BASEFONT:case a.TEMPLATE:{Mt(e,t);break}case a.BODY:{oI(e,t);break}case a.FORM:{lI(e,t);break}case a.NOBR:{pI(e,t);break}case a.MATH:{RI(e,t);break}case a.TABLE:{_I(e,t);break}case a.INPUT:{AI(e,t);break}case a.PARAM:case a.TRACK:case a.SOURCE:{II(e,t);break}case a.IMAGE:{yI(e,t);break}case a.BUTTON:{mI(e,t);break}case a.APPLET:case a.OBJECT:case a.MARQUEE:{TI(e,t);break}case a.IFRAME:{DI(e,t);break}case a.SELECT:{SI(e,t);break}case a.OPTION:case a.OPTGROUP:{OI(e,t);break}case a.NOEMBED:case a.NOFRAMES:{gd(e,t);break}case a.FRAMESET:{aI(e,t);break}case a.TEXTAREA:{NI(e,t);break}case a.NOSCRIPT:{e.options.scriptingEnabled?gd(e,t):pd(e,t);break}case a.PLAINTEXT:{hI(e,t);break}case a.COL:case a.TH:case a.TD:case a.TR:case a.HEAD:case a.FRAME:case a.TBODY:case a.TFOOT:case a.THEAD:case a.CAPTION:case a.COLGROUP:break;default:pd(e,t)}}function PI(e,t){if(e.openElements.hasInScope(a.BODY)&&(e.insertionMode=I.AFTER_BODY,e.options.sourceCodeLocationInfo)){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e._setEndLocation(r,t)}}function vI(e,t){e.openElements.hasInScope(a.BODY)&&(e.insertionMode=I.AFTER_BODY,Oh(e,t))}function kI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r))}function xI(e){const t=e.openElements.tmplCount>0,{formElement:r}=e;t||(e.formElement=null),(r||t)&&e.openElements.hasInScope(a.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(a.FORM):r&&e.openElements.remove(r))}function UI(e){e.openElements.hasInButtonScope(a.P)||e._insertFakeElement(k.P,a.P),e._closePElement()}function BI(e){e.openElements.hasInListItemScope(a.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(a.LI),e.openElements.popUntilTagNamePopped(a.LI))}function HI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r))}function FI(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function zI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker())}function jI(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(k.BR,a.BR),e.openElements.pop(),e.framesetOk=!1}function _h(e,t){const r=t.tagName,n=t.tagID;for(let i=e.openElements.stackTop;i>0;i--){const s=e.openElements.items[i],o=e.openElements.tagIDs[i];if(n===o&&(n!==a.UNKNOWN||e.treeAdapter.getTagName(s)===r)){e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.stackTop>=i&&e.openElements.shortenToLength(i);break}if(e._isSpecialElement(s,o))break}}function Co(e,t){switch(t.tagID){case a.A:case a.B:case a.I:case a.S:case a.U:case a.EM:case a.TT:case a.BIG:case a.CODE:case a.FONT:case a.NOBR:case a.SMALL:case a.STRIKE:case a.STRONG:{Fc(e,t);break}case a.P:{UI(e);break}case a.DL:case a.UL:case a.OL:case a.DIR:case a.DIV:case a.NAV:case a.PRE:case a.MAIN:case a.MENU:case a.ASIDE:case a.BUTTON:case a.CENTER:case a.FIGURE:case a.FOOTER:case a.HEADER:case a.HGROUP:case a.DIALOG:case a.ADDRESS:case a.ARTICLE:case a.DETAILS:case a.SEARCH:case a.SECTION:case a.SUMMARY:case a.LISTING:case a.FIELDSET:case a.BLOCKQUOTE:case a.FIGCAPTION:{kI(e,t);break}case a.LI:{BI(e);break}case a.DD:case a.DT:{HI(e,t);break}case a.H1:case a.H2:case a.H3:case a.H4:case a.H5:case a.H6:{FI(e);break}case a.BR:{jI(e);break}case a.BODY:{PI(e,t);break}case a.HTML:{vI(e,t);break}case a.FORM:{xI(e);break}case a.APPLET:case a.OBJECT:case a.MARQUEE:{zI(e,t);break}case a.TEMPLATE:{vr(e,t);break}default:_h(e,t)}}function Ah(e,t){e.tmplInsertionModeStack.length>0?Sh(e,t):zc(e,t)}function VI(e,t){var r;t.tagID===a.SCRIPT&&((r=e.scriptHandler)===null||r===void 0||r.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function GI(e,t){e._err(t,G.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function ea(e,t){if(e.openElements.currentTagId!==void 0&&mh.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=I.IN_TABLE_TEXT,t.type){case Ce.CHARACTER:{bh(e,t);break}case Ce.WHITESPACE_CHARACTER:{Ih(e,t);break}}else yi(e,t)}function YI(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,ee.HTML),e.insertionMode=I.IN_CAPTION}function QI(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ee.HTML),e.insertionMode=I.IN_COLUMN_GROUP}function qI(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(k.COLGROUP,a.COLGROUP),e.insertionMode=I.IN_COLUMN_GROUP,jc(e,t)}function WI(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ee.HTML),e.insertionMode=I.IN_TABLE_BODY}function $I(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(k.TBODY,a.TBODY),e.insertionMode=I.IN_TABLE_BODY,Ro(e,t)}function KI(e,t){e.openElements.hasInTableScope(a.TABLE)&&(e.openElements.popUntilTagNamePopped(a.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function ZI(e,t){Th(t)?e._appendElement(t,ee.HTML):yi(e,t),t.ackSelfClosing=!0}function XI(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,ee.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function an(e,t){switch(t.tagID){case a.TD:case a.TH:case a.TR:{$I(e,t);break}case a.STYLE:case a.SCRIPT:case a.TEMPLATE:{Mt(e,t);break}case a.COL:{qI(e,t);break}case a.FORM:{XI(e,t);break}case a.TABLE:{KI(e,t);break}case a.TBODY:case a.TFOOT:case a.THEAD:{WI(e,t);break}case a.INPUT:{ZI(e,t);break}case a.CAPTION:{YI(e,t);break}case a.COLGROUP:{QI(e,t);break}default:yi(e,t)}}function li(e,t){switch(t.tagID){case a.TABLE:{e.openElements.hasInTableScope(a.TABLE)&&(e.openElements.popUntilTagNamePopped(a.TABLE),e._resetInsertionMode());break}case a.TEMPLATE:{vr(e,t);break}case a.BODY:case a.CAPTION:case a.COL:case a.COLGROUP:case a.HTML:case a.TBODY:case a.TD:case a.TFOOT:case a.TH:case a.THEAD:case a.TR:break;default:yi(e,t)}}function yi(e,t){const r=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,Mo(e,t),e.fosterParentingEnabled=r}function Ih(e,t){e.pendingCharacterTokens.push(t)}function bh(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function Dn(e,t){let r=0;if(e.hasNonWhitespacePendingCharacterToken)for(;r<e.pendingCharacterTokens.length;r++)yi(e,e.pendingCharacterTokens[r]);else for(;r<e.pendingCharacterTokens.length;r++)e._insertCharacters(e.pendingCharacterTokens[r]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}const yh=new Set([a.CAPTION,a.COL,a.COLGROUP,a.TBODY,a.TD,a.TFOOT,a.TH,a.THEAD,a.TR]);function JI(e,t){const r=t.tagID;yh.has(r)?e.openElements.hasInTableScope(a.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(a.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=I.IN_TABLE,an(e,t)):rt(e,t)}function eb(e,t){const r=t.tagID;switch(r){case a.CAPTION:case a.TABLE:{e.openElements.hasInTableScope(a.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(a.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=I.IN_TABLE,r===a.TABLE&&li(e,t));break}case a.BODY:case a.COL:case a.COLGROUP:case a.HTML:case a.TBODY:case a.TD:case a.TFOOT:case a.TH:case a.THEAD:case a.TR:break;default:Co(e,t)}}function jc(e,t){switch(t.tagID){case a.HTML:{rt(e,t);break}case a.COL:{e._appendElement(t,ee.HTML),t.ackSelfClosing=!0;break}case a.TEMPLATE:{Mt(e,t);break}default:eo(e,t)}}function tb(e,t){switch(t.tagID){case a.COLGROUP:{e.openElements.currentTagId===a.COLGROUP&&(e.openElements.pop(),e.insertionMode=I.IN_TABLE);break}case a.TEMPLATE:{vr(e,t);break}case a.COL:break;default:eo(e,t)}}function eo(e,t){e.openElements.currentTagId===a.COLGROUP&&(e.openElements.pop(),e.insertionMode=I.IN_TABLE,e._processToken(t))}function Ro(e,t){switch(t.tagID){case a.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,ee.HTML),e.insertionMode=I.IN_ROW;break}case a.TH:case a.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(k.TR,a.TR),e.insertionMode=I.IN_ROW,Lo(e,t);break}case a.CAPTION:case a.COL:case a.COLGROUP:case a.TBODY:case a.TFOOT:case a.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=I.IN_TABLE,an(e,t));break}default:an(e,t)}}function ka(e,t){const r=t.tagID;switch(t.tagID){case a.TBODY:case a.TFOOT:case a.THEAD:{e.openElements.hasInTableScope(r)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=I.IN_TABLE);break}case a.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=I.IN_TABLE,li(e,t));break}case a.BODY:case a.CAPTION:case a.COL:case a.COLGROUP:case a.HTML:case a.TD:case a.TH:case a.TR:break;default:li(e,t)}}function Lo(e,t){switch(t.tagID){case a.TH:case a.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,ee.HTML),e.insertionMode=I.IN_CELL,e.activeFormattingElements.insertMarker();break}case a.CAPTION:case a.COL:case a.COLGROUP:case a.TBODY:case a.TFOOT:case a.THEAD:case a.TR:{e.openElements.hasInTableScope(a.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=I.IN_TABLE_BODY,Ro(e,t));break}default:an(e,t)}}function Nh(e,t){switch(t.tagID){case a.TR:{e.openElements.hasInTableScope(a.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=I.IN_TABLE_BODY);break}case a.TABLE:{e.openElements.hasInTableScope(a.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=I.IN_TABLE_BODY,ka(e,t));break}case a.TBODY:case a.TFOOT:case a.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(a.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=I.IN_TABLE_BODY,ka(e,t));break}case a.BODY:case a.CAPTION:case a.COL:case a.COLGROUP:case a.HTML:case a.TD:case a.TH:break;default:li(e,t)}}function rb(e,t){const r=t.tagID;yh.has(r)?(e.openElements.hasInTableScope(a.TD)||e.openElements.hasInTableScope(a.TH))&&(e._closeTableCell(),Lo(e,t)):rt(e,t)}function nb(e,t){const r=t.tagID;switch(r){case a.TD:case a.TH:{e.openElements.hasInTableScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=I.IN_ROW);break}case a.TABLE:case a.TBODY:case a.TFOOT:case a.THEAD:case a.TR:{e.openElements.hasInTableScope(r)&&(e._closeTableCell(),Nh(e,t));break}case a.BODY:case a.CAPTION:case a.COL:case a.COLGROUP:case a.HTML:break;default:Co(e,t)}}function wh(e,t){switch(t.tagID){case a.HTML:{rt(e,t);break}case a.OPTION:{e.openElements.currentTagId===a.OPTION&&e.openElements.pop(),e._insertElement(t,ee.HTML);break}case a.OPTGROUP:{e.openElements.currentTagId===a.OPTION&&e.openElements.pop(),e.openElements.currentTagId===a.OPTGROUP&&e.openElements.pop(),e._insertElement(t,ee.HTML);break}case a.HR:{e.openElements.currentTagId===a.OPTION&&e.openElements.pop(),e.openElements.currentTagId===a.OPTGROUP&&e.openElements.pop(),e._appendElement(t,ee.HTML),t.ackSelfClosing=!0;break}case a.INPUT:case a.KEYGEN:case a.TEXTAREA:case a.SELECT:{e.openElements.hasInSelectScope(a.SELECT)&&(e.openElements.popUntilTagNamePopped(a.SELECT),e._resetInsertionMode(),t.tagID!==a.SELECT&&e._processStartTag(t));break}case a.SCRIPT:case a.TEMPLATE:{Mt(e,t);break}}}function Dh(e,t){switch(t.tagID){case a.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===a.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===a.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===a.OPTGROUP&&e.openElements.pop();break}case a.OPTION:{e.openElements.currentTagId===a.OPTION&&e.openElements.pop();break}case a.SELECT:{e.openElements.hasInSelectScope(a.SELECT)&&(e.openElements.popUntilTagNamePopped(a.SELECT),e._resetInsertionMode());break}case a.TEMPLATE:{vr(e,t);break}}}function ib(e,t){const r=t.tagID;r===a.CAPTION||r===a.TABLE||r===a.TBODY||r===a.TFOOT||r===a.THEAD||r===a.TR||r===a.TD||r===a.TH?(e.openElements.popUntilTagNamePopped(a.SELECT),e._resetInsertionMode(),e._processStartTag(t)):wh(e,t)}function sb(e,t){const r=t.tagID;r===a.CAPTION||r===a.TABLE||r===a.TBODY||r===a.TFOOT||r===a.THEAD||r===a.TR||r===a.TD||r===a.TH?e.openElements.hasInTableScope(r)&&(e.openElements.popUntilTagNamePopped(a.SELECT),e._resetInsertionMode(),e.onEndTag(t)):Dh(e,t)}function ob(e,t){switch(t.tagID){case a.BASE:case a.BASEFONT:case a.BGSOUND:case a.LINK:case a.META:case a.NOFRAMES:case a.SCRIPT:case a.STYLE:case a.TEMPLATE:case a.TITLE:{Mt(e,t);break}case a.CAPTION:case a.COLGROUP:case a.TBODY:case a.TFOOT:case a.THEAD:{e.tmplInsertionModeStack[0]=I.IN_TABLE,e.insertionMode=I.IN_TABLE,an(e,t);break}case a.COL:{e.tmplInsertionModeStack[0]=I.IN_COLUMN_GROUP,e.insertionMode=I.IN_COLUMN_GROUP,jc(e,t);break}case a.TR:{e.tmplInsertionModeStack[0]=I.IN_TABLE_BODY,e.insertionMode=I.IN_TABLE_BODY,Ro(e,t);break}case a.TD:case a.TH:{e.tmplInsertionModeStack[0]=I.IN_ROW,e.insertionMode=I.IN_ROW,Lo(e,t);break}default:e.tmplInsertionModeStack[0]=I.IN_BODY,e.insertionMode=I.IN_BODY,rt(e,t)}}function ab(e,t){t.tagID===a.TEMPLATE&&vr(e,t)}function Sh(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(a.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):zc(e,t)}function cb(e,t){t.tagID===a.HTML?rt(e,t):to(e,t)}function Oh(e,t){var r;if(t.tagID===a.HTML){if(e.fragmentContext||(e.insertionMode=I.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===a.HTML){e._setEndLocation(e.openElements.items[0],t);const n=e.openElements.items[1];n&&!(!((r=e.treeAdapter.getNodeSourceCodeLocation(n))===null||r===void 0)&&r.endTag)&&e._setEndLocation(n,t)}}else to(e,t)}function to(e,t){e.insertionMode=I.IN_BODY,Mo(e,t)}function ub(e,t){switch(t.tagID){case a.HTML:{rt(e,t);break}case a.FRAMESET:{e._insertElement(t,ee.HTML);break}case a.FRAME:{e._appendElement(t,ee.HTML),t.ackSelfClosing=!0;break}case a.NOFRAMES:{Mt(e,t);break}}}function db(e,t){t.tagID===a.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==a.FRAMESET&&(e.insertionMode=I.AFTER_FRAMESET))}function lb(e,t){switch(t.tagID){case a.HTML:{rt(e,t);break}case a.NOFRAMES:{Mt(e,t);break}}}function fb(e,t){t.tagID===a.HTML&&(e.insertionMode=I.AFTER_AFTER_FRAMESET)}function hb(e,t){t.tagID===a.HTML?rt(e,t):Ki(e,t)}function Ki(e,t){e.insertionMode=I.IN_BODY,Mo(e,t)}function mb(e,t){switch(t.tagID){case a.HTML:{rt(e,t);break}case a.NOFRAMES:{Mt(e,t);break}}}function Eb(e,t){t.chars=He,e._insertCharacters(t)}function gb(e,t){e._insertCharacters(t),e.framesetOk=!1}function Mh(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==ee.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function pb(e,t){if(RA(t))Mh(e),e._startTagOutsideForeignContent(t);else{const r=e._getAdjustedCurrentElement(),n=e.treeAdapter.getNamespaceURI(r);n===ee.MATHML?fh(t):n===ee.SVG&&(LA(t),hh(t)),Hc(t),t.selfClosing?e._appendElement(t,n):e._insertElement(t,n),t.ackSelfClosing=!0}}function Tb(e,t){if(t.tagID===a.P||t.tagID===a.BR){Mh(e),e._endTagOutsideForeignContent(t);return}for(let r=e.openElements.stackTop;r>0;r--){const n=e.openElements.items[r];if(e.treeAdapter.getNamespaceURI(n)===ee.HTML){e._endTagOutsideForeignContent(t);break}const i=e.treeAdapter.getTagName(n);if(i.toLowerCase()===t.tagName){t.tagName=i,e.openElements.shortenToLength(r);break}}}k.AREA,k.BASE,k.BASEFONT,k.BGSOUND,k.BR,k.COL,k.EMBED,k.FRAME,k.HR,k.IMG,k.INPUT,k.KEYGEN,k.LINK,k.META,k.PARAM,k.SOURCE,k.TRACK,k.WBR;function _b(e,t,r){typeof e=="string"&&(r=t,t=e,e=null);const n=FA.getFragmentParser(e,r);return n.tokenizer.write(t,!0),n.getFragment()}const rr=e=>{if(!Se(e))throw Ne("帖子响应必须是对象");return e};function ht(e){if(typeof e!="string")throw Ne("帖子响应字符串字段无效");return e}function Tr(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw Ne("帖子响应数值字段无效");return e}function Zi(e){if(typeof e!="boolean")throw Ne("帖子响应状态无效");return e}function Ab(e,t){if(!Array.isArray(e))throw Ne("帖子响应列表无效");return e.map(t)}function Ib(e){const t=rr(e),r=ht(t.revision);if(!/^(0|[1-9]\d*)$/.test(r))throw Ne("绑定版本无效");return{postId:ht(t.postId),revision:r}}function bb(e){const t=rr(e);return{id:ht(t.id),name:ht(t.name),avatar:ht(t.avatar),isMe:Zi(t.isMe)}}function yb(e){const t=rr(e);return{url:ht(t.url),width:Tr(t.width),height:Tr(t.height)}}function Nb(e){const t=rr(e),r=rr(t.stats),n=rr(t.viewer);return{id:ht(rr(t.binding).postId),title:ht(t.title),text:ht(t.text),author:bb(t.author),content:Ab(t.content,i=>{const s=rr(i);if(s.type==="text")return{type:"text",text:ht(s.text)};if(s.type==="image")return{type:"image",image:yb(s.image)};if(s.type==="link")return{type:"link",url:ht(s.url)};throw Ne("帖子内容类型无效")}),createdAt:Tr(t.createdAt),updatedAt:Tr(t.updatedAt),url:ht(t.url),canComment:Zi(t.canComment),stats:{likes:Tr(r.likes),comments:Tr(r.comments),favorites:Tr(r.favorites)},viewer:{liked:Zi(n.liked),favorited:Zi(n.favorited)}}}const wb=new Set(["address","article","aside","blockquote","div","dl","dt","dd","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","caption","td","th","tr","ul"]);function Db(e){const t=[];let r=!1,n=!1;const i=()=>t.length===0||t[t.length-1].endsWith(`
|
|
6
|
-
`),s=()=>{r&&!i()&&t.push(`
|
|
7
|
-
`),r&&(n=!1),r=!1};function o(c,u=!1){const d="tagName"in c?c.tagName:"";if(["script","style","video"].includes(d))return;if(d==="br"){s(),n=!1,t.push(`
|
|
8
|
-
`);return}const l=wb.has(d);if(l&&t.length>0&&(r=!0),u=u||d==="pre"||d==="textarea","value"in c){const f=c.value;if(!u&&/^[ \t\r\n\f]*$/.test(f)){if(r||i())return;n=!0;return}s(),n&&!t[t.length-1].endsWith(" ")&&t.push(" "),n=!1,t.push(f)}"childNodes"in c&&c.childNodes.forEach(f=>o(f,u)),l&&t.length>0&&(r=!0)}return o(_b(ht(e))),t.join("")}function Ht(e){if(!Se(e))throw Ne("社区评论响应无效");return e}function Jt(e){const t=typeof e=="string"&&/^\d+$/.test(e)?Number(e):e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw Ne("社区评论数值无效");return t}function Gn(e){if(e==null||e===""||e===0||e==="0")return"";if(typeof e!="string"&&!Number.isSafeInteger(e))throw Ne("社区评论 ID 无效");const t=String(e);if(!/^[1-9]\d{0,18}$/.test(t))throw Ne("社区评论 ID 无效");return t}function ta(e){if(typeof e!="string")throw Ne("社区评论文本无效");return e}function xa(e,t,r,n){const i=Ht(e),s=Gn(i.commentid);if(!s)throw Ne("社区评论缺少 ID");const o=i.user==null?{}:Ht(i.user),c=Gn(i.userid??o.userid),u=i.is_support==null?void 0:Jt(i.is_support);if(u!==void 0&&![0,1,2].includes(u))throw Ne("社区评论点赞状态无效");const d=i.imgs==null?void 0:(()=>{if(!Array.isArray(i.imgs))throw Ne("社区评论图片无效");return i.imgs.map(f=>{const h=Ht(f);return{url:ta(h.url),width:Jt(h.width??0),height:Jt(h.height??0)}})})(),l=(d?.length??0)>0||Jt(i.has_imgs??0)>0;return{id:s,rootCommentId:t||s,replyToCommentId:Gn(i.replyid),author:{id:c,name:ta(o.username??""),avatar:ta(o.avatar??""),isMe:c===r},text:Db(i.text),hasImages:l,...d?.length||!l?{images:d??[]}:{},createdAt:Jt(i.create_at),likes:Jt(i.up??0),replies:Jt(i.child_num??0),...u!==void 0?{liked:u===1}:{},canDelete:c===r||n===r}}function Sb(e,t,r,n,i,s){const o=Ht(t),c=o.comments??[];if(!Array.isArray(c))throw Ne("社区评论列表无效");const u=c.map(f=>{if(r)return xa(f,r,n,i);const h=Ht(f).comment;if(!Array.isArray(h)||!h.length)throw Ne("社区评论楼层无效");return xa(h[0],"",n,i)});if(r){if(typeof o.has_more!="boolean")throw Ne("社区回复分页无效");const f=Gn(o.lastval);if(o.has_more&&!f)throw Ne("社区回复缺少游标");return{items:u,cursor:o.has_more?f:"",hasMore:o.has_more}}const d=o.total_page??Ht(e).total_page,l=d==null?u.length>0:s<Jt(d);return{items:u,cursor:l?String(s+1):"",hasMore:l}}function Ob(e,t,r,n,i,s){const o=Ht(t),c=o.current_comment??Ht(e).current_comment,u=[...c==null?[]:[c],...Array.isArray(o.comments)?o.comments:[]];for(const d of u){const l=Ht(d).comment;if(!Array.isArray(l))continue;const f=l.find(h=>Gn(Ht(h).commentid)===r);if(f)return xa(f,n,i,s)}throw{code:"COMMENT_UNAVAILABLE",message:"评论不存在或不可访问"}}const Ch=3e4;function Mb(e){let t=!1,r=!0,n=!1,i=!1,s;const o=()=>t&&r&&!n,c=()=>{clearTimeout(s),s=void 0},u=()=>{c(),o()&&(s=setTimeout(d,Ch*(1+(e.random??Math.random)()*.1)))};async function d(){if(c(),!(!o()||i)){i=!0;try{await e.refresh()}catch{}finally{i=!1,u()}}}return{setEnabled(l){n||t===l||(t=l,t?u():c())},setVisible(l){n||r===l||(r=l,r?d():c())},reset:d,invalidate(l){if(!(!t||n))try{e.emit(l)}catch{}},dispose(){n=!0,c()}}}function Cb(e){const t=new Set;let r=0,n=!1,i,s,o=!1,c=new AbortController,u,d=!1,l,f=0,h=0,_,g,b,N;const y=D=>{if(n||e.operationContext.signal.aborted)throw ne("RUNTIME_DESTROYED","小程序已关闭");if(r!==D)throw ne("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")};function L(){if(d)throw ne("BINDING_CHANGED","关联帖子已更换,请重新打开小程序")}function A(D){throw Se(D)&&D.code==="BINDING_CHANGED"&&(U(),L()),D}function U(){if(!d){d=!0,l=void 0,b?.abort(),c.abort(),H.setEnabled(!1);try{e.emit({changed:["binding"]})}catch{}}}function Q(D){return L(),u&&(u.revision!==D.revision||u.postId!==D.postId)&&(U(),L()),u??=D,u}async function C(D,W){y(D),L();const $=await e.account.getCurrentUserId(W);if(y(D),L(),i!==void 0&&i!==$)throw F(),ne("AUTHORIZATION_CONTEXT_CHANGED","账号已变化,请重试");if(!$)throw ne("UNAUTHORIZED","请先登录小黑盒");if(o&&s!==$)throw ne("AUTHORIZATION_CONTEXT_CHANGED","账号已变化,请重试");i=$}async function P(D,W,$,m=r){const w=Re(Re(e.operationContext,c.signal),$);await C(m,w);const B=await W(w);await C(m,w);const K=await Ii({network:e.network,operationContext:w,subject:"关联帖子",assertUsable:()=>{y(m),L()},...e.requestGate?{gate:{capability:"post",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},D,B);return await C(m,w),K}async function M(D,W,$){try{const m=await P(V_,async B=>{if(!e.authorizationContext)throw ne("METHOD_FORBIDDEN","宿主不支持关联帖子授权上下文");const K=await e.authorizationContext.get(B);if(!K.token||K.expiresAt<=Date.now())throw ne("UNAUTHORIZED","小程序运行上下文已过期");return{runtime_auth_context_token:K.token,action:D,payload:JSON.stringify(W)}},$),w=Je(m,D,"关联帖子");if(!Se(w)||!Se(w.data))throw ne("INVALID_RESPONSE","关联帖子响应缺少数据");return w.data}catch(m){return A(m)}}function V(){if(g)return g;const D=r,W=h,$=M("get",{},e.operationContext.signal).then(m=>{if(y(D),W!==h)return g=void 0,V();Q(Ib(m.binding));const w=Nb(m);if(m.commentsRevision!==void 0&&(typeof m.commentsRevision!="string"||!/^\d+$/.test(m.commentsRevision)))throw ne("INVALID_RESPONSE","评论版本无效");const B=[];if(l){const{stats:K,viewer:ce,...pe}=l,{stats:ue,viewer:Te,...we}=w;JSON.stringify(pe)!==JSON.stringify(we)&&B.push("content"),JSON.stringify([K,ce])!==JSON.stringify([ue,Te])&&B.push("stats")}return m.commentsRevision!==void 0&&_!==void 0&&_!==m.commentsRevision&&B.push("comments"),l=w,f=Date.now(),m.commentsRevision!==void 0&&(_=m.commentsRevision),B.length&&H.invalidate({changed:B}),w}).catch(m=>{if(r===D&&h===W&&Se(m)&&["POST_UNAVAILABLE","POST_NOT_BOUND","POST_TYPE_UNSUPPORTED"].includes(String(m.code))){const w=l!==void 0;l=void 0,w&&H.invalidate({changed:["content","stats"]})}throw m}).finally(()=>{g===$&&(g=void 0)});return g=$,$}function z(D){y(D),L(),h++,f=0}async function te(D,W){const $=r;try{await W()}catch(m){if(n||e.operationContext.signal.aborted||r!==$||m instanceof Error&&m.name==="AbortError")return;try{e.onBackgroundError?.(D,m)}catch{}}}function x(D,W){return z(D),H.invalidate({changed:["comments"]}),M("comments.changed",{bindingRevision:u.revision},W)}async function Y(D){const W=r;await C(W,Re(e.operationContext,D));const $=l&&Date.now()-f<Ch?l:await be(V,D).catch(m=>{throw L(),m});return y(W),L(),$}async function j(D,W,$,m,w){const K=await P(D==="post.setLiked"?j_:z_,()=>({targetId:$,enabled:W.liked===!0||W.favorited===!0}),m,w);(!Se(K)||K.status!=="ok")&&Je(K,D,"帖子互动")}const H=Mb({emit:e.emit,refresh:V});function F(){r++,l&&H.invalidate({changed:["content","stats"]}),l=void 0,f=0,_=void 0,g=void 0,b?.abort(),c.abort(),c=new AbortController,i=void 0,H.reset()}const v=bi(e.account,D=>{s=D,o=!0,i!==void 0&&D!==i&&F()}),R=e.authorization.onEvent(F),q={};for(const D of[...lo,...Zn])q[D]=async(W,$)=>{if(y(r),D==="post.watch"){if(W!==void 0)throw ne("INVALID_ARGUMENT","变化订阅无需参数");if(t.size>=32)throw ne("RATE_LIMITED_BY_RUNTIME","帖子订阅过多");const ue=r;if(L(),await Y($.signal),y(ue),L(),$.signal.aborted)return;if(t.size>=32)throw ne("RATE_LIMITED_BY_RUNTIME","帖子订阅过多");return new Promise((Te,we)=>{const Ae=()=>{$.signal.removeEventListener("abort",Ae),t.delete(Ae),H.setEnabled(t.size>0&&!d),Te()};t.add(Ae),$.signal.addEventListener("abort",Ae,{once:!0}),H.setEnabled(!0);try{$.postProgress({watching:!0})}catch(Ie){$.signal.removeEventListener("abort",Ae),t.delete(Ae),H.setEnabled(t.size>0&&!d),we(Ie)}})}if(Zn.includes(D)&&!$.trustedUserGesture)throw ne("USER_GESTURE_REQUIRED","请通过用户操作发起帖子互动");const w=Rb(D,W);L();const B=r;if(D==="post.get")return JSON.parse(JSON.stringify(await Y($.signal)));let K;D==="post.comments.openEditor"&&(b?.abort(),b=K=new AbortController,N=$.requestId,$={...$,...Re($,K.signal)});const ce=await Y($.signal),pe=i;if(y(B),L(),D==="post.comments.delete"||D==="post.comments.setLiked"){const ue=await P(D==="post.comments.delete"?F_:H_,()=>({body:{comment_id:w.commentId,...D==="post.comments.setLiked"?{support_type:w.liked?1:2}:{}}}),$.signal,B);(!Se(ue)||ue.status!=="ok")&&Je(ue,D,"帖子评论"),te("post.comments.changed",()=>x(B,c.signal));return}if(D.startsWith("post.comments.")){const{cursor:ue,limit:Te}=w,we=$.signal;if(D==="post.comments.list"){const Ae=String(w.rootCommentId??""),Ie=Ae?1:Number(ue||1),ye=Ae?{root_comment_id:Ae,lastval:ue||"",limit:Te??20}:{link_id:ce.id,page:Ie,limit:Te??20,owner_only:0,hide_cy:1,sort_filter:0,index:2},xe=await P(Ae?B_:od,()=>ye,we,B);return Sb(xe,Je(xe,D,"帖子评论"),Ae,pe,ce.author.id,Ie)}if(D==="post.comments.openEditor"){const Ae=e.presentation?.openPostCommentEditor;if(!Ae||!K)throw ne("METHOD_FORBIDDEN","当前宿主不支持评论编辑器");let Ie;if(w.replyToCommentId){const ve=String(w.replyToCommentId),Fe=String(w.rootCommentId??ve),Ge=await P(od,()=>({link_id:ce.id,root_comment_id:Fe,comment_id:ve,page:1,limit:20,owner_only:0,hide_cy:1,sort_filter:0,index:2}),we,B);Ie=Ob(Ge,Je(Ge,D,"帖子评论"),ve,Fe,pe,ce.author.id)}const ye=Re(Re(e.operationContext,c.signal),K.signal),xe=Re(ye,we);await C(B,xe),await be(()=>Ae({postId:ce.id,...Ie?{reply:Ie}:{},lifetimeSignal:ye.signal,onSubmitted(){b!==K||ye.signal.aborted||r!==B||te("post.comments.changed",async()=>{await C(B,ye),!ye.signal.aborted&&await x(B,ye.signal)})}},xe),xe.signal),await C(B,xe);return}}await j(D,w,ce.id,$.signal,B),z(B),te("post.get",V)};return{handlers:q,setVisible:H.setVisible,dismissEditor(D){D===N&&(N=void 0,b?.abort())},dispose(){if(!n){n=!0;for(const D of[...t])D();r++,c.abort(),H.dispose(),v(),R()}}}}const ki={"post.get":[],"post.comments.list":["rootCommentId","cursor","limit"],"post.comments.openEditor":["replyToCommentId","rootCommentId"],"post.comments.delete":["commentId"],"post.comments.setLiked":["commentId","liked"],"post.setLiked":["liked"],"post.setFavorited":["favorited"]};function Rb(e,t){if(ki[e].length===0&&t===void 0)return{};if(!Se(t)||Object.keys(t).some(r=>!ki[e].includes(r)))throw ne("INVALID_ARGUMENT","帖子操作参数无效");for(const r of["liked","favorited"])if(ki[e].includes(r)&&typeof t[r]!="boolean")throw ne("INVALID_ARGUMENT","请提供目标状态");for(const r of["rootCommentId","replyToCommentId","commentId"])if(t[r]!==void 0&&(typeof t[r]!="string"||!/^[1-9]\d{0,18}$/.test(t[r])))throw ne("INVALID_ARGUMENT","评论 ID 无效");if(ki[e].includes("commentId")&&t.commentId===void 0)throw ne("INVALID_ARGUMENT","缺少评论 ID");if(e==="post.comments.openEditor"&&t.rootCommentId!==void 0&&t.replyToCommentId===void 0)throw ne("INVALID_ARGUMENT","根评论 ID 需要同时指定回复目标");if(t.limit!==void 0&&(!Number.isInteger(t.limit)||Number(t.limit)<1||Number(t.limit)>50))throw ne("INVALID_ARGUMENT","分页数量须为 1–50");if(t.cursor!==void 0&&(typeof t.cursor!="string"||!/^(|[1-9]\d{0,18})$/.test(t.cursor)))throw ne("INVALID_ARGUMENT","评论游标无效");if(!t.rootCommentId&&t.cursor&&!Number.isSafeInteger(Number(t.cursor)))throw ne("INVALID_ARGUMENT","评论页码无效");return{...t}}const Lb=new Set(["stdio","attachments","notifications"]),Rh=new Set(["windows-x64","macos-arm64"]),Pb=new Set(["unsigned","valid","invalid","unknown"]),vb=/^[a-f0-9]{64}$/,kb=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),xb=new Set(tf),Ub=new Set([...tf,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Lh=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 Bb(e){const t=async(n,i,s,o)=>{const c=Hb(n);try{kt(i.signal);const u=await s(c,{...e.operationContext,signal:i.signal});return kt(i.signal),u}catch(u){throw Ba(u,o)}},r=async(n,i,s)=>{if(!s.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw p("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const o={...e.operationContext,signal:s.signal},c=await e.companion.getInfo(i,o).then(d=>Fb(d,i)).catch(d=>{throw Ba(d)});kt(s.signal);const u=await e.companionPresentation.confirmCompanionOperation({action:n,companion:c,miniProgram:e.miniProgramPresentation,signal:s.signal});if(kt(s.signal),u.status!=="granted")throw p("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[fo]:(n,i)=>t(n,i,async(s,o)=>Ua(await e.companion.getInfo(s,o),s)),[ho]:(n,i)=>t(n,i,async(s,o)=>Td(await e.companion.getPreparationStatus(s,o))),[mo]:(n,i)=>t(n,i,async(s,o)=>{const c=Td(await e.companion.getPreparationStatus(s,o));return kt(i.signal),c.state!=="ready"&&c.state!=="preparing"&&await r("prepare",s,i),kt(i.signal),Ua(await e.companion.prepare(s,{...o,onProgress:u=>i.postProgress(vh(u))}),s)},"COMPANION_PREPARATION_CANCELLED"),[Eo]:(n,i)=>t(n,i,(s,o)=>e.companion.cancelPreparation(s,o)),[go]:(n,i)=>t(n,i,async(s,o)=>_d(await e.companion.getActiveSession(s,o),s)),[po]:(n,i)=>t(n,i,async(s,o)=>{const c=_d(await e.companion.getActiveSession(s,o),s);return kt(i.signal),c||(await r("launch",s,i),kt(i.signal),kh(await e.companion.launch(s,o),s))}),[To]:(n,i)=>Vr(n,i,e,"write"),[_o]:(n,i)=>Vr(n,i,e,"closeStdin"),[Ao]:(n,i)=>Vr(n,i,e,"terminate"),[Io]:(n,i)=>Vr(n,i,e,"ackOutput"),[bo]:async(n,i)=>{const s=await Vr(n,i,e,"openAttachment");return e.fileRegistry.registerFile(s,"companion-attachment","read")},[yo]:(n,i)=>Vr(n,i,e,"showNotification")}}function Hb(e){if(!le(e)||typeof e.alias!="string"||!eE.test(e.alias))throw p("INVALID_PARAMS","Companion alias 不合法");return e.alias}function kt(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function Vr(e,t,r,n){if(!le(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw p("INVALID_PARAMS","Companion Session controller 不合法");try{kt(t.signal);const i=await r.companion[n](zb(e,n),{...r.operationContext,signal:t.signal});return kt(t.signal),i}catch(i){throw Ba(i)}}function St(){throw p("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Ph(e){return!Array.isArray(e)||e.some(t=>!Lb.has(t))?St():Object.freeze([...new Set(e)])}function Ua(e,t){return!le(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Rh.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!Pb.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?St():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Ph(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function Fb(e,t){const r=Ua(e,t);return!le(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!vb.test(e.sha256)?St():Object.freeze({...r,sha256:e.sha256})}function vh(e){return le(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}):St():St()}function Td(e){return le(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:vh(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&le(e.error)&&typeof e.error.code=="string"&&xb.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:Lh[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):St():St()}function kh(e,t){return!le(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Rh.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?St():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Ph(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function _d(e,t){return e===void 0?void 0:kh(e,t)}function zb(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Wl(r.data))throw p("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 p("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw p("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw p("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function jb(e){return!le(e)||!kb.has(String(e.reason))?St():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):St():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?St():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Vb(e){if(!le(e)||!le(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||!Wl(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:jb(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 Ba(e,t){return le(e)&&typeof e.code=="string"&&Ub.has(e.code)?p(e.code,Lh[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&le(e)&&e.name==="AbortError"?p(t,"Companion 准备已取消"):p("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Ad=5e3,Id=1e4;function st(e){throw{code:"INVALID_PARAMS",message:e}}function Vc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xh(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&st(`${r} 不支持字段: ${n.join(", ")}`)}function Gb(e){if(e===void 0)return{intensity:"light",delay:0};if(!Vc(e))return st("device.vibrate 参数必须是对象");xh(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return st("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Ad?st(`device.vibrate delay 必须是 0-${Ad} 的整数毫秒`):{intensity:r,delay:n}}function Yb(e){return Vc(e)?(xh(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?st("device.setClipboard text 必须是非空字符串"):e.text.length>Id?st(`device.setClipboard text 不能超过 ${Id} 字符`):{text:e.text}):st("device.setClipboard 参数必须是对象")}function Qb(e){return typeof e=="string"?e.trim()?e:st("device.executeProtocol 协议字符串不能为空"):Vc(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?st("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(Ha(e,new Set),e):st("device.executeProtocol 参数必须是协议字符串或协议对象")}function Ha(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||st("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":st("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":st(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&st("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)Ha(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&st("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))Ha(i,t);t.delete(r)}function qb(e){return{[Hs]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),await be(()=>e.presentation.vibrate(Gb(t),n),n.signal)},[Fs]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),await be(()=>e.presentation.setClipboard(Yb(t),n),n.signal)},[zs]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal);const i=Qb(t);await be(()=>e.protocol.invoke(i,n),n.signal)}}}const bd=1e3,Wb=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function $b(e){const t=r=>Re(e.operationContext,r.signal);return{files:{[Ss]:async(r,n)=>{ra(n);const i=na(e.picker),s=Kb(r),o=await ft(()=>i.pickFiles(s,t(n)));return e.registry.registerFiles(o,"external",s.mode,s.multiple?void 0:1)},[Os]:async(r,n)=>{ra(n);const i=na(e.picker),s=Zb(r),o=await ft(()=>i.pickDirectory(s,t(n)));return e.registry.registerDirectory(o,"external",s.mode)},[Ms]:async(r,n)=>{ra(n);const i=na(e.picker),s=Xb(r).suggestedName,o=t(n);if(!i.saveFile)throw At("files.saveFile");const c=await ft(()=>i.saveFile({suggestedName:s},o));return e.registry.registerFile(c,"external","readwrite")}},file:{[ti]:async(r,n)=>{const i=pt(r,["recursive","exclusive"]),s=e.registry.resolveFile(i.target);Gr(s.mode),await ft(()=>s.create(yd(i),t(n)))},[ri]:async(r,n)=>{const i=pt(r),s=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(s),Gr(s.handle.mode),!s.handle.remove)throw At(ri);await ft(()=>s.handle.remove(t(n)))},[Cs]:async(r,n)=>{const i=pt(r);return Nd(async()=>{const s=await e.registry.resolveFile(i.target).stat(t(n));if(!le(s)||s.kind!=="file")throw Dd()})},[ni]:async(r,n)=>{const i=pt(r),s=wd(await ft(()=>e.registry.resolveFile(i.target).read(t(n))));try{const o=new TextDecoder("utf-8",{fatal:!0}).decode(s);return o.charCodeAt(0)===65279?o.slice(1):o}catch{throw p("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Rs]:async(r,n)=>{const i=pt(r,["content"]);typeof i.content!="string"&&It("content 必须是字符串");const s=e.registry.resolveFile(i.target);Gr(s.mode),await ft(()=>s.write(new TextEncoder().encode(i.content),t(n)))},[ii]:async(r,n)=>{const i=pt(r),s=await ft(()=>e.registry.resolveFile(i.target).read(t(n)));return wd(s)},[Ls]:async(r,n)=>{const i=pt(r,["content"]),s=e.registry.resolveFile(i.target);Gr(s.mode),await ft(()=>s.write(ey(i.content),t(n)))},[si]:async(r,n)=>{const i=pt(r),s=await ft(()=>e.registry.resolveFile(i.target).stat(t(n)));return ty(s)}},directory:{[Ps]:async(r,n)=>{const i=pt(r,["recursive","exclusive"]),s=e.registry.resolveDirectory(i.target);Gr(s.mode),await ft(()=>s.create(yd(i),t(n)))},[oi]:async(r,n)=>{const i=pt(r,["recursive"]);if(le(i.target)&&i.target.relativePath===".")throw p("FILE_ACCESS_DENIED","不能删除根目录");const s=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(s),Gr(s.handle.mode),!s.handle.remove)throw At(oi);await ft(()=>s.handle.remove({recursive:i.recursive===void 0?!1:ro(i.recursive,"recursive")},t(n)))},[vs]:async(r,n)=>{const i=pt(r);return Nd(async()=>{const s=await e.registry.resolveDirectory(i.target).stat(t(n));if(!le(s)||s.kind!=="directory")throw Dd()})},[ks]:async(r,n)=>{const i=pt(r,["limit"]),s=Jb(i.limit),o=e.registry.resolveDirectoryEntry(i.target),c=await ft(()=>o.handle.list({limit:s},t(n)));return e.registry.describeListedEntries(o,c,s)}}}}function Kb(e){if(e===void 0)return{mode:"read",multiple:!1};le(e)||It("pickFiles 参数必须是对象"),Po(e,["mode","accept","multiple"]);const t=Uh(e.mode,"read"),r=e.multiple===void 0?!1:ro(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)))&&It("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function Zb(e){return e===void 0?{mode:"read"}:(le(e)||It("pickDirectory 参数必须是对象"),Po(e,["mode"]),{mode:Uh(e.mode,"read")})}function Xb(e){return le(e)||It("saveFile 参数必须是对象"),Po(e,["suggestedName"]),{suggestedName:pi(e.suggestedName,"suggestedName")}}function pt(e,t=[]){return(!le(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&It("文件操作参数必须包含 target"),Po(e,["target",...t]),e}function yd(e){return{recursive:e.recursive===void 0?!1:ro(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:ro(e.exclusive,"exclusive")}}function Uh(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&It("mode 必须是 read 或 readwrite"),e)}function ro(e,t){return typeof e!="boolean"&&It(`${t} 必须是布尔值`),e}function Jb(e){if(e===void 0)return bd;if((!Number.isSafeInteger(e)||e<=0)&&It("limit 必须是正整数"),e>bd)throw p("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Po(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&It(`不支持字段: ${r.join(", ")}`)}function Gr(e){if(e!=="readwrite")throw p("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function ra(e){if(!e.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function na(e){if(!e)throw At("files.external");return e}async function Nd(e){try{return await e(),!0}catch(t){if(Wb.has(Rc(t)??""))return!1;throw sn(t)}}async function ft(e){try{return await e()}catch(t){throw sn(t)}}function ey(e){return e instanceof Uint8Array||It("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&It("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function wd(e){if(!(e instanceof Uint8Array))throw p("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Dd(){return p("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function ty(e){if(!le(e)||e.kind!=="file"||!ry(e.size))throw p("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!ny(e[t]))throw p("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 ry(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ny(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function It(e){throw p("INVALID_PARAMS",e)}const Sd=16*1024,Od=200;function iy(e){const t=yf(e.runtimePermissions);function r(n,i){e.capabilities&&gf(i,e.capabilities);const s=t({kind:"all",permissions:["filesystem"]},i);if(!s.allowed)throw p(s.code,s.message);const o=Re(e.operationContext,n);return Fa(o),o}return{async list(n,i={}){const s=r(i.signal,"directory.list"),o=e.registry.resolveDirectoryEntry({kind:"directory",root:{kind:"sandbox"},relativePath:n}),c=await Md(()=>o.handle.list({limit:Od},s),s);return e.registry.describeListedEntries(o,c,Od).map(({name:u,kind:d})=>({name:u,kind:d}))},async read(n,i={}){const s=i.maxBytes??Sd;if(!Number.isSafeInteger(s)||s<1||s>Sd)throw p("INVALID_PARAMS","诊断读取最多允许 16384 bytes");const o=r(i.signal,"file.readBytes"),c=e.registry.resolveFile({kind:"file",root:{kind:"sandbox"},relativePath:n});if(!c.readPrefix)throw p("DIAGNOSTICS_UNSUPPORTED","当前 Host 不支持有界文件诊断读取");const u=await Md(()=>c.readPrefix({maxBytes:s},o),o);if(!u||!(u.bytes instanceof Uint8Array)||u.bytes.byteLength>s||typeof u.truncated!="boolean")throw p("FILE_IO_FAILED","Host 返回了无效的有界读取结果");return{bytes:new Uint8Array(u.bytes),truncated:u.truncated}}}}function Fa(e){if(e.signal.aborted)throw p("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")}async function Md(e,t){let r;try{const n=await Promise.race([e(),new Promise((i,s)=>{r=()=>s(p("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")),t.signal.addEventListener("abort",r,{once:!0}),t.signal.aborted&&r()})]);return Fa(t),n}catch(n){throw t.signal.aborted&&Fa(t),sn(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const sy=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),ia={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function oy(e){if(e instanceof qe)return p("REQUEST_UNSUPPORTED",ia.REQUEST_UNSUPPORTED);const t=Bh(e);return t!==void 0&&sy.has(t)?p(t,ia[t]??"媒体操作失败"):p("MEDIA_PREPARE_FAILED",ia.MEDIA_PREPARE_FAILED)}function Bh(e){try{if(!le(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const ay=["source","mediaType","maxCount"],Xi=Object.freeze({source:"album",mediaType:"all",maxCount:1});function cy(e){if(e===void 0)return Xi;if(!P0(e))throw p("INVALID_PARAMS",dy(e));return uy(e)}function uy(e){return Object.freeze({source:e.source??Xi.source,mediaType:e.mediaType??Xi.mediaType,maxCount:e.maxCount??Xi.maxCount})}function dy(e){if(!le(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!ay.includes(r));if(t.length>0)return`media.pick 不支持字段: ${t.join(", ")}`;if(e.source!==void 0&&e.source!=="album"&&e.source!=="camera")return"source 必须是 album 或 camera";if(e.mediaType!==void 0&&e.mediaType!=="image"&&e.mediaType!=="video"&&e.mediaType!=="all")return"mediaType 必须是 image、video 或 all";if(e.maxCount!==void 0){if(typeof e.maxCount!="number"||!Number.isSafeInteger(e.maxCount))return"maxCount 必须是安全整数";if(e.source==="camera"&&e.maxCount!==1)return"相机只支持 maxCount 为 1 或省略,不能静默收窄"}return"media.pick 参数不合法"}const ly=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),fy={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class hy{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=my(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const s=n.map((o,c)=>gy(o,i[c]));if(!v0(s))throw Bt("Host 返回的媒体结果未通过协议校验");for(const o of n)this.committed.add(o);return s}catch(s){throw this.registry.revokeFiles(i.map(py).filter(o=>o!==void 0)),s}}releaseBatch(t,r){this.releaseItems(t,r)}dispose(){if(this.disposed)return;this.disposed=!0;const t=[...this.committed];this.committed.clear(),this.releaseItems(t,{...this.operationContext,lifecycle:"cleanup"})}registerBatch(t,r){try{return this.registry.registerFiles(t.map(n=>n.file),"external","read",r)}catch(n){const i=Bh(n);throw i!==void 0&&ly.has(i)?n:Bt("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function Cd(e,t){if(e.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw p("REQUEST_CANCELLED","media.pick 已取消")}function my(e,t){if(!Array.isArray(e))throw Bt("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw Bt("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw Bt("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw Bt("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw Bt("Host 返回了稀疏媒体结果");Ey(e[n],n)}return e}function Ey(e,t){if(!le(e))throw Bt(`第 ${t+1} 项不是对象`);if(!ql({...e,file:fy}))throw Bt(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!le(e.file))throw Bt(`第 ${t+1} 项缺少文件句柄`)}function gy(e,t){const r={mimeType:e.mimeType,size:e.size,width:e.width,height:e.height,previewUrl:e.previewUrl,file:t};return e.type==="video"?{...r,type:"video",durationMs:e.durationMs}:{...r,type:"image"}}function py(e){return"handleId"in e.ref?e.ref.handleId:void 0}function Bt(e){return p("MEDIA_PREPARE_FAILED",e)}function Ty(e){const t=e.media?new hy(e.registry,e.media,e.operationContext):void 0;return{handlers:{[ai]:async(n,i)=>{const s=cy(n);Ay(i);const o=e.media,c=t;if(!o||typeof o.pick!="function"||!c)throw At(ai);const u=Re(e.operationContext,i.signal);Cd(e.operationContext,i.signal);const d=await _y(o,s,u,e.operationContext,i.signal);Cd(e.operationContext,i.signal);try{return c.commit(d,s)}catch(l){throw c.releaseBatch(d,u),l}}},dispose(){t?.dispose()}}}async function _y(e,t,r,n,i){try{return await be(()=>e.pick(t,r),r.signal)}catch(s){throw n.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?p("REQUEST_CANCELLED","media.pick 已取消"):oy(s)}}function Ay(e){if(!e.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const xi=4294967296;function Iy(e){const t=new by;return t.write(e),t.finish()}class by{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<xi?(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=yy(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<xi)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/xi),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/xi)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function yy(e){const t=new Uint8Array(Ny(e));let r=0,n=0;for(;r<e.length;){let i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<e.length){const s=e.charCodeAt(r);s>=56320&&s<=57343&&(r+=1,i=((i&1023)<<10)+(s&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 Ny(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 Hh(e){za(e);const t=Iy(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 za(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 s of e)za(s,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[s,o]of i){if(s==="__proto__")throw new Error("extra object key is not supported");za(o,t+1,r)}r.delete(e)}const wy=["pc","console","mobile"],Dy=["game","wiki"];function no(e){throw{code:"INVALID_PARAMS",message:e}}function Sy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ur(e,t){return typeof e!="string"||!e.trim()?no(t):e.trim()}function Rd(e,t,r){return typeof e!="string"||!t.includes(e)?no(r):e}function Oy(e){const t={target:"game_detail",appId:ur(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Rd(e.gameType,wy,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Rd(e.page,Dy,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=ur(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=ur(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function My(e){return{target:"user_detail",userId:ur(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Cy(e){const t={target:"post_detail",linkId:ur(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=ur(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=ur(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Ry(e){const t={target:"mini_program",miniProgramId:ur(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Ly(e){return Sy(e)?e.target==="game_detail"?Oy(e):e.target==="user_detail"?My(e):e.target==="post_detail"?Cy(e):e.target==="mini_program"?Ry(e):no("navigation.openAppPage target 不支持"):no("navigation.openAppPage options 必须是对象")}function Py(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 vy(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function ky(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 xy(e){const t=e;return t.target==="game_detail"?Py(t):t.target==="user_detail"?vy(t):ky(t)}const Uy="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",By="data-hb-sdk-fullscreen-exit",Hy=3e3,Fy=2e3,Ld="var(--white-70a,rgba(255,255,255,.7))",Pd="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function zy(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(By,""),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 ${Ld}`,`box-shadow:${Pd}`,"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=Uy,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 s=!0,o=!1,c=!1,u,d;function l(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function f(){s||(t.style.width=l())}function h(){d?.cancel(),d=void 0}function _(N=Fy){clearTimeout(u),u=setTimeout(()=>{h(),s=!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")},N)}function g(){h(),s=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Ld,t.style.boxShadow=Pd,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),_()}async function b(){if(!(o||c)){if(!s){g();return}c=!0,clearTimeout(u),h();try{await e()}catch{}finally{c=!1,o||g()}}}return t.addEventListener("click",b),window.addEventListener("resize",f),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"})),_(Hy),{dispose(){o=!0,clearTimeout(u),h(),t.removeEventListener("click",b),window.removeEventListener("resize",f),t.remove()}}}const Fh=1e4;function zh(e,t){const r=new AbortController;let n;const i=()=>{n??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},r.abort()};e.addEventListener("abort",i,{once:!0}),t?.addEventListener("abort",i,{once:!0}),(e.aborted||t?.aborted)&&i();const s=setTimeout(()=>{n??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},r.abort()},Fh);return{signal:r.signal,async run(o){try{return await be(o,r.signal)}catch(c){throw n??c}},dispose(){clearTimeout(s),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function vd(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 sa(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Sn(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function jy(e){let t=0,r=0,n,i,s={mode:"portrait",hideCapsule:!1},o={mode:"portrait",hideCapsule:!1},c;function u(){c?.dispose(),c=void 0}function d(g){if(!g.hideCapsule){u();return}c??=zy(()=>_.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",u,{once:!0});function l(g,b){if(n===g){if(n=void 0,clearTimeout(g.timer),e.operationContext.signal.removeEventListener("abort",f),"error"in b)g.controller.abort();else if(i={options:g.options,result:b.result},s=g.options,d(g.options),e.onApplied?.(g.options),b.result.supported&&!sa(o,g.options)){o={...g.options};try{e.onDisplayChange?.({orientation:o.mode,fullscreen:o.hideCapsule,source:g.source})}catch{}}for(const N of g.subscribers)N.dispose(),"error"in b?N.reject(b.error):N.resolve(b.result);g.subscribers.clear()}}function f(){n&&l(n,{error:Sn()})}function h(g,b){return new Promise((N,y)=>{const L=()=>{g.subscribers.delete(A),A.dispose(),y(Sn()),g.subscribers.size===0&&l(g,{error:Sn()})},A={resolve:N,reject:y,dispose:()=>b?.removeEventListener("abort",L)};g.subscribers.add(A),b?.addEventListener("abort",L,{once:!0}),b?.aborted&&L()})}const _={async runDisplayRequest(g,b,N){const y=++t,L=zh(b,e.operationContext.signal);try{return await L.run(async()=>{if(await N(L.signal),L.signal.aborted)throw Sn();if(vd(g),y<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=y,_.apply(g,L.signal)})}finally{L.dispose()}},async apply(g,b,N="api"){if(Oe(e.operationContext.signal),b?.aborted)throw Sn();const y=vd(g),L=n?.options??s,A={mode:y.orientation??L.mode,hideCapsule:y.fullscreen??L.hideCapsule};A.mode==="landscape"&&(A.hideCapsule=!0);const U=e.presentation.applyOrientation;if(!U)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&sa(n.options,A))return h(n,b);if(n&&l(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&sa(i.options,A))return i.result;i=void 0;const Q={options:A,source:N,controller:new AbortController,subscribers:new Set};n=Q;const C=h(Q,b);return e.operationContext.signal.addEventListener("abort",f,{once:!0}),b||(Q.timer=setTimeout(()=>{l(Q,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Fh)),be(()=>U.call(e.presentation,A,{...e.operationContext,signal:Q.controller.signal}),Q.controller.signal).then(P=>l(Q,{result:P??{supported:!0}}),P=>l(Q,{error:P})),C},dispose(){e.operationContext.signal.removeEventListener("abort",u),u()}};return _}function jh(e){throw{code:"INVALID_PARAMS",message:e}}function kd(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&jh(`${t} 不支持参数`)}function Vy(e){return{[js]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),kd(t,"navigation.close"),await be(()=>e.presentation.close(n),n.signal)},[Vs]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),kd(t,"navigation.reload"),await be(()=>e.presentation.reload(n),n.signal)},[Gs]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal);const i=Ly(t);if(i.target==="mini_program"){let s;if(i.extra!==void 0)try{s=Hh(i.extra)}catch{jh("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const o=e.resetDisplay;if(o){const c=zh(n.signal);try{await c.run(()=>o(c.signal))}finally{c.dispose()}}Oe(n.signal),await be(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...s===void 0?{}:{extra:s}},n),n.signal);return}await be(()=>e.presentation.openAppPage(xy(i),n),n.signal)}}}const xd={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function Gy(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw At("network.upload");const s=Re(r.operationContext,t.signal),o=()=>{if(s.signal.aborted)throw p("UPLOAD_CANCELLED","上传已取消")};o();let c,u;try{c=i.resolveFileEntry(e.from).hostHandle,u=await c.stat(s)}catch(h){throw o(),sn(h)}if(o(),u.kind!=="file"||!Number.isSafeInteger(u.size)||u.size<0)throw p("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&u.size>e.maxBytes)throw p("FILE_TOO_LARGE","文件超过大小限制");let d=0,l=!1;const f=h=>{l||s.signal.aborted||!Number.isSafeInteger(h)||h<d||h>u.size||(d=h,t.postProgress({loaded:d,total:u.size,lengthComputable:!0}))};try{const{from:h,..._}=e,g=await n.upload(c,{..._,expectedBytes:u.size,...e.format==="multipart"?{fileName:e.fileName??c.name}:{}},{...s,onProgress:f});if(l=!0,!Number.isSafeInteger(g.uploadedBytes)||g.uploadedBytes<d||g.uploadedBytes>u.size)throw p("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(g.status>=200&&g.status<300&&g.uploadedBytes!==u.size)throw p("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:g.uploadedBytes,total:u.size,lengthComputable:!0}),g}catch(h){l=!0;const _=Rc(h);throw _&&xd[_]?p(_,xd[_]):s.signal.aborted?p("UPLOAD_CANCELLED","上传已取消"):_?.startsWith("FILE_")||_?.startsWith("DIRECTORY_")?sn(h):p("UPLOAD_NETWORK_FAILED","上传网络失败")}}const Gc="withCredentials",Yy=new Set(["url","method","params","data","headers","timeout",Gc]),Qy=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Gc]),qy=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Ud=3e4,ja=2*1024*1024,Wy=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Vh=/[\u0000-\u0008\u000A-\u001F\u007F]/,$y=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Ky="network.request 不支持 multipart/form-data,请使用专用上传能力";function Zy(e){const t=Xy(e.runtimePermissions);t.firstParty=e.firstParty===!0,t.networkPolicy=t.firstParty?void 0:_f(e.networkPolicy);const r=fN(e.allowedHttpOrigins);return{[Ds]:async(n,i)=>{const s=eN(n,{permission:t,allowedHttpOrigins:r}),o=await Gy(s,i,e),{uploadedBytes:c,...u}=o;return Hd(u)},[ws]:async(n,i)=>{const s=tN(n,{permission:t,allowedHttpOrigins:r});return Cf(s,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Ns]:async(n,i)=>{const s=Re(e.operationContext,i?.signal);Oe(s.signal);const o=Jy(n,{permission:t,allowedHttpOrigins:r});let c;try{c=await be(()=>e.network.request(o,s),s.signal)}catch(u){throw mN(u)?u:EN(u,"REQUEST_UNSUPPORTED")?De("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):De("REQUEST_FAILED","网络请求失败")}return Hd(c)}}}function Xy(e){const t=ot(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Jy(e,t){const r=cn(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(u=>!Yy.has(u));if(n.length>0)throw De("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Gh(r,"network.request");const i=Yc(r,t,"network.request"),s=nN(r.method),o=r.data;o!==void 0&&oN(o),cN(i.headers,o);const c=uN(i.headers,o,i.official);return{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:i.official?"official":"external",...s===void 0?{}:{method:s},...i.params===void 0?{}:{params:i.params},...o===void 0?{}:{data:o},...i.headers===void 0?{}:{headers:i.headers},...c===void 0?{}:{bodyEncoding:c},...i.timeout===void 0?{}:{timeout:i.timeout}}}function eN(e,t){const r=cn(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 De("INVALID_PARAMS","network.upload 包含不支持的字段");const i=Yc(r,t,"network.upload");if(!t.permission.firstParty&&i.official)throw De("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw De("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!Dr(r.from))throw De("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw De("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw De("INVALID_PARAMS","format 必须是 raw 或 multipart");const s=r.method??(r.format==="raw"?"PUT":"POST");if(s!=="POST"&&(r.format!=="raw"||s!=="PUT"))throw De("INVALID_PARAMS","上传 HTTP 方法不支持");const o={from:r.from,format:r.format,request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"upload",method:s,...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 De("INVALID_PARAMS","raw 不接受 multipart 字段");return o}if(Object.keys(i.headers??{}).some(l=>l.toLowerCase()==="content-type"))throw De("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const c=Bd(r.fieldName),u=r.fields===void 0?void 0:cn(r.fields,"fields 必须是字符串字典");for(const[l,f]of Object.entries(u??{}))if(Bd(l),typeof f!="string"||l===c)throw De("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw De("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||Vh.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw De("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:c,fields:u,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>ja)throw De("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...o,fieldName:c,...u===void 0?{}:{fields:{...u}},...r.fileName===void 0?{}:{fileName:Pc(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function Bd(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw De("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function tN(e,t){const r=cn(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(u=>!Qy.has(u));if(n.length>0)throw De("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Gh(r,"network.download");const i=Yc(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw De("INVALID_PARAMS","network.download timeout 必须是有限正数");Gp(i.headers);const s=Dr(r.to),o=Yl(r.to);if(!s&&!o)throw De("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(s&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw De("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let c;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw De("INVALID_PARAMS","suggestedName 必须是字符串");c=Pc(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw De("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw De("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:s?"file":"directory",...c===void 0?{}:{suggestedName:c},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function Yc(e,t,r){const n=rN(e.url,t.allowedHttpOrigins,r),i=xg(n);if(!t.permission.firstParty){const s=t.permission.networkPolicy,o=s?.enforcement==="approved_domains"&&n.protocol==="http:"&&t.allowedHttpOrigins.has(n.origin);if(s&&!o&&(n.protocol!=="https:"||n.port!==""||!s.entries.some(c=>c.domain===n.hostname.toLowerCase())))throw De("PERMISSION_DENIED",`${r} 目标不在平台批准的域名清单中`);if(i&&!t.permission.useOfficialDomain)throw De("PERMISSION_DENIED","当前小程序暂不支持访问官方域名")}if(kg(n.pathname,i))throw De("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...cn(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:iN(e.headers,r),timeout:sN(e.timeout,r)}}function rN(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw De("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw De("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw De("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw De("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw De("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function nN(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw De("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!qy.has(t))throw De("INVALID_PARAMS","network.request method 不合法");return t}function iN(e,t="network.request"){const r=cn(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,s]of Object.entries(r)){const o=i.trim();if(!o||o!==i||!Wy.test(o)||typeof s!="string"||Vh.test(s))throw De("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Ug(o))throw De("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[o]=s}return n}function Gh(e,t){const r=e[Gc];if(r!==void 0&&typeof r!="boolean")throw De("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function sN(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw De("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Ud)throw De("INVALID_PARAMS",`${t} timeout 不能超过 ${Ud}ms`);return e}}function oN(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw De("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(aN(e)>ja)throw De("INVALID_PARAMS",`network.request data 不能超过 ${ja} 字节`)}function aN(e){if(typeof e=="string")return oa(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return oa(e.toString());try{const t=JSON.stringify(e);return t?oa(t):0}catch{throw De("INVALID_PARAMS","network.request data 必须可序列化")}}function cN(e,t){const r=Yh(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 De("INVALID_PARAMS",Ky)}function uN(e,t,r){if(t===void 0)return;const n=Yh(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)||lN(t))?"form":dN(t)?"json":void 0}function Yh(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function dN(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function lN(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function fN(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&&hN(n.hostname)&&t.add(n.origin)}catch{}return t}function hN(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 Hd(e){return Object.keys(e.headers).some(Fd)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Fd(t)))}:e}function Fd(e){const t=e.trim().toLowerCase();return $y.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function mN(e){return e instanceof Error&&e.name==="AbortError"}function EN(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function cn(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw De("INVALID_PARAMS",t);return e}function oa(e){return new TextEncoder().encode(e).length}function De(e,t){return{code:e,message:t}}function gN(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pN(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 TN(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 s=pN(i);s?r.has(s)||(r.add(s),n.push(s)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function _N(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 s=typeof i=="string"?i.trim():"";!s||s.startsWith("#")||s.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):r.has(s)||(r.add(s),n.push(s))}return{invalidMessages:t,values:n}}function Qh(e,t){if(e==null)return{};if(!gN(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=TN(e.topicIds),n=_N(e.topics),i=[...r.invalidMessages,...n.invalidMessages];let s=r.values;t.maxTopicIds!==void 0&&s.length>t.maxTopicIds&&(i.push(`${t.method} post.topicIds 最多允许 ${t.maxTopicIds} 项`),s=s.slice(0,t.maxTopicIds));const o=s.length||n.values.length?{...s.length?{topicIds:s}:{},...n.values.length?{topics:n.values}:{}}:void 0;return o||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:o}}function AN(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function IN(e){try{if(AN(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function Ke(e){throw{code:"INVALID_PARAMS",message:e}}function Ni(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Va(e,t){return typeof e!="string"||!e.trim()?Ke(t):e}function bN(e,t){const r=Va(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?Ke(t):r}catch{return Ke(t)}}function yN(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function qh(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return Ke(`${t} 缺少有效的小程序分享地址`);try{const s=new URL(e.environment.getCurrentHref()),o=new URL("/tools/common_share",s);o.searchParams.set("user_miniprogram_id",i);const c=n?.version?.trim();c&&o.searchParams.set("miniprogram_version",c);const u=s.searchParams.get("h_src");return u?.trim()&&o.searchParams.set("h_src",u),r!==void 0&&o.searchParams.set("extra",r),o.href}catch{return Ke(`${t} 缺少有效的小程序分享地址`)}}function NN(e,t){if(!Ni(e))return Ke("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return Ke("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!yN(r))return Ke("share.showShareMenu channel 不合法");const n=Wh(e.extra,"share.showShareMenu");return{title:Va(e.title,"share.showShareMenu title 必须是非空字符串"),description:Va(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:qh(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:bN(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Wh(e,t){if(e!==void 0)try{return Hh(e)}catch{return Ke(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function $h(e,t){return e.invalidMessage&&await be(()=>IN(t.environment),t.operationContext.signal)?Ke(e.invalidMessage):e.post}function zd(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function wN(e){const t=e.getViewportMetrics();return{left:0,top:0,width:zd(t.windowWidth,0),height:zd(t.windowHeight,0)}}function Ga(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?Ke(t):r}function jd(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?Ke(t):r}function DN(e){return Ni(e)?{left:Ga(e.left,"share.screenshot rect.left 必须是非负数字"),top:Ga(e.top,"share.screenshot rect.top 必须是非负数字"),width:jd(e.width,"share.screenshot rect.width 必须是正数"),height:jd(e.height,"share.screenshot rect.height 必须是正数")}:Ke("share.screenshot rect 必须是对象")}function Vd(e,t){if(e!=null&&!Ni(e))return Ke("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?Ke("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?Ke("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?wN(t):DN(r.rect),...r.delay===void 0?{}:{delay:Ga(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function SN(e,t){Oe(t.operationContext.signal);const r=NN(e,t);let n=Qh(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await $h(n,t);return be(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function ON(e,t){if(Oe(t.operationContext.signal),e!==void 0&&!Ni(e))return Ke("share.copyLink 参数必须是对象");const r=Wh(e?.extra,"share.copyLink"),n=qh(t,"share.copyLink",r);return await be(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Gd(e,t,r,n=!1){Oe(t.operationContext.signal);const i=Qh(Ni(e)?e.post:void 0,{method:"share.screenshot"}),s=await $h(i,t),o=t.identity.get()?.miniProgramId.trim()||void 0,c=MN(),{watermarkTheme:u,...d}=r;let l=!1,f,h,_;try{if(n&&(!t.presentation.supportsLongScreenshot||!t.prepareLongScreenshot))throw{code:"REQUEST_UNSUPPORTED",message:"当前宿主不支持 DOM 长图,请更新宿主"};if(l=!0,await be(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),n){const N=await t.prepareLongScreenshot(r.rect,t.operationContext.signal);f=N.restore,d.rect=N.rect}h=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,u),_={status:"fulfilled",value:await be(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:s,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(b){_={status:"rejected",error:b}}finally{try{h?.()}finally{f?.()}}const g=l?await CN(t.presentation,c,t.operationContext.signal):void 0;if(_.status==="rejected")throw _.error;if(g)throw g;return _.value}function MN(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function CN(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await be(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function RN(e){let t=Promise.resolve();const r=async(n,i)=>{const s=Re(e.operationContext,i.signal,i.requestId),o=Vd(n,e.presentation);(o.rect.top+o.rect.height>1e4||o.rect.left+o.rect.width>2048||o.rect.width*o.rect.height>4e6)&&Ke("长图尺寸超出限制");const c=t.then(()=>Gd(n,{...e,operationContext:s},o,!0));return t=c.then(()=>{},()=>{}),c};return{[Is]:r,[Ts]:(n,i)=>ON(n,{...e,operationContext:Re(e.operationContext,i.signal,i.requestId)}),[_s]:(n,i)=>SN(n,{...e,operationContext:Re(e.operationContext,i.signal,i.requestId)}),[As]:async(n,i)=>{const s=Re(e.operationContext,i.signal,i.requestId);Oe(s.signal);const o=Vd(n,e.presentation),c=t.then(()=>Gd(n,{...e,operationContext:s},o));return t=c.then(()=>{},()=>{}),be(()=>c,s.signal)}}}const Yd=new WeakMap,Ui=new Map;function Kh(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return ng(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Ef(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Zh(e){const t=e.coordinationKey??e.storage;let r;const n=()=>r??=Promise.resolve().then(e.resolveScope).catch(u=>{throw r=void 0,u}),i=async(u,d)=>{const l=await n();let f=Yd.get(t);f||(f=new Map,Yd.set(t,f));const h=f.get(l)??Promise.resolve(),_=async()=>(Oe(u.signal,{preserveReason:!0}),d(l)),g=h.catch(()=>{}).then(()=>e.lock?e.lock(l,_):_());f.set(l,g);try{return await g}finally{f.get(l)===g&&f.delete(l)}},s=async(u,d,l=!1)=>{const f=Br(u,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(g=>g.key.startsWith(f)&&g.value!=="").map(g=>g.key.slice(f.length)))];const h=await e.storage.getRaw(Mi(u),d);if((h===void 0||h==="")&&!l)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let _;try{_=h?JSON.parse(h):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(_)||_.length>Nu||_.some(g=>typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)))throw new Error("本地数据索引异常");return[...new Set(_)]},o=async(u,d)=>{if(e.diagnostics){const h=Br(u,"");return(await e.diagnostics.listRaw(d)).filter(_=>_.key.startsWith(h)&&_.value!=="").map(_=>({..._,key:_.key.slice(h.length)}))}const l=[],f=await s(u,d);for(let h=0;h<f.length;h+=16){Oe(d.signal,{preserveReason:!0});const _=await Promise.all(f.slice(h,h+16).map(async g=>{const b=await e.storage.getRaw(Br(u,g),d);return b!==void 0&&b!==""?{area:"local",key:g,value:b}:void 0}));for(const g of _)g&&l.push(g)}return l},c=u=>{if(!/^[A-Za-z0-9_-]{1,128}$/.test(u))throw Object.assign(new Error("storage key 不合法"),{code:"INVALID_REQUEST"})};return{get(u,d){return c(u),i(d,l=>e.storage.getRaw(Br(l,u),d))},set(u,d,l){return c(u),i(l,async f=>{const h=await s(f,l,!0);if(!h.includes(u)&&h.length>=Nu)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const _=[...new Set([...h,u])];await e.storage.setRaw(Mi(f),JSON.stringify(_),l)}Oe(l.signal,{preserveReason:!0}),await e.storage.setRaw(Br(f,u),d,l),Oe(l.signal,{preserveReason:!0})})},list(u){return i(u,d=>o(d,u))},clear(u){return i(u,async d=>{const l=await s(d,u);e.diagnostics||await e.storage.setRaw(Mi(d),JSON.stringify(l),u);for(let f=0;f<l.length;f+=16){Oe(u.signal,{preserveReason:!0});const _=(await Promise.allSettled(l.slice(f,f+16).map(g=>e.storage.setRaw(Br(d,g),"",u)))).find(g=>g.status==="rejected");if(_)throw _.reason}Oe(u.signal,{preserveReason:!0}),await e.storage.setRaw(Mi(d),"[]",u)})}}}function Xh(e,t){if(typeof navigator<"u"&&navigator.locks)return new Promise((n,i)=>{navigator.locks.request(`hb-miniprogram-storage:${e}`,()=>t().then(n,i)).catch(i)});const r=(Ui.get(e)??Promise.resolve()).catch(()=>{}).then(t);return Ui.set(e,r),r.finally(()=>{Ui.get(e)===r&&Ui.delete(e)})}const LN=128,PN=/^[A-Za-z0-9_-]+$/;function vN(e){const t=e.scopedStorage??Zh({storage:e.storage,resolveScope:()=>Kh({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[Jn]:async n=>{Oe(e.operationContext.signal);const i=Qd(n,Jn,e.storageLimits?.maxKeyLength),s=await be(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:qd(s)}},[ei]:async n=>{Oe(e.operationContext.signal);const i=Jh(n,"storage.setStorage 参数必须是对象"),s=Qd(i,ei,e.storageLimits?.maxKeyLength),o=kN(i.data,e.storageLimits?.maxValueBytes);await be(()=>t.set(s,o,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(Oe(e.operationContext.signal),(await be(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?Mr("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const s=i.value;return{area:i.area,key:i.key,value:qd(s),serializedValue:s,bytes:em(s)}}).sort((i,s)=>i.key.localeCompare(s.key)))}}}function Qd(e,t,r=LN){const i=Jh(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Mr("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!PN.test(i))throw Mr("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function kN(e,t){let r;try{r=JSON.stringify(e)}catch{throw Mr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw Mr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&em(r)>t)throw Mr("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function qd(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Jh(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Mr("INVALID_PARAMS",t);return e}function em(e){return new TextEncoder().encode(e).length}function Mr(e,t){return{code:e,message:t}}const Wd=120;function sr(e){throw{code:"INVALID_PARAMS",message:e}}function Qc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tm(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&sr(`${r} 不支持字段: ${n.join(", ")}`)}function xN(e){if(!Qc(e))return sr("ui.showToast 参数必须是对象");if(tm(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return sr("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Wd)return sr(`ui.showToast message 不能超过 ${Wd} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return sr("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function UN(e){return e===void 0?{dismissible:!1}:Qc(e)?(tm(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?sr("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):sr("ui.showLoading 参数必须是对象")}function BN(e){e!==void 0&&(!Qc(e)||Object.keys(e).length)&&sr("ui.hideLoading 不支持参数")}function HN(e){return{[xs]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),await be(()=>e.presentation.showToast(xN(t),n),n.signal)},[Us]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),await be(()=>e.presentation.showLoading(UN(t),n),n.signal)},[Bs]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),BN(t),await be(()=>e.presentation.hideLoading(n),n.signal)}}}const FN={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return Ue(e,"当前用户首页资料接口响应异常")}},zN=3e4;function jN(e,t,r={}){const n=r.ttlMs??zN,i=r.requestPolicyEnabled!==!1,s=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let o=0,c,u;async function d(){let f;try{f=await Do(e,FN,void 0,{...t,credentials:"heybox-session",...s?{gate:s}:{}})}catch(h){throw t.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):h instanceof qe?p("REQUEST_UNSUPPORTED",h.message):h instanceof Ai?p("INVALID_RESPONSE","user home_v2 响应不合法"):h instanceof on?p("REQUEST_FAILED","user home_v2 请求失败"):h instanceof _i?i&&(h.status===403||h.status===429)?p("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:h.status,...h.retryAfterMs===void 0?{}:{retryAfterMs:h.retryAfterMs}}):p("REQUEST_FAILED",h.message):GN(h)?h:p("REQUEST_FAILED","user home_v2 请求失败")}return VN(f,"user home_v2")}function l(f){const h=Date.now();if(c?.userId===f&&c.expiresAt>h)return Promise.resolve(c.value);if(u?.userId===f&&u.generation===o)return u.promise;const _=o,g=d().then(b=>(o===_&&(c={userId:f,value:b,expiresAt:Date.now()+n}),b)).finally(()=>{u?.promise===g&&(u=void 0)});return u={userId:f,generation:_,promise:g},g}return{get:l,clear(){o+=1,c=void 0,u=void 0}}}function VN(e,t){if(!le(e))throw p("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 p(n,r)}if(!le(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function GN(e){return le(e)&&typeof e.code=="string"&&typeof e.message=="string"}const YN={auth:"optional",channel:"api",id:"heybox.bbs.app.profile.follow.user.post",method:"POST",path:"/bbs/app/profile/follow/user",bodyEncoding:"form",failurePresentation:"none",query(e){return e.query?{...e.query}:void 0},body(e){return{...e.body??{}}},parse(e,t){return Ue(e,"关注用户接口响应异常")}},QN={auth:"none",channel:"api",id:"heybox.user_miniprogram.runtime.author.follow_status.post",method:"POST",path:"/user_miniprogram/runtime/author/follow_status",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return Ue(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowStatus 接口响应异常")}},qN={auth:"none",channel:"api",id:"heybox.user_miniprogram.runtime.author.follow_guidance.begin.post",method:"POST",path:"/user_miniprogram/runtime/author/follow_guidance/begin",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return Ue(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowGuidanceBegin 接口响应异常")}},WN={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 Ue(e,"Steam 游戏库接口响应异常")}};function $N(e,t=Sa){const r=Kp({version:"2",validate:ZN}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):Sa,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 $d(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 KN(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 ZN(e){if(!le(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Kd(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Kr();for(const t of e.gameList){if(!le(t)||!Ya(t.appid)||!Ya(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Kr();for(const r of["image","portraitImage","icon"])XN(t,r);for(const r of["playtimeForever","playtime2Weeks"])Kd(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Kr()}return e}function Ya(e){return typeof e=="number"&&Number.isFinite(e)}function Kd(e,t){if(e[t]!==void 0&&!Ya(e[t]))throw Kr()}function XN(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Kr()}function Kr(){return p("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const rm=20,JN=100,ew=128,nm=0,im="weeks",tw=100,rw=new Set(["weeks","all","achieved"]);function nw(){return{nickname:"",avatar:""}}function iw(e){const t=jN(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??Pf(),i=$N(n,r?e.steamGameListTtlMs:0);let s;const o=new Map;let c=Promise.resolve();function u(j,H){const F=JSON.stringify([j,H]);return(!s||s.key!==F)&&(s={key:F,scope:n.createScope(H,n.createScope(j))}),s.scope}function d(){const j=s;s=void 0,j&&n.invalidateScope(j.scope).catch(()=>{}),o.clear()}const l=Qf({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??jf))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let h,_,g=0,b=!1;const N=e.account.onChange(()=>{g+=1,t.clear(),l.invalidate(),d()}),y=e.authorization.onEvent((j,H)=>{j==="user_info_authorization_change"&&Object.values(H).some(F=>F==="denied")&&(g+=1,t.clear(),l.invalidate(),d(),c=c.then(async()=>{if(b)return;const F=await e.account.getCurrentUserId(e.operationContext);typeof F=="string"&&F.trim()&&await n.invalidateScope(u(A(),F.trim()))}).catch(()=>{}))});function L(){if(b||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function A(){const j=e.identity.get()?.miniProgramId?.trim();if(!j)throw p("INVALID_STATE","用户能力缺少 canonical 小程序身份");return j}async function U(){L(),await c,L();let j;try{j=await e.account.getCurrentUserId(e.operationContext)}catch(H){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):On(H)?H:p("REQUEST_FAILED","读取小黑盒账号失败")}return typeof j=="string"&&j.trim()?j.trim():void 0}async function Q(j,H){const F=await U();if(g!==H||F!==j)throw p("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function C(j,H,F=e.operationContext.signal){try{return await Do(e.network,j,H,{...e.operationContext,signal:F,credentials:"heybox-session",...f?{gate:f}:{}})}catch(v){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):v instanceof qe?p("REQUEST_UNSUPPORTED",v.message):v instanceof Ai?p("INVALID_RESPONSE","用户接口响应不合法"):v instanceof on?p("REQUEST_FAILED","用户请求失败"):v instanceof _i?r&&(v.status===403||v.status===429)?p("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:v.status,...v.retryAfterMs===void 0?{}:{retryAfterMs:v.retryAfterMs}}):p("REQUEST_FAILED",v.message):On(v)?v:p("REQUEST_FAILED","用户请求失败")}}async function P(j,H){if(!e.authorizationContext)return{mini_program_id:j};let F;try{F=await be(()=>e.authorizationContext.get({...e.operationContext,signal:H}),H)}catch(v){if(On(v))throw v;const R=p("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(R,"cause",{configurable:!0,value:v}),R}if(!F.token?.trim())throw p("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:j,runtime_auth_context_token:F.token}}async function M(){L();const j=A(),H=g,F=await U();if(!F){if(g!==H)throw p("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const v=await P(j,e.operationContext.signal);await Q(F,H);const R=await C(QN,v);if(await Q(F,H),A()!==j)throw p("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Jd(Xd(R))}function V(j,H){if(!j)return Promise.reject(p("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(H?.aborted)return Promise.reject(p("REQUEST_CANCELLED","关注操作已取消"));if(h)return Promise.reject(p("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(p("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const F=z(H).finally(()=>{h===F&&(h=void 0)});return h=F,F}async function z(j){L();const H=A(),F=new AbortController;_=F;const v=()=>F.abort();e.operationContext.signal.addEventListener("abort",v,{once:!0}),j?.addEventListener("abort",v,{once:!0});let R=()=>{},q=!1;try{try{await be(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:F.signal}),F.signal)}catch(Te){throw On(Te)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(Te.code)?p("FOLLOW_CANCELLED","已取消小黑盒登录"):Te}L();const D=g;R=e.account.onChange(()=>{q=!0,v()});const W=await be(U,F.signal);if(!W)throw p("FOLLOW_CANCELLED","未完成小黑盒登录");const $=async()=>{if(await be(()=>Q(W,D),F.signal),L(),A()!==H)throw p("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await $();const m=await P(H,F.signal);await $();const w=hw(),B=await be(()=>C(qN,{...m,request_id:w},F.signal),F.signal);await $();const K=Xd(B);if(K.status!=="notFollowing")return Jd(K);if(K.rateLimited)throw p("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const ce=await be(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:H,signal:F.signal}),F.signal);if(await $(),ce!=="confirmed")throw p("FOLLOW_CANCELLED","已取消关注作者");const pe=K.authorId,ue=await be(()=>C(YN,{body:{following_id:pe}},F.signal),F.signal);if(await $(),ue.status!=="ok"){const Te=["login","relogin","lack_token"].includes(ue.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw p(Te,typeof ue.msg=="string"&&ue.msg.trim()?ue.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(D){throw L(),q?p("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):j?.aborted?p("REQUEST_CANCELLED","关注操作已取消"):On(D)?D:p("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{R(),e.operationContext.signal.removeEventListener("abort",v),j?.removeEventListener("abort",v),_===F&&(_=void 0)}}async function te(){A();const j=g,H=await U();if(!H)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[F,v]=await Promise.all([e.authorization.getOrCreateLocalIdentity(H),x(H).catch(()=>nw())]);return await Q(H,j),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:F.appUserId,profile:v,...F.steamId?{steam_id:F.steamId}:{}}}}function x(j){return l.read(j,()=>C(Yf,void 0).then(H=>{const F=Qa(H,"账号基础信息");if(F.display_username!==void 0&&typeof F.display_username!="string")throw p("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(F.display_avatar!==void 0&&typeof F.display_avatar!="string")throw p("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:F.display_username??"",avatar:F.display_avatar??""}}))}async function Y(j){const H=sw(j),F=A(),v=g,R=await U();if(!R)return d(),{isLogin:!1,isBound:!1,data:null};const q=await t.get(R);await Q(R,v);const D=sm(q.steam_id_info);if(Object.keys(D).length===0)return await n.invalidateScope(u(F,R)).catch(()=>{}),await Q(R,v),o.delete(JSON.stringify([F,R])),{isLogin:!0,isBound:!1,data:null};const W=JSON.stringify([F,R]),$=u(F,R),m=$d({...H,steamId:void 0},D),w=om(D.personal_infomation_open??D.personal_information_open),B=JSON.stringify([m??null,w??null]),K=o.get(W);K&&K.identity!==B&&(await n.invalidateScope($).catch(()=>{}),await Q(R,v));const ce={identity:B,scope:n.createScope(B,$)};o.set(W,ce);const pe=$d(H,D),ue=pe?i.persistent:i.unresolved,Te=n.createScope(pe??"unresolved",ce.scope),we=async()=>{if(await Q(R,v),A()!==F||o.get(W)?.identity!==B)throw p("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},Ae=await ue.read({scope:Te,key:KN({miniProgramId:F,userId:R,effectiveSteamId:pe,personalInformationOpen:w,query:H}),signal:e.operationContext.signal,load:async Ie=>{const ye=await C(WN,{userId:R,...H,personalInformationOpen:w},Ie);return await we(),dw(Qa(ye,"Steam 游戏库"),H)}}).catch(async Ie=>{throw await we(),Ie});return await we(),{isLogin:!0,isBound:!0,data:Ae}}return{getFollowStatus:M,requestFollowAuthor:V,getInfo:te,getSteamGameList:Y,async invalidateSteamGameListCache(){const j=A(),H=g,F=await U();if(!F)return;const v=u(j,F);await Promise.all([i.persistent.invalidateScope(v),i.unresolved.invalidateScope(v)]),t.clear(),o.delete(JSON.stringify([j,F])),await Q(F,H)},dispose(){b||(b=!0,_?.abort(),g+=1,N(),y(),t.clear(),l.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function sw(e){if(e==null)return{limit:rm,offset:nm,sort:im,includeHidden:!1};if(!le(e))throw or("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw or(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:ow(e.limit),offset:aw(e.offset),sort:cw(e.sort),includeHidden:uw(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>ew)throw or("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw or("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,tw))}return r}function ow(e){if(e===void 0)return rm;if(!Number.isInteger(e)||Number(e)<1)throw or("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),JN)}function aw(e){if(e===void 0)return nm;if(!Number.isInteger(e)||Number(e)<0)throw or("user.getSteamGameList offset 必须是非负整数");return Number(e)}function cw(e){if(e===void 0)return im;if(typeof e!="string"||!rw.has(e))throw or("user.getSteamGameList sort 不支持");return e}function uw(e){if(e===void 0)return!1;if(typeof e!="boolean")throw or("user.getSteamGameList includeHidden 必须是 boolean");return e}function dw(e,t){if(!Array.isArray(e.game_list))throw p("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(lw).filter(c=>c!==void 0),n=io(e.total),i=t.offset+r.length,s={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(s.total=n,s.hasMore=i<n);const o=om(e.is_me);return o!==void 0&&(s.isMe=o),s}function lw(e){const t=sm(e),r=io(t.appid),n=io(t.steam_appid)??r,i=qc(t.name);if(r===void 0||n===void 0||!i)return;const s={appid:r,steamAppid:n,name:i};aa(s,"image",t.image),typeof t.vertical_head_image=="string"&&aa(s,"portraitImage",t.vertical_head_image),aa(s,"icon",t.appicon??t.icon),Zd(s,"playtimeForever",t.playtime_forever),Zd(s,"playtime2Weeks",t.playtime_2weeks);const o=fw(t.external_tags??t.tags);return o.length&&(s.tags=o),s}function Qa(e,t){if(!le(e))throw p("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 p(n,r)}if(!le(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function sm(e){return le(e)?e:{}}function qc(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function fw(e){return Array.isArray(e)?e.map(qc).filter(Boolean):[]}function io(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function om(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function aa(e,t,r){const n=qc(r);n&&Object.assign(e,{[t]:n})}function Zd(e,t,r){const n=io(r);n!==void 0&&Object.assign(e,{[t]:n})}function or(e){return p("INVALID_PARAMS",e)}function On(e){return le(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Xd(e){const t=Qa(e,"关注状态");if(![0,1,2].includes(t.follow_status)||typeof t.author_id!="string"||!/^[1-9]\d*$/.test(t.author_id)||typeof t.rate_limited!="boolean")throw p("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Jd(e){return e.status}function hw(){const e=globalThis.crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function mw(e){return{[hs]:async t=>(Bi(t,"user.getFollowStatus"),e.user.getFollowStatus()),[ms]:async(t,r)=>(Bi(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[Es]:async t=>(Bi(t,"user.getInfo"),e.user.getInfo()),[gs]:async(t,r)=>{Bi(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[ps]:async t=>e.user.getSteamGameList(t)}}function Bi(e,t){if(e!==void 0)throw p("INVALID_PARAMS",`${t} 不接收入参`)}function Ew(){return p("USER_DATA_PERMISSION_STATE_INVALID","本地用户数据许可状态异常,已停止访问")}function el(e){return p("USER_DATA_PERMISSION_SAVE_FAILED","本次运行已停止访问,设置未保存,请重试",e===void 0?void 0:{reason:e instanceof Error?e.message:String(e)})}function gw(e){const t=e.managedResources??Ir,r=typeof e.storage.withLock=="function"||typeof navigator<"u"&&!!navigator.locks,n=e.hash??Sc,i=new Map,s=new Set;let o=!1;function c(){if(o)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function u(A,U){if(e.storage.withLock)return e.storage.withLock(l(A),U);if(typeof navigator<"u"&&navigator.locks)return Xh(l(A),U);throw p("REQUEST_UNSUPPORTED","当前宿主不支持跨实例保存资料许可")}function d(A){return lg({miniProgramId:e.resolveMiniProgramId(),userId:A,environment:e.resolveEnvironment()})}function l(A){return sg(dg(d(A)))}function f(A,U){return e.purposeOf?n(Xl(A,e.revisionOf(A),U,e.purposeOf(A))):n(`${A}\0${e.revisionOf(A)}\0${U}`)}function h(A,U){return`${A}\0${U}`}async function _(A,U){let Q;try{Q=await e.storage.getRaw(l(A),U)}catch(P){throw c(),U.signal.aborted?p("REQUEST_CANCELLED","许可操作已取消"):p("USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","无法读取本地用户数据许可",{reason:P instanceof Error?P.message:String(P)})}if(c(),U.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");const C=Q===void 0||Q===""?void 0:ug(Q);if(Q!==void 0&&Q!==""&&C===void 0)throw Ew();return C??{schema_version:1,records:{}}}async function g(A,U,Q){if(c(),Q.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");await e.storage.setRaw(l(A),JSON.stringify(U),Q)}function b(A){return A?.revision??0}function N(A,U,Q){const C=new Set(Q.declared??[]),P=new Set(t);for(const z of Object.keys(U.records))tr(z)&&P.add(z);for(const z of i.keys())z.startsWith(`${A}\0`)&&P.add(z.slice(A.length+1));const V=[...P].sort((z,te)=>{const x=Ir.indexOf(z),Y=Ir.indexOf(te);return(x<0?Number.MAX_SAFE_INTEGER:x)-(Y<0?Number.MAX_SAFE_INTEGER:Y)}).map(z=>{const te=U.records[z],x=b(te),Y=Q.egressTier===void 0?void 0:f(z,Q.egressTier),j=i.get(h(A,z)),H=j!==void 0&&j.revision===x&&(Y===void 0||j.consentFingerprint===Y);return{resource:z,name:Nc(z)?.name??z,purposeText:e.purposeOf?.(z)??"",scopeFingerprint:Y??"",declared:C.has(z),available:C.has(z),decision:te?.decision??"ask",revision:x,...te?.decision==="allow"&&te.consentFingerprint?{consentFingerprint:te.consentFingerprint}:{},sessionAllowed:H,allowed:!s.has(h(A,z))&&C.has(z)&&te?.decision!=="deny"&&(H||r&&te?.decision==="allow"&&Y!==void 0&&te.consentFingerprint===Y)}});return Object.freeze({schema_version:1,canPersist:r,resources:Object.freeze(V),...Q.egressTier===void 0?{}:{egressTier:Q.egressTier}})}function y(A,U,Q,C){const P=U.records[Q],M=h(A,Q);if(s.has(M))return{status:"denied",reason:"tightening"};if(P?.decision==="deny")return{status:"denied",reason:"deny"};const V=f(Q,C);if(r&&P?.decision==="allow"&&P.consentFingerprint===V)return{status:"allowed",source:"persistent"};const z=i.get(M);return z&&z.revision===b(P)&&z.consentFingerprint===V?{status:"allowed",source:"session"}:{status:"ask"}}function L(A){if(typeof A!="string"||!Ir.includes(A))throw p("INVALID_PARAMS","用户数据资源标识不合法")}return{canPersist:r,async read(A,U,Q={}){c();const C=await _(A,U);return N(A,C,Q)},async evaluate(A,U,Q){c(),L(U.resource);const C=await _(A,Q);return y(A,C,U.resource,U.egressTier)},async decide(A,U){c(),L(A.resource);const Q=async()=>{c();const C=await _(A.userId,U);if(c(),U.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");const P=C.records[A.resource],M=b(P);if(A.expectedRevision!==void 0&&M!==A.expectedRevision)throw p("AUTHORIZATION_CONTEXT_CHANGED","资料许可已变化,请重新确认");const V=h(A.userId,A.resource),z=f(A.resource,A.egressTier);if(A.expectedFingerprint!==void 0&&A.expectedFingerprint!==z)throw p("AUTHORIZATION_CONTEXT_CHANGED","资料披露范围已变化,请重新确认");if(A.scope==="session"){if(A.decision!=="allow")throw p("INVALID_PARAMS","本次许可只支持允许");return i.set(V,Object.freeze({revision:M,consentFingerprint:z})),N(A.userId,C,{egressTier:A.egressTier})}const te=M+1,x=A.decision==="allow"?{decision:"allow",revision:te,consentFingerprint:z}:{decision:A.decision,revision:te},Y={schema_version:1,records:{...C.records,[A.resource]:x}};A.decision!=="allow"&&(s.add(V),i.delete(V));try{await g(A.userId,Y,U)}catch(j){throw el(j)}return s.delete(V),i.delete(V),N(A.userId,Y,{egressTier:A.egressTier})};return A.scope==="session"?Q():u(A.userId,Q)},async revokeSession(A,U){c(),A.resource!==void 0&&L(A.resource);for(const C of[...i.keys()])C.startsWith(`${A.userId}\0`)&&(A.resource===void 0||C===h(A.userId,A.resource))&&i.delete(C);const Q=await _(A.userId,U);return N(A.userId,Q,{})},async reset(A,U){return c(),u(A.userId,async()=>{c();const Q=await _(A.userId,U);if(c(),U.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");const C=new Set(t);for(const V of Object.keys(Q.records))C.add(V);for(const V of i.keys())V.startsWith(`${A.userId}\0`)&&C.add(V.slice(A.userId.length+1));for(const V of C)s.add(h(A.userId,V));for(const V of[...i.keys()])V.startsWith(`${A.userId}\0`)&&i.delete(V);const P={...Q.records};for(const V of C)P[V]={decision:"ask",revision:(P[V]?.revision??0)+1};const M={schema_version:1,records:P};try{await g(A.userId,M,U)}catch(V){throw el(V)}for(const V of C)s.delete(h(A.userId,V));return N(A.userId,M,{})})},dispose(){o||(o=!0,i.clear(),s.clear())}}}const vo={auth:"none",channel:"api",method:"POST",bodyEncoding:"form",failurePresentation:"none",parse(e){return Ue(e,"游戏资料接口响应异常")}};function ko(e){return{runtime_auth_context_token:e.runtime_auth_context_token,resource:e.resource,disclosure_revision:e.disclosure_revision}}const pw={...vo,id:"heybox.user_miniprogram.runtime.user_game_data.query.post",path:"/user_miniprogram/runtime/user_game_data/query",body(e){return{...ko(e),operation:e.operation,schema_version:e.schema_version,...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit}}}},Tw={...vo,id:"heybox.user_miniprogram.runtime.user_game_data.sync.post",path:"/user_miniprogram/runtime/user_game_data/sync",body:ko},tl={...vo,id:"heybox.user_miniprogram.runtime.user_game_data.sync_status.post",path:"/user_miniprogram/runtime/user_game_data/sync_status",body(e){return{...ko(e),task_id:e.task_id}}},_w={...vo,id:"heybox.user_miniprogram.runtime.user_game_data.file.post",path:"/user_miniprogram/runtime/user_game_data/file",body(e){return{...ko(e),save_id:e.save_id,file_id:e.file_id}}};function Aw(e){const t=Jf(e.storage),r=e.fileDownloads??(e.files&&e.transfer?kc({files:e.files,transfer:e.transfer,registry:e.registry,signal:e.signal}):void 0),n=new Set,i=d=>{if(e.signal.aborted||d.signal.aborted)throw ne("REQUEST_CANCELLED","资料请求已取消")};async function s(d,l){if(i(l),!e.authorizationContext)throw ne("REQUEST_UNSUPPORTED","宿主缺少受信运行上下文");const f=await e.authorizationContext.get(l);if(!f.token||!Number.isFinite(f.expiresAt)||f.expiresAt<=Date.now())throw ne("UNAUTHORIZED","受信运行上下文已过期");return{runtime_auth_context_token:f.token,resource:d.key,disclosure_revision:d.disclosureRevision}}async function o(d,l,f){i(f);const h=await Ii({network:e.network,operationContext:f,subject:"游戏资料",assertUsable:()=>i(f),requestPolicyEnabled:e.requestPolicyEnabled,...e.requestGate?{gate:{capability:"userGameData",gate:e.requestGate}}:{}},d,l),_=Je(h,"user.data","游戏资料");if(!Se(_))throw ne("INVALID_RESPONSE","游戏资料响应无效");return i(f),_}const c=d=>{const l=Nc(d);if(!l)throw ne("REQUEST_UNSUPPORTED","未开放资料资源");return l};async function u(d){n.delete(d),await r?.release(d)}return{releaseFile:u,invalidate(){for(const d of n)r?.release(d);n.clear()},async query(d,l){const f=c(d.resource),h=f.queries[d.operation];if(!h)throw ne("REQUEST_UNSUPPORTED","未开放资料操作");const _=await o(pw,{...await s(f,l),operation:d.operation,schema_version:h.version,...d.cursor===void 0?{}:{cursor:d.cursor},...d.limit===void 0?{}:{limit:d.limit}},l);if(_.resource!==d.resource||_.operation!==d.operation||_.schema_version!==h.version||_.disclosure_revision!==f.disclosureRevision)throw ne("INVALID_RESPONSE","游戏资料合同不匹配");if(_.status==="ready"){if(!tg(h.schema,_.data))throw ne("INVALID_RESPONSE","游戏资料正文不匹配公开 schema");return{status:"ready",data:_.data,meta:{},schemaVersion:h.version}}if(_.status==="empty"&&(_.reason==="no_data"||_.reason==="not_ready")&&typeof _.message=="string")return{status:"empty",reason:_.reason,message:_.message,meta:{},schemaVersion:h.version};throw ne("INVALID_RESPONSE","游戏资料状态无效")},async sync(d,l,f){const h=c(d.resource);if(!h.operations.includes("sync"))throw ne("REQUEST_UNSUPPORTED","资源不支持同步");const _=await s(h,l),g=new AbortController,b=()=>g.abort();l.signal.addEventListener("abort",b,{once:!0}),l.signal.aborted&&b();let N=!1;const y=setTimeout(()=>{N=!0,b()},5*6e4),L={...l,signal:g.signal},A={...f,gameId:h.game,resource:d.resource};let U;try{const Q=await t.run(A,L,async()=>{const P=await t.get(A,L);if(P)return U=P,{id:P,status:await o(tl,{...await s(h,L),task_id:P},L)};const M=await o(Tw,_,L);if(typeof M.task_id!="string"||!M.task_id||M.task_id.length>128)throw ne("INVALID_RESPONSE","同步任务缺失");return await t.set(A,M.task_id,L),{id:M.task_id,status:M}});let C=Q.status;for(U=Q.id;;){if(i(L),C.state==="succeeded")return await t.remove(A,U,L),{status:"succeeded"};if(C.state==="failed")throw await t.remove(A,U,L),ne(typeof C.error_code=="string"?C.error_code:"SYNC_FAILED","存档同步失败");if(C.state!=="syncing"&&C.state!=="uploading")throw ne("INVALID_RESPONSE","同步状态无效");if(await Iw(L.signal),C=await o(tl,{...await s(h,L),task_id:U},L),C.task_id!==U)throw ne("INVALID_RESPONSE","同步任务不匹配")}}catch(Q){throw U&&Se(Q)&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED"].includes(String(Q.code))&&await t.remove(A,U,L),N?ne("REQUEST_TIMEOUT","等待同步超时,后台任务可能仍在执行"):Q}finally{clearTimeout(y),l.signal.removeEventListener("abort",b)}},async file(d,l,f){const h=c(d.resource);if(!h.operations.includes("file")||!r)throw ne("REQUEST_UNSUPPORTED","宿主不支持资料文件下载");const _=async b=>{await f(b);const N=await o(_w,{...await s(h,b),save_id:d.saveId,file_id:d.fileId},b);if(!Se(N.file)||N.file.file_id!==d.fileId)throw ne("INVALID_RESPONSE","文件标识不匹配");return await f(b),N},g=await r.download(await _(l),async b=>{await _(b)},l);try{return i(l),await f(l),i(l),n.add(g),g}catch(b){throw await u(g),b}}}}function Iw(e){return new Promise((t,r)=>{const n=()=>{clearTimeout(i),e.removeEventListener("abort",n),r(ne("REQUEST_CANCELLED","已停止等待同步"))},i=setTimeout(()=>{e.removeEventListener("abort",n),t()},2e3);e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})}const Mn=["event_id","miniProgramId","environment","host_platform","host_version","sdk_version","runtime_version","egress_tier","resource","call_id","flow_id"],bw=Object.freeze({user_game_data_permission_show:new Set([...Mn,"entry","reason"]),user_game_data_permission_result:new Set([...Mn,"choice","apply_result"]),user_game_data_permission_manage:new Set([...Mn,"operation","apply_result","succeeded_count","failed_count"]),user_game_data_action:new Set([...Mn,"stage","action_type","outcome","duration_ms"]),user_game_data_access_result:new Set([...Mn,"api","trigger","status","error_code","failure_stage","duration_ms","cache_hit","sample_rate","overview_status_counts"])}),rl=10*6e4,yw=256;function Nw(e){const t=e.now??Date.now,r=e.random??Math.random,n=e.createId??Ow,i=Dw(e.sampleRate),s=new Map,o=new Map,c=new Map;let u=!1,d=0,l=0,f=0,h=0;const _={get emitted(){return d},get failed(){return l},get skipped(){return f},get deduplicated(){return h}};function g(C){return`${C}${n()}`}function b(){const C=t();for(const[P,M]of s)C-M.createdAt<=rl||(s.delete(P),o.get(M.key)===P&&o.delete(M.key));for(const[P,M]of c){if(C-M<=rl&&c.size<=yw)break;c.delete(P)}}function N(C){const P=s.get(C);P!==void 0&&(s.delete(C),o.get(P.key)===C&&o.delete(P.key))}function y(C){N(C),c.delete(C),c.set(C,t())}function L(C,P){const M=bw[C],V={};for(const[z,te]of Object.entries(P))te===void 0||!M.has(z)||(V[z]=te);return Object.freeze(V)}function A(C){const P={event_id:g("evt_"),miniProgramId:Yr(()=>e.resolveMiniProgramId())??"unknown",environment:ww(Yr(()=>e.resolveEnvironment())),host_platform:Yr(e.resolveHostPlatform)??"unknown",host_version:Yr(e.resolveHostVersion)??"unknown",sdk_version:Yr(e.resolveSdkVersion)??"unknown",runtime_version:Yr(e.resolveRuntimeVersion)??"unknown",egress_tier:Sw(e)};return C.resource!==void 0&&(P.resource=C.resource),C.callId!==void 0&&(P.call_id=C.callId),C.flowId!==void 0&&(P.flow_id=C.flowId),P}function U(C,P){if(u){f+=1;return}try{if(e.sink===void 0){f+=1;return}e.sink.postEvent(C,L(C,P)),d+=1}catch{l+=1}}function Q(C,P){if(C===void 0)return!1;const M=s.get(C);return M===void 0?!1:P==="start"&&M.started||P==="shown"&&M.shown||P==="decided"&&M.decided?!0:(P==="start"&&(M.started=!0),P==="shown"&&(M.shown=!0),P==="decided"&&(M.decided=!0),!1)}return{diagnostics:_,createCallId(){return g("call_")},beginFlow(C){b();const P=`${C.resource??""}\0${C.actionType}`,M=o.get(P);if(M!==void 0&&s.has(M))return M;const V=g("flow_");return s.set(V,{key:P,createdAt:t(),started:!1,shown:!1,decided:!1}),o.set(P,V),V},permissionShow(C){if(Q(C.flowId,"shown")){h+=1;return}U("user_game_data_permission_show",{...A(C),entry:C.entry,reason:C.reason})},permissionResult(C){if(Q(C.flowId,"decided")){h+=1;return}U("user_game_data_permission_result",{...A(C),choice:C.choice,apply_result:C.applyResult})},permissionManage(C){U("user_game_data_permission_manage",{...A(C),operation:C.operation,apply_result:C.applyResult,...C.succeededCount===void 0?{}:{succeeded_count:C.succeededCount},...C.failedCount===void 0?{}:{failed_count:C.failedCount}})},action(C){if(C.stage==="start"&&Q(C.flowId,"start")){h+=1;return}if(C.stage==="finish"){if(C.flowId!==void 0&&c.has(C.flowId)){h+=1;return}C.flowId!==void 0&&y(C.flowId)}U("user_game_data_action",{...A(C),stage:C.stage,action_type:C.actionType,...C.outcome===void 0?{}:{outcome:C.outcome},...C.durationMs===void 0?{}:{duration_ms:Math.max(0,Math.round(C.durationMs))}})},access(C){if(i<=0){f+=1;return}if(i<1&&r()>=i){f+=1;return}U("user_game_data_access_result",{...A(C),api:C.api,trigger:C.trigger,status:C.status,duration_ms:Math.max(0,Math.round(C.durationMs)),sample_rate:i,...C.errorCode===void 0?{}:{error_code:C.errorCode},...C.failureStage===void 0?{}:{failure_stage:C.failureStage},...C.cacheHit===void 0?{}:{cache_hit:C.cacheHit},...C.overviewStatusCounts===void 0?{}:{overview_status_counts:C.overviewStatusCounts}})},dispose(){u||(u=!0,s.clear(),o.clear(),c.clear())}}}function ww(e){switch(e){case"public":case"production":return"production";case"preview":return"preview";case"development":case"dev":case"local":return"development";case"mock":return"mock";default:return"unknown"}}function Dw(e){return e===void 0||!Number.isFinite(e)?1:e<=0?0:e>=1?1:e}function Yr(e){if(e!==void 0)try{const t=e();if(typeof t!="string")return;const r=t.trim();return r===""?void 0:r}catch{return}}function Sw(e){try{return e.resolveEgressTier()==="upload"?"upload":"no_network"}catch{return"no_network"}}function Ow(){const e=globalThis.crypto;if(typeof e?.randomUUID=="function")return e.randomUUID();const t=new Uint8Array(16);if(typeof globalThis.crypto?.getRandomValues=="function")globalThis.crypto.getRandomValues(t);else for(let r=0;r<t.length;r+=1)t[r]=Math.floor(Math.random()*256);return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function Pt(e){const t=ot(e);return t.valid?t.permissions.network?.status==="enabled"||t.permissions.companion?.status==="enabled"?"upload":"no_network":"upload"}function Mw(e){let t=!1,r=0,n,i=!1;const s=new Map,o=new Map,c=new Set,u=new Map,d=e.now??Date.now,l=m=>y()[m]?.purpose??"",f=m=>{const w=Nc(m);if(!w)throw p("REQUEST_UNSUPPORTED","未开放的资料资源");return w},h=m=>Xl(m,f(m).disclosureRevision,Pt(e.runtimePermissions),l(m)),_=()=>gw({storage:e.storage,resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,revisionOf:m=>f(m).disclosureRevision,purposeOf:l,...e.hash?{hash:e.hash}:{}});let g=_();const b=Nw({resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,resolveEgressTier:()=>Pt(e.runtimePermissions),...e.telemetry??{}}),N=Aw({network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,storage:e.storage,registry:e.fileRegistry,fileDownloads:e.fileDownloads,requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled,signal:e.operationContext.signal});function y(){const m=ot(e.runtimePermissions),w=m.valid?m.permissions.user_game_data:void 0;return w?.status==="enabled"?ci(w.config.resources):{}}function L(m){if(t||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序已关闭");if(m?.signal.aborted)throw p("REQUEST_CANCELLED","资料请求已取消")}function A(m){for(const[w,B]of s)B!==void 0&&(m===void 0||B===m)&&w.abort()}function U(m){for(const[w,B]of o)(m===void 0||w===m)&&(B.abort(),o.delete(w))}function Q(){r++,U();for(const m of s.keys())m.abort();for(const m of c)e.fileRegistry.revokeFiles([m]);c.clear(),u.clear(),N.invalidate()}const C=bi(e.account,m=>{if(i&&n===m)return;const w=n;i=!0,n=m,w!==void 0&&(Q(),g.dispose(),g=_())}),P=()=>Q();e.operationContext.signal.addEventListener("abort",P,{once:!0});async function M(m,w){L(m);const B=new AbortController,K=()=>B.abort();s.set(B,void 0),m.signal.addEventListener("abort",K,{once:!0}),m.signal.aborted&&K();const ce={...e.operationContext,...m,signal:B.signal};try{const pe=await w(ce);return L(ce),pe}catch(pe){throw le(pe)&&pe.name==="AbortError"?p("REQUEST_CANCELLED","资料操作已取消"):pe}finally{m.signal.removeEventListener("abort",K),s.delete(B)}}function V(m){const w=f(m);if(!l(w.key))throw p("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明这项游戏资料",{resource:w.key});return w}async function z(m){L(m);const w=await e.account.getCurrentUserId(m);if(L(m),!i)i=!0,n=w;else if(n!==w){const B=n;n=w,B!==void 0&&(Q(),g.dispose(),g=_(),L(m))}return w}function te(m,w){const B={login_required:"请先登录小黑盒",permission_required:"尚未允许读取这项资料",permission_denied:"已拒绝读取这项资料",source_not_linked:"请先在小黑盒关联对应游戏账号",source_login_required:"请先在小黑盒更新游戏来源登录"},K=w==="login_required"?{type:"user_login",label:"登录并授权"}:w==="permission_required"?{type:"permission",label:"允许读取"}:w==="permission_denied"&&e.presentation?.openDataPermissions?{type:"manage",label:"管理数据权限"}:void 0;return{status:"blocked",resource:m,reason:w,message:B[w],...K?{interaction:K}:{}}}async function x(m,w){V(m);const B=await z(w);if(!B)return te(m,"login_required");const K=await g.evaluate(B,{resource:m,egressTier:Pt(e.runtimePermissions)},w);return L(w),K.status==="allowed"?{userId:B}:te(m,K.status==="denied"?"permission_denied":"permission_required")}async function Y(m,w,B,K,ce){if(L(ce),r!==B||await z(ce)!==w||h(m)!==K)throw p("AUTHORIZATION_CONTEXT_CHANGED","账号或资料范围已变化");return x(m,ce)}function j(m,w){if(!le(m)||typeof m.resource!="string")throw p("INVALID_PARAMS","资料请求无效");if(!tr(m.resource))throw p("REQUEST_UNSUPPORTED","当前宿主尚未开放该资料资源");const B=w==="query"?["resource","operation","schemaVersion","cursor","limit"]:["resource","saveId","fileId"];if(Object.keys(m).some(ce=>!B.includes(ce)))throw p("INVALID_PARAMS","资料请求包含未知参数");const K=V(m.resource);if(w==="query"){if(m.operation!=="get"&&m.operation!=="list")throw p("INVALID_PARAMS","资料查询操作无效");const ce=K.queries[m.operation];if(!ce)throw p("REQUEST_UNSUPPORTED","资源不支持该查询");if(m.schemaVersion!==ce.version)throw p("REQUEST_UNSUPPORTED","SDK 与宿主正文合同版本不匹配");if(m.operation!=="list"&&(m.cursor!==void 0||m.limit!==void 0))throw p("INVALID_PARAMS","单份查询不能分页");if(m.cursor!==void 0&&(typeof m.cursor!="string"||!m.cursor||m.cursor.length>32768))throw p("INVALID_PARAMS","分页游标无效");if(!ce.page&&(m.cursor!==void 0||m.limit!==void 0))throw p("INVALID_PARAMS","该列表不支持分页");if(m.limit!==void 0&&(typeof m.limit!="number"||!Number.isInteger(m.limit)||m.limit<1||m.limit>(ce.page?.maxSize??100)))throw p("INVALID_PARAMS","分页数量无效")}else if(!K.operations.includes(w))throw p("REQUEST_UNSUPPORTED","资源不支持该操作");if(w==="file"&&(typeof m.saveId!="string"||!m.saveId||typeof m.fileId!="string"||!m.fileId))throw p("INVALID_PARAMS","资料文件标识无效");return w==="query"?{resource:m.resource,operation:m.operation,schemaVersion:m.schemaVersion,...m.cursor===void 0?{}:{cursor:m.cursor},...m.limit===void 0?{}:{limit:m.limit}}:{resource:m.resource,saveId:m.saveId,fileId:m.fileId}}async function H(m,w,B,K){const ce=d(),pe=r,ue=h(w.resource);for(const Te of s.keys())Te.signal===B.signal&&s.set(Te,w.resource);try{const Te=await x(w.resource,B);if("status"in Te)return b.access({resource:w.resource,api:m,trigger:"initial",status:"blocked",durationMs:d()-ce}),Te;let we;try{we=await K()}catch(Ie){const ye=le(Ie)?Ie.code:void 0;if(ye==="USER_DATA_SOURCE_NOT_LINKED"||ye==="USER_DATA_SOURCE_LOGIN_REQUIRED")return b.access({resource:w.resource,api:m,trigger:"initial",status:"blocked",durationMs:d()-ce}),te(w.resource,ye==="USER_DATA_SOURCE_NOT_LINKED"?"source_not_linked":"source_login_required");throw Ie}const Ae=await Y(w.resource,Te.userId,pe,ue,B);return"status"in Ae?(b.access({resource:w.resource,api:m,trigger:"initial",status:"blocked",durationMs:d()-ce}),Ae):(b.access({resource:w.resource,api:m,trigger:"initial",status:le(we)&&we.status==="empty"?"empty":m===Un?"succeeded":"ready",durationMs:d()-ce}),we)}catch(Te){throw b.access({resource:w.resource,api:m,trigger:"initial",status:"error",durationMs:d()-ce,errorCode:le(Te)?String(Te.code):"REQUEST_FAILED"}),Te}}async function F(m){const w=await z(m);if(!w)throw p("UNAUTHORIZED","请先登录小黑盒");return g.read(w,m,{declared:Object.keys(y()),egressTier:Pt(e.runtimePermissions)})}async function v(m,w){const B=V(m);let K=await z(w);if(K||(await e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:w.signal}),K=await z(w)),!K)return{status:"cancelled"};let ce=await g.evaluate(K,{resource:m,egressTier:Pt(e.runtimePermissions)},w);if(ce.status==="allowed")return{status:"allowed"};if(ce.status==="denied"){if(e.presentation?.openDataPermissions){const ve=r,Fe=h(m),Ge=await e.presentation.openDataPermissions({resource:m,miniProgramName:e.miniProgramPresentation?.name,signal:w.signal});if(!("status"in await Y(m,K,ve,Fe,w)))return{status:"allowed"};if(!Ge)return{status:"cancelled"}}return ce=await g.evaluate(K,{resource:m,egressTier:Pt(e.runtimePermissions)},w),{status:ce.status==="allowed"?"allowed":"denied"}}if(!e.presentation?.confirmDataPermission)throw p("REQUEST_UNSUPPORTED","当前宿主不支持资料许可弹窗");U(m);const pe=new AbortController;o.set(m,pe);const ue=()=>pe.abort();w.signal.addEventListener("abort",ue,{once:!0}),w.signal.aborted&&ue();const Te={...w,signal:pe.signal},we=r,Ae=h(m),Ie=g,ye=b.beginFlow({resource:m,actionType:"permission"});let xe="error";try{const Fe=(await Ie.read(K,Te,{egressTier:Pt(e.runtimePermissions)})).resources.find(hr=>hr.resource===m);b.action({resource:m,flowId:ye,stage:"start",actionType:"permission"}),b.permissionShow({resource:m,flowId:ye,entry:"other",reason:Fe?.decision==="allow"?"scope_changed":"first"});const Ge=await be(()=>e.presentation.confirmDataPermission({miniProgramName:e.miniProgramPresentation?.name,resource:m,scopeText:`此黑盒账号关联的${B.name}${B.operations.includes("sync")?`。${Y0}`:""}`,purposeText:l(m),egress:Pt(e.runtimePermissions),canPersist:Ie.canPersist,signal:pe.signal}),pe.signal);if(L(Te),r!==we||await z(Te)!==K||h(m)!==Ae)throw p("AUTHORIZATION_CONTEXT_CHANGED","资料许可范围已变化");return Ge.decision==="cancelled"?(xe="cancelled",b.permissionResult({resource:m,flowId:ye,choice:"cancel",applyResult:"cancelled"}),{status:"cancelled"}):(await Ie.decide({userId:K,resource:m,decision:Ge.decision==="deny"?"deny":"allow",scope:Ge.decision==="session"?"session":"persistent",egressTier:Pt(e.runtimePermissions),expectedRevision:Fe?.revision??0,expectedFingerprint:Fe?.scopeFingerprint},Te),Ge.decision==="deny"&&A(m),xe=Ge.decision==="deny"?"unresolved":"resolved",b.permissionResult({resource:m,flowId:ye,choice:Ge.decision,applyResult:"applied"}),{status:Ge.decision==="deny"?"denied":"allowed"})}catch(ve){throw xe=Te.signal.aborted?"cancelled":"error",b.permissionResult({resource:m,flowId:ye,choice:"cancel",applyResult:Te.signal.aborted?"cancelled":"error"}),ve}finally{b.action({resource:m,flowId:ye,stage:"finish",actionType:"permission",outcome:xe}),w.signal.removeEventListener("abort",ue),o.get(m)===pe&&o.delete(m)}}async function R(m,w,B,K,ce,pe){w==="allow"?V(m):f(m);const ue=await z(K);if(!ue)throw p("UNAUTHORIZED","请先登录小黑盒");try{await g.decide({userId:ue,resource:m,decision:w,scope:B,expectedRevision:ce,expectedFingerprint:pe,egressTier:Pt(e.runtimePermissions)},K)}catch(Te){throw le(Te)&&Te.code==="USER_DATA_PERMISSION_SAVE_FAILED"&&A(m),Te}return U(m),w!=="allow"&&A(m),F(K)}async function q(m,w,B){try{const K=await B();return b.permissionManage({operation:m,resource:w,applyResult:"applied"}),K}catch(K){throw b.permissionManage({operation:m,resource:w,applyResult:le(K)&&K.code==="USER_DATA_PERMISSION_SAVE_FAILED"?"save_failed":"error"}),K}}async function D(m,w){U(m),A(m);const B=await z(w);if(!B)throw p("UNAUTHORIZED","请先登录小黑盒");return q("revoke",m,async()=>(await g.revokeSession({userId:B,resource:m},w),F(w)))}function W(){let m;const w=B=>M(e.operationContext,async K=>{const ce=await z(K);if(!ce)throw p("UNAUTHORIZED","请先登录小黑盒");if(m&&(m.userId!==ce||m.generation!==r))throw p("AUTHORIZATION_CONTEXT_CHANGED","管理页面所属账号已变化,请重新打开");return m??={userId:ce,generation:r},B(K)});return{getSnapshot:()=>w(F),setDecision:B=>w(K=>q("modify",B.resource,()=>R(B.resource,B.decision,B.scope,K,B.expectedRevision,B.expectedFingerprint))),revokeSession:B=>w(K=>D(B?.resource,K)),resetAll:()=>w(async B=>{U(),A();const K=await z(B);return q("reset",void 0,async()=>(await g.reset({userId:K},B),F(B)))})}}return{handlers:{[pc]:async(m,w)=>M(w,async B=>{if(m!==void 0&&(!le(m)||Object.keys(m).some(pe=>pe!=="game")||m.game!==void 0&&typeof m.game!="string"))throw p("INVALID_PARAMS","概览参数无效");if(le(m)&&typeof m.game=="string"&&!Eu(m.game))throw p("REQUEST_UNSUPPORTED","当前宿主尚未开放该游戏");const K=Object.keys(y()),ce=le(m)?m.game:void 0;return Kl.filter(pe=>ce===void 0||pe===ce).map(pe=>({game:pe,name:$l[pe],resources:Sr.filter(ue=>ue.game===pe&&K.includes(ue.key)).map(ue=>({resource:ue.key,name:ue.name,status:"not_checked",statusText:"尚未检查"}))})).filter(pe=>pe.resources.length>0)}),[cs]:async(m,w)=>M(w,B=>{const K=j(m,"query");return H(cs,K,B,()=>N.query(K,B))}),[Un]:async(m,w)=>M(w,async B=>{if(!le(m)||Object.keys(m).length!==1||typeof m.game!="string"||!Eu(m.game))throw p("INVALID_PARAMS","同步需要指定已开放的游戏");const K={game:m.game};if(!Sr.some(we=>we.game===K.game&&we.sync))throw p("REQUEST_UNSUPPORTED","该游戏不支持存档同步");const ce=Sr.filter(we=>we.game===K.game&&we.sync&&l(we.key));if(ce.length===0)throw p("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明可同步的资料");let pe,ue;for(const we of ce){const Ae=await x(we.key,B);if(!("status"in Ae)){pe=we.key;break}(!ue||ue.reason==="permission_denied")&&(ue=Ae)}if(!pe)return ue;const Te={resource:pe};return H(Un,Te,B,async()=>{const we=await z(B),Ae=`${we}\0${Te.resource}`;let Ie=u.get(Ae);if(!Ie){const ye=new AbortController;s.set(ye,Te.resource);const xe={controller:ye,waiters:0,settled:!1,promise:Promise.resolve(void 0)};xe.promise=N.sync(Te,{...e.operationContext,signal:ye.signal},{userId:we,miniProgramId:e.identity.get()?.miniProgramId??""}).finally(()=>{xe.settled=!0,s.delete(ye),u.get(Ae)===xe&&u.delete(Ae)}),xe.promise.catch(()=>{}),u.set(Ae,xe),Ie=xe}Ie.waiters++;try{return await be(()=>Ie.promise,B.signal)}finally{Ie.waiters--,Ie.waiters===0&&!Ie.settled&&Ie.controller.abort()}})}),[us]:async(m,w)=>M(w,async B=>{const K=j(m,"file"),ce=await z(B),pe=r,ue=h(K.resource),Te=async Ae=>{try{const Ie=await Y(K.resource,ce,pe,ue,Ae);if("status"in Ie)throw p("FILE_ACCESS_REVOKED","文件授权已撤销",{reason:Ie.reason})}catch(Ie){throw le(Ie)&&["AUTHORIZATION_CONTEXT_CHANGED","USER_DATA_RESOURCE_NOT_DECLARED"].includes(String(Ie.code))?p("FILE_ACCESS_REVOKED","文件授权已失效",{causeCode:Ie.code}):Ie}};let we;try{const Ae=await H(us,K,B,async()=>(we=await N.file(K,B,Te),{handle:we}));if(le(Ae)&&Ae.status==="blocked"){const ve=String(Ae.reason);throw p(ve==="source_not_linked"?"USER_DATA_SOURCE_NOT_LINKED":ve==="source_login_required"?"USER_DATA_SOURCE_LOGIN_REQUIRED":ve==="login_required"?"UNAUTHORIZED":"PERMISSION_DENIED",String(Ae.message),{reason:ve})}const Ie=Ae.handle,ye={...Ie,read:async ve=>{await Te(ve);const Fe=await Ie.read(ve);try{return await Te(ve),Fe}catch(Ge){throw Fe.fill(0),Ge}},stat:async ve=>{await Te(ve);const Fe=await Ie.stat(ve);return await Te(ve),Fe}},xe=e.fileRegistry.registerFile(ye,"download","read");return"handleId"in xe.ref&&c.add(xe.ref.handleId),xe}catch(Ae){throw we&&await N.releaseFile(we),Ae}}),[Tc]:async(m,w)=>{if(!w.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","许可操作需要点击");return M(w,B=>{if(!le(m)||Object.keys(m).length!==1||typeof m.resource!="string"||!tr(m.resource))throw p("INVALID_PARAMS","许可资源无效");return v(m.resource,B)})},[_c]:async(m,w)=>M(w,F),[Ac]:async(m,w)=>{if(!w.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","修改许可需要点击");if(!le(m)||typeof m.resource!="string"||!tr(m.resource)||m.decision!=="deny"||m.scope!=="persistent"||Object.keys(m).some(B=>!["resource","decision","scope"].includes(B)))throw p("INVALID_PARAMS","允许许可只能由可信弹窗确认");return M(w,B=>R(m.resource,m.decision,"persistent",B))},[Ic]:async(m,w)=>{if(!w.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","管理资料许可需要点击");if(!e.presentation?.openDataPermissions)throw p("REQUEST_UNSUPPORTED","宿主未提供资料管理界面");if(m!==void 0&&(!le(m)||Object.keys(m).some(B=>B!=="resource")||m.resource!==void 0&&(typeof m.resource!="string"||!tr(m.resource))))throw p("INVALID_PARAMS","管理资源无效");return M(w,async B=>(await e.presentation.openDataPermissions({resource:le(m)?m.resource:void 0,miniProgramName:e.miniProgramPresentation?.name,signal:B.signal}),F(B)))},[bc]:async(m,w)=>{if(!w.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","撤销许可需要点击");if(m!==void 0&&(!le(m)||Object.keys(m).some(B=>B!=="resource")||m.resource!==void 0&&(typeof m.resource!="string"||!tr(m.resource))))throw p("INVALID_PARAMS","撤销资源无效");return M(w,B=>D(le(m)?m.resource:void 0,B))}},get permissionBridge(){return W()},diagnostics:{telemetry:b.diagnostics},dispose(){t||(t=!0,Q(),C(),e.operationContext.signal.removeEventListener("abort",P),g.dispose(),b.dispose())}}}function nl(e){throw{code:"INVALID_PARAMS",message:e}}function Cn(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function am(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Hi(e,t,r){return Math.min(am(e,t),r)}async function Cw(e){try{return am(await e.getNavigationBarHeight(),0)}catch{return 0}}function Rw(e,t,r,n){const i=Hi(e.safeArea?.left,0,t),s=Math.max(i,Hi(e.safeArea?.right,t,t)),o=Hi(e.safeArea?.top,n,r),c=Math.max(o,Hi(e.safeArea?.bottom,r,r));return{left:i,right:s,top:o,bottom:c,width:s-i,height:c-o}}async function il(e){const t=e.getViewportMetrics(),r=Cn(t.windowWidth,0),n=Cn(t.windowHeight,0),i=await Cw(e);return{pixelRatio:Cn(t.pixelRatio,1),screenWidth:Cn(t.screenWidth,r),screenHeight:Cn(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:Rw(t,r,n,i),screenTop:i}}function Lw(e){const t=new AbortController,r={...e,operationContext:{...e.operationContext,signal:t.signal}};let n=!1,i=0,s,o;const c=()=>{if(n||r.operationContext.signal.aborted||!r.onViewportChange)return;const f=++i;il(r.presentation).then(h=>{if(n||r.operationContext.signal.aborted||f!==i)return;const _=JSON.stringify(h);_!==s&&(s=_,r.onViewportChange?.(h))}).catch(()=>{})},u=jy({...r,onApplied:c}),d=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),u.dispose(),o?.())};return e.operationContext.signal.aborted?d():(o=r.presentation.onViewportChange?.(c),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[Cr]:async(f,h)=>u.apply(f,h?.signal),[bs]:async()=>(Oe(r.operationContext.signal),il(r.presentation)),[ys]:async f=>{if(Oe(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return nl("viewport.setNavigationBarStyle 参数必须是对象");const h=f.foregroundStyle;if(h!=="light"&&h!=="dark")return nl("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await be(()=>r.presentation.setNavigationBarStyle(h,e.operationContext),r.operationContext.signal)}},runDisplayRequest:u.runDisplayRequest,applyOrientation:(f,h)=>u.apply({orientation:f.mode,fullscreen:f.hideCapsule},h),notifyChange:()=>{s=void 0,c()},dispose:d}}function Pw(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw Me("INVALID_PARAMS","工作区卡片刷新参数必须是对象");const t=e;if(Object.keys(t).some(i=>i!=="gameAppId"&&i!=="cardIds"))throw Me("INVALID_PARAMS","工作区卡片刷新包含未知参数");const{gameAppId:r,cardIds:n}=t;if(r!==void 0&&(typeof r!="string"||!/^[1-9][0-9]{0,9}$/.test(r)||Number(r)>2147483647))throw Me("INVALID_PARAMS","工作区卡片游戏编号无效");if(n!==void 0&&(!Array.isArray(n)||n.length>3||n.some(i=>typeof i!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(i))||new Set(n).size!==n.length))throw Me("INVALID_PARAMS","工作区卡片编号无效");return{...r===void 0?{}:{gameAppId:r},...n===void 0?{}:{cardIds:[...n]}}}function vw(e,t){return{[ds]:async(r,n)=>{const i=Re(t,n.signal,n.requestId);if(Oe(i.signal),!e)throw Me("CAPABILITY_UNAVAILABLE","当前 Host 不支持工作区卡片");const s=Pw(r),o=await be(()=>e.requestRefresh(s,i),i.signal);if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(c=>c!=="scheduled")||!Number.isSafeInteger(o.scheduled)||o.scheduled<0)throw Me("HOST_INVALID_RESPONSE","工作区卡片刷新回执无效");return{scheduled:o.scheduled}}}}const kw=new Map(cr.map(e=>[e.method,e]));function ca(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function xw(e){const t=yf(e);return r=>t(r.requirement,r.method)}function Uw(e,t,r,n){let i;try{i=Promise.resolve(e(t,r))}catch(s){return n.aborted?Promise.resolve({status:"dropped"}):Promise.reject(s)}return n.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((s,o)=>{let c=!1;const u=l=>{c||(c=!0,n.removeEventListener("abort",d),l())},d=()=>u(()=>s({status:"dropped"}));n.addEventListener("abort",d,{once:!0}),i.then(l=>u(()=>s({status:"handled",value:l})),l=>u(()=>o(l)))})}function Bw(e){const t=xw(e.runtimePermissions),r=ot(e.runtimePermissions);let n=0;return{async dispatch(i,s,o){const c=e.now??Hw,u=e.onTrace?c():0,d=e.onTrace?Date.now():0,l=e.onTrace?o.requestId??`runtime_${++n}`:"";e.onTrace&&ua(e.onTrace,{callId:l,method:i,startedAt:d,outcome:"started"},()=>u,u);try{if(e.terminalSignal.aborted)throw ca("RUNTIME_DESTROYED","小程序 Runtime 已终止");gf(i,e.effectiveCapabilities);const f=kw.get(i);if(!f)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const h=t(f),_=!h.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,s)===!0,g=!h.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,s)===!0,b=!h.allowed&&r.valid&&r.permissions.user_game_data?.status==="enabled"&&e.allowsUserGameDataFileAccess?.(i,s)===!0;if(!h.allowed&&!_&&!g&&!b)throw ca(h.code,h.message,h.data);const N=e.handlers[i];if(!N)throw new Error(`Capability method ${i} 缺少 handler`);const y=async U=>{for(const Q of e.policies??[]){const C=await Q.evaluate({method:i,payload:s,capability:f});if(e.terminalSignal.aborted||U.aborted)throw ol();if(!C.allowed)throw ca(C.code,C.message,C.data)}if(e.terminalSignal.aborted||U.aborted)throw ol()},A=await Uw(async()=>{if(i===Cr){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(s,o.signal,y)}return await y(e.terminalSignal),N(s,o)},void 0,o,e.terminalSignal);return e.onTrace&&ua(e.onTrace,sl(l,i,s,d,A),c,u),A}catch(f){throw e.onTrace&&ua(e.onTrace,sl(l,i,s,d,{status:"error",error:f}),c,u),f}}}}function Hw(){return typeof performance>"u"?Date.now():performance.now()}function ua(e,t,r,n){if(!e)return;const i=r()-n,s=Date.now();try{e({...t,phase:"host",timestamp:s,durationMs:Math.max(0,Number.isFinite(i)?i:0)})}catch{}}function sl(e,t,r,n,i){const s=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:n,outcome:s,...i.status==="error"?{errorCode:Fw(i.error)}:{},...zw(t,r,i)}}function Fw(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function zw(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 s=("method"in t&&typeof t.method=="string"?t.method:"GET").trim().toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(s))return{};const o=r.status==="handled"&&qa(r.value)&&typeof r.value.status=="number"?r.value.status:void 0;return{network:{method:s,origin:n.origin,pathname:n.pathname,...o===void 0?{}:{responseStatus:o}}}}catch{return{}}}function qa(e){return typeof e=="object"&&e!==null}function ol(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function jw(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=fT(e.requestPolicy);let n;if(e.files)try{n=rT(e.files,t)}catch{}const i=Pf({store:n}),s=e.onRequestPolicyReport??(r.debugReport?Vw:void 0),o=r.enabled?cT({...r.gateOptions,...s?{onReport:s}:{}}):void 0,c=new Lc(e.files,e.miniProgramDetail),u=$b({registry:c,picker:e.picker,operationContext:t}),d=UT({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:o,requestPolicyEnabled:r.enabled});let l,f,h,_,g,b,N,y=()=>{},L=()=>{};try{l=Lw({operationContext:t,presentation:e.hostPresentation,onDisplayChange:j=>e.eventSink.postEvent("display_change",j),onViewportChange:j=>e.eventSink.postEvent("viewport_change",j)}),h=iw({authPresentation:e.authPresentation,authorizationContext:e.authorizationContext,account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:d,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:o,requestPolicyEnabled:r.enabled}),y=d.onEvent((j,H)=>e.eventSink.postEvent(j,H)),L=e.hostCompanion?.onSessionEvent?.(j=>{const H=Vb(j);!e.terminalSignal.aborted&&H&&e.eventSink.postEvent(H.type,H.payload)})??(()=>{}),_=T_({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:o,requestPolicyEnabled:r.enabled});const A=e.files&&e.transfer?kc({files:e.files,transfer:e.transfer,registry:c,signal:t.signal}):void 0,U=Mw({identity:e.identity,account:e.account,storage:e.storage,network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,fileDownloads:A,requestGate:o,requestPolicyEnabled:r.enabled,fileRegistry:c,...e.userDataPresentation===void 0?{}:{presentation:e.userDataPresentation},...e.miniProgramPresentation===void 0?{}:{miniProgramPresentation:e.miniProgramPresentation},runtimePermissions:e.runtimePermissions,environment:e.miniProgramDetail?.releaseChannel,operationContext:t,...e.onUserDataTelemetry===void 0?{}:{telemetry:{sink:{postEvent(j,H){e.onUserDataTelemetry?.({name:j,payload:H})}}}}});N=U,g=C_({identity:e.identity,storage:e.storage,account:e.account,presentation:e.hostPresentation,network:e.network,authorization:d,authorizationContext:e.authorizationContext,operationContext:t,files:e.files,transfer:e.transfer,fileRegistry:c,fileDownloads:A,requestGate:o,requestPolicyEnabled:r.enabled}),b=Cb({presentation:e.hostPresentation,account:e.account,network:e.network,authorization:d,authorizationContext:e.authorizationContext,operationContext:t,requestGate:o,requestPolicyEnabled:r.enabled,onBackgroundError:e.onBackgroundError,emit:j=>e.eventSink.postEvent("post_change",j)});const Q=vN({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});f=Ty({registry:c,media:e.media,operationContext:t});const C=[{name:"post",handlers:b.handlers},{name:"gameSaves",handlers:Object.fromEntries(Object.entries(g.handlers).map(([j,H])=>[j,async(F,v)=>{const R=e.verifiedSdkVersion,q=R?xc(R,"0.10.0-0"):void 0;if(q===void 0||q>=0)throw p("REQUEST_UNSUPPORTED","当前 SDK 不支持旧游戏存档入口,请使用 user.games.get(...).saves");return H(F,v)}]))},{name:"auth",handlers:YT({authorization:d})},{name:"user",handlers:{...mw({user:h,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...$p({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:RN({prepareScreenshot:e.prepareScreenshot,prepareLongScreenshot:e.prepareLongScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:l.handlers},{name:"storage",handlers:Q.handlers},{name:"network",handlers:Zy({network:e.network,transfer:e.transfer,fileRegistry:c,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins,networkPolicy:e.networkPolicy,firstParty:e.firstParty})},{name:"workspaceCards",handlers:vw(e.workspaceCards,t)},{name:"files",handlers:u.files},{name:"file",handlers:u.file},{name:"directory",handlers:u.directory},{name:"media",handlers:f.handlers},{name:"ui",handlers:HN({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:qb({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:Vy({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:j=>l.applyOrientation({mode:"portrait",hideCapsule:!1},j)}:{}})},{name:"cloud",handlers:_.handlers},{name:"userGameData",handlers:N.handlers},{name:"companion",handlers:Bb({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:c})}],P=Gw(C);let M=!1;const V=()=>{M||(M=!0,e.terminalSignal.removeEventListener("abort",V),l?.dispose(),f?.dispose(),_?.dispose(),g?.dispose(),b?.dispose(),N?.dispose(),y(),L(),h?.dispose(),i.dispose(),d.dispose(),o?.dispose(),c.dispose())};e.terminalSignal.aborted?V():e.terminalSignal.addEventListener("abort",V,{once:!0});const z=new Set(["file.readText","file.readBytes","file.stat"]),te=(j,H)=>z.has(j)&&qa(H)&&c.isCompanionAttachmentRef(H.target),x=new Set(["file.readText","file.readBytes","file.stat","file.exists"]),Y=(j,H)=>x.has(j)&&qa(H)&&c.isUserDataDownloadRef(H.target);return{get permissionBridge(){return U.permissionBridge},modules:C,setPostVisible:b.setVisible,dismissPostEditor:b.dismissEditor,handlers:P,runDisplayRequest:l.runDisplayRequest,allowsCompanionAttachmentAccess:te,allowsGameSaveAccess:g.allowsRead,allowsUserGameDataFileAccess:Y,gameSaveDiagnostics:g.diagnostics,applyOrientation:l.applyOrientation,notifyViewportChange:l.notifyChange,...Q.diagnostics?{storageDiagnostics:Q.diagnostics}:{},...e.files?{sandboxDiagnostics:iy({registry:c,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},dispose:V}}catch(A){throw l?.dispose(),f?.dispose(),_?.dispose(),g?.dispose(),b?.dispose(),N?.dispose(),y(),L(),h?.dispose(),i.dispose(),d.dispose(),o?.dispose(),c.dispose(),A}}function Vw(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Gw(e){const t=new Map(cr.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[s,o]of Object.entries(i.handlers)){const c=s,u=t.get(c);if(!u)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${c}`);if(u!==i.name)throw new Error(`Capability method ${c} 应由 ${u} 拥有,不能注册到 ${i.name}`);if(r.has(c))throw new Error(`Capability method ${c} 存在重复 owner`);if(typeof o!="function")throw new Error(`Capability method ${c} 缺少 handler`);r.set(c,o)}const n=cr.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==cr.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Yw="heybox-mini-dev:";function al(e){try{return Qw(new URL(e))}catch{return!1}}function Qw(e){return e.protocol===Yw}function qw(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Ww(e)}function Ww(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 $w=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Kw(e,t){const r=[],n=Zw(e.environmentInfo,r),i=Ji(n?.appVersion,"host.appVersion",r),s=Jw(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:Xw(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:Ji(t.miniProgramId),version:Ji(t.miniProgramVersion)}),operatingSystem:Object.freeze(s)}),invalidFields:Object.freeze(r)}}function Zw(e,t){if(e!=null){if(cm(e))return e;t.push("environmentInfo")}}function Xw(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function Jw(e,t){if(e==null)return{name:"unknown",version:null};if(!cm(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=$w.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:Ji(e.version,"operatingSystem.version",t)}}function Ji(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function cm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const eD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",tD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",rD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",nD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function iD(e,t,r,n,i="dark"){Oe(n);const s=e.defaultView;if(!s||!e.body)throw new Error("截图水印缺少可用的展示窗口");const o=e.createElement("div"),c=i==="light",u=c?"black":"white";o.dataset.miniProgramScreenshotWatermark="",o.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);o.style.cssText=`position:absolute;left:${r.left+s.scrollX}px;top:${r.top+s.scrollY+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 f=e.createElement("div");f.style.cssText="display:flex;align-items:center;max-width:calc(100% - 24px);height:22px;flex-shrink:0;";const h=e.createElement("img");h.src=c?rD:eD,h.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const _=e.createElement("div");_.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${u};border-radius:11px;padding:0 7px 0 6px;`;const g=e.createElement("img");g.src=c?nD:tD,g.style.cssText="width:12px;height:12px;flex-shrink:0;";const b=e.createElement("span");b.textContent=t?.trim()||"小程序工坊",b.style.cssText=`color:${u};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const N=e.createElement("div");N.textContent="小黑盒工坊小程序",N.style.cssText=`margin-top:6px;color:${c?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,_.append(g,b),f.append(h,_),l.append(f,N),o.append(l),e.body.append(o);const y=()=>{o.remove(),n.removeEventListener("abort",y)};n.addEventListener("abort",y,{once:!0});try{return await be(()=>Promise.all([h.decode(),g.decode()]),n),await be(()=>new Promise(L=>{let A=s.requestAnimationFrame(()=>{A=s.requestAnimationFrame(()=>{n.removeEventListener("abort",U),L()})});const U=()=>s.cancelAnimationFrame(A);n.addEventListener("abort",U,{once:!0})}),n),y}catch(L){throw y(),L}}const sD=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"]),oD=new Set(["url","inline","eval","unknown"]),aD=/^\/(?:\:segment(?:\/\:segment)*)?$/,cD=/^[a-f0-9]{64}$/,uD=255,dD=160,lD=256;function fD(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!sD.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>lD||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!oD.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=hD(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>dD||!aD.test(i)))return;const s=r.sanitizedPathnameHash;if(!(s!==void 0&&(typeof s!="string"||!cD.test(s)||i===void 0)))return{effectiveDirective:r.effectiveDirective,violatedDirective:r.effectiveDirective,blockedResourceType:r.blockedResourceType,origin:n,sanitizedPathname:i,sanitizedPathnameHash:s,sdkVersion:r.sdkVersion,timestamp:r.timestamp}}function hD(e){if(e!==void 0&&!(typeof e!="string"||e.length>uD))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const xo=["android","ios","ohos","windows","macos","linux"],mD="0.9.0",ED=Object.freeze(["android","ios","ohos","windows","macos"]),um="该小程序暂不支持当前平台",gD="PLATFORM_UNSUPPORTED";function pD(e){return typeof e=="string"&&xo.includes(e)}function TD(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 _D(e){const t=e.manifest;if(!ND(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=ul(e.sdkVersion)??ul(t.sdkVersion);return bD(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:ID()}const r=dm(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function AD(e){const t=TD(e.operatingSystemName);if(!t)return qr("host_operating_system_unknown");const r=e.platformAccess;if(!r)return qr("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:xo,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const o=_D({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return o.status==="invalid"?qr("platform_declaration_invalid",{invalidReason:o.reason,platform:t}):cl(t,o)}if(r.effectivePlatforms===void 0)return qr("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=dm(r.effectivePlatforms);if("reason"in n)return qr("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,s=yD(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return cl(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:s})}function cl(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:qr("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function qr(e,t={}){return{status:"denied",reason:e,message:um,...t}}function ID(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:ED,platformsDeclared:!1,policy:"legacy_mobile_default"}}function dm(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(!pD(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(xo.filter(r=>t.has(r)))}}function bD(e){if(typeof e!="string"||!e.trim())return!1;const t=xc(e.trim(),mD);return t!==void 0&&t>=0}function ul(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function yD(e){return e==="explicit"||e==="legacy_mobile_default"}function ND(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wD(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:DD(i.pathname),sanitizedPathnameHash:Sc(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function DD(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}const SD=1e4,OD=1e4,da=2e3,MD=2,CD="open-with-native-credential-policy",lm="安全提示",fm="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class RD{nonce=Ru();runtimeId=Ru();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;workspaceCardsDisposer;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;failureTransitionInProgress=!1;destroyRequestedDuringFailure=!1;sdkVersionDecision;platformGateDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;unexpectedDocumentLoadTimer;devDocumentDisposer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;firstParty=!1;networkPolicy;networkPolicyDisposer;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=Tf(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities,hasUserDataPresentation:t.userDataPresentation!==void 0,hasUserDataSettings:t.userDataPresentation?.openDataPermissions!==void 0});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??SD,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}getDataPermissionBridge(){return this.capabilityGraph?.permissionBridge}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics,r=this.capabilityGraph?.sandboxDiagnostics,n=this.capabilityGraph?.gameSaveDiagnostics;return{...t?{storage:t}:{},...r?{sandbox:r}:{},...n?{gameSaves:n}:{}}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??Me("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??Me("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(VD(),this.startPromise=this.createReadyPromise(),this.setState("starting"),this.setStatus("starting"),this.launch().catch(t=>{this.failRuntime(t)}),this.startPromise)}destroy(){if(this.failureTransitionInProgress){this.destroyRequestedDuringFailure=!0;return}if(this.stateValue==="destroyed")return;const t=this.terminalError??Me("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.capabilityGraph?.setPostVisible(!0),this.emitLifecycleEvent("show"),this.capabilityGraph?.notifyViewportChange(),!t&&this.stateValue==="ready"&&this.sdkVersionDecision?.heartbeatEnabled&&(this.documentRevalidationPending?this.preparedHistoryTraversalGeneration!==void 0?this.armDocumentRevalidationTimer(this.documentRevalidationGeneration,{waitingForDocument:!0}):this.resendDocumentRevalidationProbe():this.sendLocationProbe())}hide(){this.hostVisible=!1,this.capabilityGraph?.setPostVisible(!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.isInactive()||t!==this.documentRevalidationGeneration?()=>{}:(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;if(this.runtimePermissions=sp(t.runtimePermissions),this.firstParty=t.firstParty===!0,this.networkPolicy=this.firstParty?void 0:_f(t.networkPolicy),this.networkPolicy?.enforcement==="restricted"){const o=t.canonicalIdentity?.miniProgramId?.trim();if(!o||!this.options.networkPolicyEnforcement)throw{code:"NETWORK_POLICY_UNSUPPORTED",message:"当前 Host 尚未具备严格网络策略执行能力,请更新 Host 后重新打开"};const c=await zg(this.options.networkPolicyEnforcement,{policy:this.networkPolicy,miniProgramId:o,launchUrl:t.launchUrl,onInvalidated:()=>this.failRuntime({code:"NETWORK_POLICY_CHANGED",message:"网络权限已变更,请重新打开小程序"})},{signal:this.terminalController.signal});if(this.isInactive()){c();return}this.networkPolicyDisposer=c}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=qp(t.sdkVersionPolicy);const n=Kw(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=AD({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw QD(this.platformGateDecision);if(this.miniProgramDetail=qD(t),this.effectiveCapabilities=pf(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),BD(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 s=await this.confirmDevMiniProgramLaunch(i);if(!this.isInactive()){if(!s){await this.closeAfterDevLaunchCancellation();return}if(this.bridgeServer?.setTargetOrigin(FD(i)),this.launchUrl=i,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const o=Af(new URL(i),this.locationBasePath);this.devDocumentDisposer=ip({iframe:this.iframe,launchUrl:i,nonce:this.nonce,locationBasePath:o,onLeaving:()=>{this.prepareForHistoryTraversal()},onResume:()=>{!this.isInactive()&&this.documentRevalidationPending&&this.beginDocumentRevalidation()},onReload:c=>{this.isInactive()||Nt(u=>this.options.onDevDocumentReload?.(u,o),c)}})}if(this.miniProgramSrc=Kg(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(o){if(this.isInactive())return;const c=Qs(o);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:Cr,errorCode:c.code,message:`默认展示设置失败,沿用宿主当前布局:${c.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Nt(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[Cr])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=jw({verifiedSdkVersion:this.sdkVersionDecision?.sdkVersion,diagnosticCapabilities:this.effectiveCapabilities,account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,media:this.ports.media,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,...this.options.userDataPresentation===void 0?{}:{userDataPresentation:this.options.userDataPresentation},...this.options.onUserDataTelemetry===void 0?{}:{onUserDataTelemetry:this.options.onUserDataTelemetry},workspaceCards:this.ports.workspaceCards,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,networkPolicy:this.networkPolicy,firstParty:this.firstParty,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,prepareLongScreenshot:(n,i)=>Fg(this.iframe,n,i),prepareScreenshot:(n,i,s)=>{const o=this.sdkVersionDecision?.sdkVersion;return!o||(xc(o,"0.9.1")??-1)<0?Promise.resolve(()=>{}):iD(this.iframe.ownerDocument,this.miniProgramPresentation?.name,n,i,s)},miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins,requestPolicy:this.options.requestPolicy,onBackgroundError:(n,i)=>{const s=Qs(i);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",errorCode:s.code,message:`后台任务 ${n} 失败:${s.message}`})},...this.options.onRequestPolicyReport?{onRequestPolicyReport:this.options.onRequestPolicyReport}:{}}),this.capabilityGraph.setPostVisible(this.hostVisible);const r=Bw({handlers:this.capabilityGraph.handlers,runDisplayRequest:this.capabilityGraph.runDisplayRequest,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,allowsGameSaveAccess:this.capabilityGraph.allowsGameSaveAccess,allowsUserGameDataFileAccess:this.capabilityGraph.allowsUserGameDataFileAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:s,timestamp:o,durationMs:c,outcome:u,errorCode:d,network:l})=>{const f={type:"capability",phase:"host",runtimeId:this.runtimeId,callId:n,method:i,startedAt:s,timestamp:o,durationMs:c,outcome:u,...d?{errorCode:d}:{},...this.identity,...l?{network:l}:{}};Nt(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new dp({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,...this.options.onDevUploadSession?{onDevUploadSession:n=>{this.isInactive()||Nt(this.options.onDevUploadSession,n)}}:{},...this.ports.workspaceCards?{getWorkspaceCardLaunchContext:()=>this.ports.workspaceCards.getLaunchContext()}:{},onHandshake:n=>this.handleBridgeHandshake(n),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:n=>{this.handleInternalBridgeEvent(n)},onResponsePosted:({method:n,outcome:i,errorCode:s})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:n,outcome:i,...s?{errorCode:s}:{}})}}),this.bridgeServer.start(),this.workspaceCardsDisposer=this.ports.workspaceCards?.onLaunchContextChange(()=>this.publishWorkspaceCardLaunchContext()),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(Me("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 UD(t)?t:hm(Me("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 $g(t,r,{allowPrivateNetwork:al(r)||dl(r)||await this.isDevRuntime()})}catch(r){throw Me("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??jD)({message:fm,title:lm,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Pu(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!al(r)&&!dl(r)}async closeAfterDevLaunchCancellation(){const t=Me("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{ll(),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(()=>ll())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Yg),this.iframe.setAttribute("referrerpolicy",Qg),this.iframe.setAttribute("sandbox",If)}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.workspaceCardsDisposer];this.lifecycleDisposer=null,this.workspaceCardsDisposer=null;for(const r of t)try{r?.()}catch{}}publishWorkspaceCardLaunchContext(){this.stateValue!=="ready"||!this.ports.workspaceCards||this.bridgeServer?.postEvent("workspace_cards_launch_context_change",this.ports.workspaceCards.getLaunchContext())}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(),Nt(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(),Nt(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Wp(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(Me("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>=MD)){this.failRuntime(Me("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Si,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},da),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Si})}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),t.deferProbe?this.armDocumentRevalidationTimer(r,{waitingForDocument:!0}):this.sendDocumentRevalidationProbe(),this.traceDocumentValidation(),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.armDocumentRevalidationTimer(this.documentRevalidationGeneration),this.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled||this.preparedHistoryTraversalGeneration!==void 0)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(Si,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Si})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&this.failRuntime(Me("DOCUMENT_REVALIDATION_TIMEOUT",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时"))},r.waitingForDocument?OD:da))}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()},da)),this.traceDocumentValidation()}traceDocumentValidation(){this.isInactive()||this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"document_validation",documentVerifying:this.documentRevalidationPending,message:this.documentRevalidationPending?"当前文档正在验证":"当前文档验证等待已结束"})}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(),this.traceDocumentValidation()}handleDuplicateBridgeHandshake(){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"}),this.documentRevalidationPending&&this.resendDocumentRevalidationProbe()}handleInternalBridgeEvent(t){if(t.method==="sdk.post.editor.dismiss"){const i=t.payload;typeof i?.requestId=="string"&&this.capabilityGraph?.dismissPostEditor(i.requestId);return}if(t.method===S0){this.handleCspViolation(t.payload);return}if(t.method!==D0)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(Me("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!bf(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(Me("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=fD(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){Nt(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=wD(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(Me("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:Gg,launchUrlType:Pu(t),networkPolicy:CD})}failRuntime(t){const r=LD(t);if(this.isInactive())return r;this.terminalError=r,this.stateValue="failed",this.failureTransitionInProgress=!0;try{this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),Nt(this.options.onError,PD(r)),Nt(this.options.onStateChange,"failed"),this.terminalController.abort(r),this.postBridgeError(r);try{this.disposeRuntimeResources()}finally{this.teardownIframe(r)}}finally{this.rejectReady?.(r),this.failureTransitionInProgress=!1,this.destroyRequestedDuringFailure&&(this.destroyRequestedDuringFailure=!1,this.destroy())}return 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.devDocumentDisposer?.(),this.devDocumentDisposer=void 0,!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0;try{this.networkPolicyDisposer?.()}catch{}this.networkPolicyDisposer=void 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,Nt(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Nt(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 LD(e){const t=Qs(e);return so(e)&&"cause"in e&&hm(t,e.cause),t}function hm(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function PD(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{},...e.cause!==void 0?{cause:xD(e.cause)}:{}}}const la=(()=>{const e=Object.getOwnPropertyDescriptor(new Error,"stack")?.get,t=Object.getOwnPropertyDescriptor(new Error,"stack")?.get;return typeof e=="function"&&e===t?e:void 0})(),vD=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function kD(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return;if("value"in r)return r.value;if(t!=="stack"||!la||r.get!==la)return;const n=Object.getPrototypeOf(e);if(vD.has(n)){for(const i of["name","message"]){const s=Object.getOwnPropertyDescriptor(e,i),o=Object.getOwnPropertyDescriptor(n,i)??Object.getOwnPropertyDescriptor(Error.prototype,i);if(s&&!("value"in s)||o&&!("value"in o))return}return la.call(e)}}function xD(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=kD(e,r);typeof n=="string"&&(t[r]=n.slice(0,r==="stack"?8192:2048).replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@").replace(/([?&][^=\s]+)=([^&#\s]*)/g,"$1=[redacted]").replace(/(authorization|cookie|password|secret|token|pkey|api[_-]?key)([\"'\s:=]+)([^\s,}]+)/gi,"$1$2[redacted]"))}return Object.keys(t).length?t:void 0}catch{return}}function UD(e){return so(e)&&typeof e.code=="string"&&typeof e.message=="string"}function so(e){return!!e&&typeof e=="object"}function Nt(e,t){try{e?.(t)}catch{}}function BD(e,t,r){try{e?.(t,r)}catch{}}function dl(e){try{const t=new URL(e);return t.protocol==="http:"&&qw(t.hostname)}catch{return!1}}function HD(e){try{return new URL(e).origin}catch{return}}function FD(e){return qg()?"*":HD(e)}function zD(e){return`${lm}
|
|
9
|
-
|
|
10
|
-
${fm}
|
|
11
|
-
|
|
12
|
-
URL: ${e}`}function jD(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(zD(e.url))}function ll(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function VD(){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:Fl,knownMethodCount:cr.length,supportsFileCreate:cr.some(i=>i.method===ti),system:GD(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:Qr(e?.hardwareConcurrency),maxTouchPoints:Qr(e?.maxTouchPoints),screen:{width:Qr(t?.width),height:Qr(t?.height)},viewport:{width:Qr(r?.innerWidth),height:Qr(r?.innerHeight),devicePixelRatio:YD(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function GD(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 Qr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function YD(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function QD(e){return Me(gD,um,{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 qD(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(),s=e.miniProgramPresentation?.author?.trim();return Object.freeze({miniProgramId:t,...r?{version:r}:{},...n?{name:n}:{},...i?{iconUrl:i}:{},...s?{author:s}:{},...e.sdkVersionPolicy.releaseChannel===void 0?{}:{releaseChannel:e.sdkVersionPolicy.releaseChannel}})}function WD(e){if(!so(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!so(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 RD(e)}function $D(e={}){return async(t,r,n)=>{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");const i=e.indexedDB??globalThis.indexedDB,s=e.crypto??globalThis.crypto;if(!i||!s?.getRandomValues)throw new Error("Host 缺少持久化账号标识能力");const o=await new Promise((c,u)=>{const d=i.open("heybox-mini-program-private-account-v1",1);let l=!1;const f=()=>n.signal.removeEventListener("abort",_),h=g=>{l||(l=!0,f(),u(g))},_=()=>h(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{l?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>h(d.error),d.onblocked=()=>h(new Error("账号存储被阻塞")),d.onsuccess=()=>{l?d.result.close():(l=!0,f(),c(d.result))},n.signal.addEventListener("abort",_,{once:!0}),n.signal.aborted&&_()});try{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");return await new Promise((c,u)=>{const d=o.transaction("accounts","readwrite"),l=d.objectStore("accounts"),f=JSON.stringify([t,r]);let h;const _=()=>{try{d.abort()}catch{}g(),u(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",_,{once:!0});const g=()=>n.signal.removeEventListener("abort",_);d.oncomplete=()=>{g(),c(h)},d.onabort=d.onerror=()=>{g(),u(d.error??new Error("账号存储事务失败"))};const b=l.get(f);b.onsuccess=()=>{try{if(typeof b.result=="string"&&/^ak_[0-9a-f]{64}$/.test(b.result))h=b.result;else{const N=s.getRandomValues(new Uint8Array(32));h=`ak_${Array.from(N,y=>y.toString(16).padStart(2,"0")).join("")}`,l.put(h,f)}}catch{d.abort()}}})}finally{o.close()}}}const KD=/^(?: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,ZD=new Set(["origin","referer","user-agent"]);function XD(e,t){return pg({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const s={...n,signal:i},o=JD(r),c=await e.authenticatedRequest(o,s);return r1(c)})}).network}function JD(e){const t=e1(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function e1(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!t1(t)))}function t1(e){const t=e.trim().toLowerCase();return ZD.has(t)}function r1(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:n1(e.headers)??{}}}function n1(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!i1(t)))}function i1(e){const t=e.trim().toLowerCase();return KD.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function s1(e,t,r){const n=d1(e.presentation,t);return{account:c1(e,t,r),network:XD(e,t),...e.storage===void 0?{}:{storage:u1(e,t)},...e.storage===void 0?{}:o1(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function o1(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 s=0;s<r.storage.length;s+=1){const o=r.storage.key(s);if(o===null)continue;const c=r.storage.getItem(o);c!==null&&i.push({area:r.area,key:o,value:c})}return i})}}}function a1(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 c1(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??$D();return{getAccountKey:(i,s,o)=>t.run(o.signal,c=>n(i,s,{...o,signal:c})),getCurrentUserId:i=>t.run(i.signal,s=>e.account.getCurrentUserId({signal:s})),ensureAuthenticated:i=>t.run(i.signal,s=>e.account.ensureAuthenticated({trustedUserGesture:i.trustedUserGesture,reason:i.reason,signal:s})),onChange:i=>{t.assertActive();const s=e.account.onChange(o=>{t.signal.aborted||i(o)});return r(s)}}}function u1(e,t){const r=e.storage.storage;return{getRaw:(n,i)=>t.run(i.signal,()=>{const s=r.getItem(n);return s===null?void 0:s}),setRaw:(n,i,s)=>t.run(s.signal,()=>{r.setItem(n,i)})}}function d1(e,t){if(!e)return;const r={};return e.close&&(r.close=n=>t.run(n.signal,i=>e.close({...n,signal:i}))),e.reload&&(r.reload=n=>t.run(n.signal,i=>e.reload({...n,signal:i}))),e.openAppPage&&(r.openAppPage=(n,i)=>t.run(i.signal,s=>e.openAppPage(n,{...i,signal:s}))),e.openWindow&&(r.openWindow=(n,i)=>t.run(i.signal,s=>e.openWindow(n,{...i,signal:s}))),e.applyOrientation&&(r.applyOrientation=(n,i)=>t.run(i.signal,s=>e.applyOrientation(n,{...i,signal:s}))),e.onViewportChange&&(r.onViewportChange=n=>{t.assertActive();const i=e.onViewportChange(()=>{t.signal.aborted||n()});let s=!1;const o=()=>{s||(s=!0,t.signal.removeEventListener("abort",o),i())};return t.signal.addEventListener("abort",o,{once:!0}),o}),e.getViewportMetrics&&(r.getViewportMetrics=()=>(t.assertActive(),e.getViewportMetrics())),e.getNavigationBarHeight&&(r.getNavigationBarHeight=()=>(t.assertActive(),e.getNavigationBarHeight())),e.setNavigationBarStyle&&(r.setNavigationBarStyle=(n,i)=>t.run(i.signal,s=>e.setNavigationBarStyle(n,{...i,signal:s}))),e.showShareMenu&&(r.showShareMenu=(n,i)=>t.run(i.signal,s=>e.showShareMenu(n,{...i,signal:s}))),e.setScreenshotChromeHidden&&(r.setScreenshotChromeHidden=(n,i)=>Mg(i)?e.setScreenshotChromeHidden(n,i):t.run(i.signal,s=>e.setScreenshotChromeHidden(n,{...i,signal:s}))),e.captureAndShare&&(r.captureAndShare=(n,i)=>t.run(i.signal,s=>e.captureAndShare(n,{...i,signal:s}))),e.showToast&&(r.showToast=(n,i)=>t.run(i.signal,s=>e.showToast(n,{...i,signal:s}))),e.showLoading&&(r.showLoading=(n,i)=>t.run(i.signal,s=>e.showLoading(n,{...i,signal:s}))),e.hideLoading&&(r.hideLoading=n=>t.run(n.signal,i=>e.hideLoading({...n,signal:i}))),e.vibrate&&(r.vibrate=(n,i)=>t.run(i.signal,s=>e.vibrate(n,{...i,signal:s}))),e.setClipboard&&(r.setClipboard=(n,i)=>t.run(i.signal,s=>e.setClipboard(n,{...i,signal:s}))),Object.keys(r).length===0?void 0:r}function l1(){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 Fi(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 Fi(i.reason);const s=new AbortController;let o;const c=new Promise((l,f)=>{o=f}),u=n.map(l=>{const f=()=>{s.signal.aborted||s.abort(l.reason),o(Fi(l.reason))};return l.addEventListener("abort",f,{once:!0}),{listener:f,source:l}});let d;try{d=Promise.resolve(r(s.signal))}catch(l){d=Promise.reject(l)}try{const l=await Promise.race([d,c]),f=n.find(h=>h.aborted);if(f)throw Fi(f.reason);return l}finally{for(const{listener:l,source:f}of u)f.removeEventListener("abort",l)}}}}function Fi(e){return new DOMException("Web Host operation aborted","AbortError")}async function f1(e){const t=l1(),r=new Set;let n=!1;const i=h=>{if(n||t.signal.aborted)return fa(h),()=>{};let _=!0;const g=()=>{_&&(_=!1,r.delete(g),fa(h))};return r.add(g),g},s=()=>o(e.signal.reason),o=h=>{if(!n){n=!0,e.signal.removeEventListener("abort",s),t.abort(h);for(const _ of[...r])_();e.onDispose&&fa(e.onDispose)}};e.signal.addEventListener("abort",s,{once:!0}),e.signal.aborted&&o(e.signal.reason);const c=s1(e,t,i);c.storage?.getRaw&&c.storage.setRaw&&(c.scopedStorage=Zh({storage:c.storage,diagnostics:c.storageDiagnostics,coordinationKey:e.storage.storage,lock:Xh,resolveScope:async()=>Kh((await f()).configuration)}));const u=Tf(c,{hostCapabilities:e.hostCapabilities,hasUserDataPresentation:e.userDataPresentation!==void 0,hasUserDataSettings:e.userDataPresentation?.openDataPermissions!==void 0}),d=a1(e,t);let l;const f=()=>l??=t.run(void 0,h=>e.resolveLaunch(h));return{platform:"web",ports:c,environment:d,resolveLaunch:f,...e.authPresentation===void 0?{}:{authPresentation:h1(e.authPresentation,t)},...e.userDataPresentation===void 0?{}:{userDataPresentation:m1(e.userDataPresentation,t)},hostCapabilities:u.effectiveCapabilities,dispose:o}}function fa(e){try{e()}catch{}}function h1(e,t){return{...e.confirmFollowAuthor?{confirmFollowAuthor:r=>t.run(r.signal,n=>e.confirmFollowAuthor({...r,signal:n}))}:{},confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}function m1(e,t){return{...e.openDataPermissions?{openDataPermissions:r=>t.run(r.signal,n=>e.openDataPermissions({...r,signal:n}))}:{},confirmDataPermission:r=>t.run(r.signal,n=>e.confirmDataPermission({...r,signal:n}))}}function E1(e){const t=`hb-game-saves-${crypto.randomUUID()}`,r=u=>`hb-sdk:game-save-cache:${u}`;let n,i;const s=new Promise((u,d)=>{n=u,i=d});let o;const c=new Promise(u=>{o=u});return e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&o(),e.locks.request(r(t),async()=>{let u;try{u=await e.getRoot();const d=await e.locks.request("hb-sdk:game-save-cache:gc",async()=>{e.signal.throwIfAborted();for await(const[l,f]of u)f.kind!=="directory"||!/^hb-game-saves-[a-f0-9-]{36}$/.test(l)||await e.locks.request(r(l),{ifAvailable:!0},async h=>{h&&await fl(u,l)});return e.signal.throwIfAborted(),u.getDirectoryHandle(t,{create:!0})});e.signal.throwIfAborted(),n(d),await c}catch(d){i(d)}finally{e.signal.removeEventListener("abort",o),u&&await fl(u,t).catch(()=>{})}}).catch(i),s.catch(()=>{}),s}async function fl(e,t){for(let r=0;;r++)try{await e.removeEntry(t,{recursive:!0});return}catch(n){if(n instanceof DOMException&&n.name==="NotFoundError")return;if(!(n instanceof DOMException)||n.name!=="NoModificationAllowedError"||r>=4)throw n;await new Promise(i=>setTimeout(i,25*(r+1)))}}const ha=8*1024*1024,g1=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),p1="/__hb_sdk__/game-save-download",it=(e,t)=>({code:e,message:t});function T1(e){const t=e.getRoot??(navigator.storage?.getDirectory?()=>navigator.storage.getDirectory():void 0),r=e.locks??navigator.locks,n=e.supportsWritable??(typeof FileSystemFileHandle<"u"&&typeof FileSystemFileHandle.prototype.createWritable=="function");if(!t||!r||!n)return;const i=E1({getRoot:t,locks:r,signal:e.signal}),s=new WeakMap,o=new WeakSet,c=g=>{g.signal.throwIfAborted(),g.lifecycle!=="cleanup"&&e.signal.throwIfAborted()},u=()=>i;function d(g){if(!/^\.hb-game-saves\/[a-zA-Z0-9_-]+\.zip$/.test(g))throw it("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存");return g.slice(15)}async function l(g,b){c(b);const N=d(g);try{return await(await u()).getFileHandle(N)}catch(y){throw y instanceof DOMException&&y.name==="NotFoundError"?it("FILE_NOT_FOUND","存档缓存不存在"):y}}function f(g){const b={kind:"file",mode:"readwrite",name:g.split("/").at(-1),async create(N,y){c(y);const L=d(g),A=await u();if(N.exclusive)try{throw await A.getFileHandle(L),it("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(U){if(!(U instanceof DOMException&&U.name==="NotFoundError"))throw U}c(y),await A.getFileHandle(L,{create:!0}),c(y)},async remove(N){c(N);const y=d(g);if(i)try{await(await i).removeEntry(y)}catch(L){if(!(L instanceof DOMException&&L.name==="NotFoundError"))throw L}},async read(N){const y=await(await l(g,N)).getFile();if(y.size>ha)throw it("FILE_TOO_LARGE","存档文件超过 8 MiB");const L=new Uint8Array(await y.arrayBuffer());try{return c(N),L}catch(A){throw L.fill(0),A}},async write(){throw it("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(N){const y=await(await l(g,N)).getFile();return c(N),{kind:"file",size:y.size,modifiedAt:y.lastModified}}};return s.set(b,g),b}const h=async()=>{throw it("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},_={kind:"directory",mode:"readwrite",name:"",file:f,directory(g){return{..._,name:g,async create(b,N){if(c(N),g!==".hb-game-saves")return h();await u(),c(N)}}},create:h,stat:h,list:h};return{files:{sandbox:_},transfer:{network:{async open(g,b){if(c(b),!hf(g))throw it("METHOD_FORBIDDEN","仅支持受控存档下载");const N=await(e.fetch??fetch)(p1,{method:"POST",credentials:"same-origin",redirect:"error",headers:{"content-type":"application/json","x-hb-sdk-csrf":e.csrfToken()},body:JSON.stringify(g),signal:AbortSignal.any([b.signal,e.signal,AbortSignal.timeout(6e4)])});if(!N.ok){const y=await N.json().catch(()=>({}));throw it(y.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return o.add(N),{status:N.status,headers:Object.fromEntries(Array.from(N.headers).filter(([y])=>g1.has(y)).map(([y,L])=>[y,[L]])),body:N}},async release(g){o.delete(g),await g.body?.cancel()}},files:{async writeResource(g,b,N,y){let L,A;try{c(y);const U=s.get(g);if(!U||!o.delete(b))throw it("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(N.mode!=="replace-existing")throw it("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(L=await(await l(U,y)).createWritable(),!b.body)throw it("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");A=b.body.getReader();let C=0;for(;;){c(y);const P=await A.read().catch(M=>{throw c(y),it(M instanceof DOMException&&M.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(c(y),P.done)break;if(C+=P.value.byteLength,C>Math.min(N.maxBytes??ha,ha))throw it("FILE_TOO_LARGE","存档文件超过 8 MiB");await L.write(new Uint8Array(P.value)),y.onProgress(C)}if(N.expectedBytes!==void 0&&C!==N.expectedBytes)throw it("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return c(y),await L.close(),L=void 0,{committedBytes:C}}catch(U){throw U instanceof DOMException&&U.name==="QuotaExceededError"?it("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):U}finally{await A?.cancel().catch(()=>{}),A||await b.body?.cancel().catch(()=>{}),await L?.abort().catch(()=>{}),o.delete(b)}}}}}}function vt(e,t){throw{code:e,message:t}}function Rn(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.keys(r).sort().map(n=>[n,r[n]])):r)}function _1(e){return{declaredPermissions:e.declaredPermissions??{},platforms:[...e.platforms??[]].sort(),runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy}}function A1(e){const t=e.now??Date.now;let r;const n=new Map,i=()=>{r=void 0};e.signal.addEventListener("abort",i,{once:!0});function s(){if(e.signal.aborted)throw new DOMException("调试会话已结束","AbortError");const c=e.readState();c.userId||(i(),vt("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:u,browser:d}=c,l=jE(u.developmentSnapshot);(u.source!=="remote"||!u.miniProgramId||!u.localDevLaunchToken||!u.expiresAt||u.expiresAt<=t()||!l||!u.developmentSnapshotDigest||!/^[a-f0-9]{64}$/.test(u.developmentSnapshotDigest))&&(i(),vt("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态"));let f;try{f=lf({...l,declared_permissions:d.declaredPermissions??{},platforms:d.platforms??[]})}catch{}(d.source!=="remote"||d.miniProgramId!==u.miniProgramId||d.devSessionId!==l.session_id||u.devSessionId!==l.session_id||u.contextRevision!==l.revision||f!==u.developmentSnapshot||Rn(d.runtimePermissions)!==Rn(u.runtimePermissions)||Rn(d.networkPolicy)!==Rn(u.networkPolicy))&&(i(),vt("AUTHORIZATION_CONTEXT_CHANGED","开发快照正在更新,请稍后重试"));const h={mini_program_id:u.miniProgramId,launch_kind:"remote-dev",version_identity:`dev:${l.session_id}:${l.revision}`,sdk_version:l.sdk_version,local_dev_launch_token:u.localDevLaunchToken,dev_snapshot_digest:u.developmentSnapshotDigest,dev_network_enabled:c.networkEnabled};return{body:h,key:Rn([c.userId,c.accountRevision,h,d.contextRevision,_1(d)]),expiresAt:u.expiresAt}}async function o(c,u){const d=u.signal;let l;try{l=await e.request({source:"runtime-private",credentials:"heybox-session",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:"heybox.user_miniprogram.runtime.auth.context.post",path:"/user_miniprogram/runtime/auth/context",channel:"api"},method:"POST",bodyEncoding:"form",data:c.body,timeout:1e4},u)}catch(b){d.throwIfAborted();const N=b&&typeof b=="object"&&"code"in b?String(b.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(N)&&vt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(N)||b instanceof DOMException&&["AbortError","TimeoutError"].includes(b.name))throw b;vt("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted(),s().key!==c.key&&vt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const f=l.data;(l.status===401||f?.status==="login"||f?.status==="relogin")&&vt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(l.status!==200||f?.status!=="ok")&&vt("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const h=f.result,_=Number(h?.expires_at)*1e3;(typeof h?.token!="string"||!h.token.trim()||!Number.isSafeInteger(h?.expires_at)||!Number.isSafeInteger(_)||_<=t()||!["legacy","local","server"].includes(String(h.user_data_mode)))&&vt("INVALID_RESPONSE","开发运行授权响应无效");const g={token:h.token,expiresAt:Math.min(_,c.expiresAt),steamAccount:h.steam_account===!0,userDataMode:h.user_data_mode};return r={key:c.key,value:g},g}return{async get(c){const u=AbortSignal.any([c.signal,e.signal]);u.throwIfAborted(),await e.refreshAccount(u),u.throwIfAborted();const d=s();if(r?.key===d.key&&r.value.expiresAt>t()+3e4)return r.value;i();let l=n.get(d.key);if(!l||l.controller.signal.aborted){const h=new AbortController,_=o(d,{...c,signal:AbortSignal.any([h.signal,e.signal])});l={promise:_,controller:h,users:0},n.set(d.key,l);const g=l;_.finally(()=>{n.get(d.key)===g&&n.delete(d.key)}).catch(()=>{})}l.users++;let f;try{const h=await Promise.race([l.promise,new Promise((_,g)=>{f=()=>g(u.reason),u.addEventListener("abort",f,{once:!0}),u.aborted&&f()})]);return u.throwIfAborted(),s().key!==d.key&&vt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),h}finally{u.removeEventListener("abort",f),--l.users===0&&l.controller.abort()}}}}const I1="/__hb_sdk__/dev-context";function hl(e,t){return fi(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId:void 0,developmentSnapshot:typeof e.developmentSnapshot=="string"?e.developmentSnapshot:void 0,developmentSnapshotDigest:typeof e.developmentSnapshotDigest=="string"?e.developmentSnapshotDigest:void 0,localDevLaunchToken:typeof e.localDevLaunchToken=="string"?e.localDevLaunchToken:void 0,runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,...e.source==="remote"&&e.firstParty===!0?{firstParty:!0}:{},publishedRuntimePermissions:e.publishedRuntimePermissions,warning:typeof e.warning=="string"?e.warning:void 0,declaredPermissions:fi(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 Yn(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Jl(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:X0({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 b1(e){if(!fi(e)||!ml(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!fi(t)||!ml(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const y1={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Uo(e){const t=ot(e.localDevGrant?Dc({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}}:w1()}function mm(e,t,r){return r?.localDevGrant?Dc({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:Em(e,t,t.networkRequest.useOfficialDomain)}function N1(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=Uo({...e,localDevGrant:void 0});return Em(e.runtimePermissions,t,!1)}function w1(){return{networkRequest:{...y1.networkRequest}}}function Em(e,t,r){const n=ot(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const o of Pr){const c=n.permissions[o];c&&i.push(o==="network"?{key:o,status:t.networkRequest.status,config:{useOfficialDomain:r}}:o==="user_game_data"||o==="post"?{key:o,status:c.status,config:{...c.config}}:{key:o,status:c.status,config:{}})}const s=fi(e)&&typeof e.revision=="number"&&Number.isInteger(e.revision)&&e.revision>=0?e.revision:void 0;return{schema_version:1,...s===void 0?{}:{revision:s},entries:i}}function fi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function ml(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function D1(e){let t,r=!1,n=!1,i;return{invalidate(c){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(c,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=s().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function s(){let c={ok:!0};for(;r&&!n;){r=!1;const u=new AbortController;t=u;let d;try{d=await e.fetch(u.signal)}catch(f){c={ok:!1},!n&&!u.signal.aborted&&o(f);continue}finally{t===u&&(t=void 0)}if(n)return{ok:!1};let l;try{l=e.apply(d)}catch(f){c={ok:!1},n||o(f);continue}if(n)return{ok:!1};if(c={ok:!0},!!e.hasChanged(l))try{await e.onChanged(l)}catch(f){c={ok:!1},n||o(f)}}return n?{ok:!1}:c}function o(c){try{e.onError(c)}catch{}}}function S1(e){return D1({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 O1(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,s;return{schedule:o,reset(){n=t,c()},dispose(){i||(i=!0,c())}};function o(){i||e.isDisposed()||(c(),s=e.timers.setTimeout(async()=>{s=void 0;let u;try{u=await e.invalidate()}catch{u={ok:!1}}if(!(i||e.isDisposed())){if(u.ok){n=t,e.connectEvents();return}n=Math.min(n*2,r),o()}},n))}function c(){s!==void 0&&e.timers.clearTimeout(s),s=void 0}}const ma=new WeakMap;function Wc(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}const{root:n,signal:i}=e;ma.set(n,document.activeElement);const s=[...n.querySelectorAll("button[data-action]")];n.dataset.hostDialog="true",n.style.zIndex="40";const o=()=>[...document.querySelectorAll("[data-host-dialog]")].at(-1);n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-label",e.title);let c;const u=()=>{i?.removeEventListener("abort",l),document.removeEventListener("keydown",h);const g=o()===n;if(n.remove(),g){const b=o();b&&(b.inert=!1,b.removeAttribute("aria-hidden"));let N=ma.get(n)??null;for(;N instanceof HTMLElement&&!N.isConnected;){const y=N.closest("[data-host-dialog]");N=y?ma.get(y)??null:null}N instanceof HTMLElement&&(!b||b.contains(N))?N.focus():b?.querySelector("button")?.focus()}},d=Ym({kind:"dialog",mode:e.mode??"simulated",title:e.title,method:e.method,...e.callId?{callId:e.callId}:{},actions:s.map(g=>g.textContent?.trim()??"")},g=>{u(),c!==void 0?t(c):r(i?.reason??new DOMException(`宿主弹窗已${g}`,"AbortError"))});function l(){d.finish("cancelled")}function f(g){c=g,d.finish(g===e.cancelAction?"cancelled":"confirmed")}function h(g){if(o()!==n||(g.key==="Escape"&&e.cancelAction&&(g.preventDefault(),f(e.cancelAction)),g.key!=="Tab"||s.length===0))return;const b=s[0],N=s.at(-1);g.shiftKey&&document.activeElement===b?(g.preventDefault(),N.focus()):!g.shiftKey&&document.activeElement===N&&(g.preventDefault(),b.focus())}if(!d.active)return;if(i?.aborted){l();return}for(const g of s)g.addEventListener("click",()=>f(g.dataset.action));n.addEventListener("click",g=>{g.target===n&&e.cancelAction&&f(e.cancelAction)}),n.dataset.interactionId=d.interactionId;const _=o();_&&(_.inert=!0,_.setAttribute("aria-hidden","true")),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n),i?.addEventListener("abort",l,{once:!0}),document.addEventListener("keydown",h),s[0]?.focus(),i?.aborted&&l()})}function Tt(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}const El="hb-sdk-action-dialog-style";async function Bo(e){await gm(e)}async function M1(e){return await gm({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function gm(e){v1();const t=document.createElement("div");return t.className="hb-sdk-action-dialog",t.innerHTML=`
|
|
13
|
-
<div class="hb-sdk-action-dialog__panel">
|
|
14
|
-
<h2>${Tt(e.title)}</h2>
|
|
15
|
-
<pre class="hb-sdk-action-dialog__detail">${Tt(e.detail)}</pre>
|
|
16
|
-
<div class="hb-sdk-action-dialog__actions">
|
|
17
|
-
${e.confirmation?'<button type="button" data-action="cancel">取消</button>':""}
|
|
18
|
-
<button type="button" class="primary" data-action="confirm">${e.confirmation?"关注":"确定"}</button>
|
|
19
|
-
</div>
|
|
20
|
-
</div>`,await Wc({root:t,title:e.title,method:e.method??"host.action",signal:e.signal,callId:e.callId,mode:e.mode,...e.confirmation?{cancelAction:"cancel"}:{}})==="confirm"}async function C1(e,t){await Bo({method:"navigation.openAppPage",title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+un(e.params)].join(`
|
|
21
|
-
`),signal:t.signal,callId:t.requestId})}async function R1(e,t){await Bo({method:"navigation.openAppPage",title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+un(e.extra)].join(`
|
|
22
|
-
`),signal:t.signal,callId:t.requestId})}async function L1(e,t){await Bo({method:"share.showShareMenu",title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+un(e.channel),"post: "+un(e.post)].join(`
|
|
23
|
-
`),signal:t.signal,callId:t.requestId})}async function P1(e,t){await Bo({method:"share.screenshot",title:"截图分享",detail:["rect: "+un(e.rect),"post: "+un(e.post)].join(`
|
|
24
|
-
`),signal:t.signal,callId:t.requestId})}function un(e){return JSON.stringify(e,null,2)}function v1(){if(document.getElementById(El))return;const e=document.createElement("style");e.id=El,e.textContent=`
|
|
25
|
-
.hb-sdk-action-dialog {
|
|
26
|
-
position: absolute;
|
|
27
|
-
inset: 0;
|
|
28
|
-
display: grid;
|
|
29
|
-
place-items: center;
|
|
30
|
-
padding: 24px;
|
|
31
|
-
background: rgba(15, 23, 42, 0.45);
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
.hb-sdk-action-dialog__panel {
|
|
35
|
-
width: min(420px, 100%);
|
|
36
|
-
border-radius: 12px;
|
|
37
|
-
padding: 20px;
|
|
38
|
-
background: #fff;
|
|
39
|
-
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
.hb-sdk-action-dialog__panel h2 {
|
|
43
|
-
margin: 0 0 8px;
|
|
44
|
-
font-size: 18px;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
.hb-sdk-action-dialog__detail {
|
|
48
|
-
margin: 0 0 16px;
|
|
49
|
-
max-height: 40vh;
|
|
50
|
-
overflow: auto;
|
|
51
|
-
color: #1f2933;
|
|
52
|
-
font-family: inherit;
|
|
53
|
-
font-size: 12px;
|
|
54
|
-
line-height: 1.6;
|
|
55
|
-
white-space: pre-wrap;
|
|
56
|
-
overflow-wrap: anywhere;
|
|
57
|
-
word-break: break-word;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
.hb-sdk-action-dialog__actions {
|
|
61
|
-
display: flex;
|
|
62
|
-
justify-content: flex-end;
|
|
63
|
-
gap: 8px;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
.hb-sdk-action-dialog__actions button {
|
|
67
|
-
min-height: 36px;
|
|
68
|
-
border: 1px solid #cad5e2;
|
|
69
|
-
border-radius: 6px;
|
|
70
|
-
padding: 0 12px;
|
|
71
|
-
background: #fff;
|
|
72
|
-
cursor: pointer;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
.hb-sdk-action-dialog__actions .primary {
|
|
76
|
-
border-color: #2563eb;
|
|
77
|
-
color: #fff;
|
|
78
|
-
background: #2563eb;
|
|
79
|
-
}
|
|
80
|
-
`,document.head.appendChild(e)}const k1={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};async function x1(e){const t=document.createElement("div");return t.className="hb-sdk-auth-dialog",t.innerHTML=`
|
|
81
|
-
<div class="hb-sdk-auth-dialog__panel">
|
|
82
|
-
<h2>授权请求</h2>
|
|
83
|
-
<p class="hb-sdk-auth-dialog__app">${Tt(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
|
|
84
|
-
<ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(n=>`<li>${Tt(k1[n]||n)}</li>`).join("")}</ul>
|
|
85
|
-
${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${Tt(e.userProfile.nickname)}</p>`:""}
|
|
86
|
-
<div class="hb-sdk-auth-dialog__actions">
|
|
87
|
-
<button type="button" data-action="deny">拒绝</button>
|
|
88
|
-
<button type="button" class="primary" data-action="allow">允许</button>
|
|
89
|
-
</div>
|
|
90
|
-
</div>
|
|
91
|
-
`,await Wc({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function U1(e){const t=e.miniProgramName?.trim();return{launchUrl:e.launchUrl,...e.locationBasePath!==void 0?{locationBasePath:e.locationBasePath}:{},...t?{miniProgramPresentation:{name:t}}:{},sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:ou,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,firstParty:e.firstParty===!0,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:xo},sdkVersion:ou},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const gl="hb-sdk-user-data-dialog-style",B1=new Map(Sr.map(e=>[e.key,e.name]));function H1(e){return(tr(e)?B1.get(e):void 0)??"游戏资料"}function F1(e){return e==="upload"?"可上传":"无网络权限"}async function z1(e){V1();const t=e.miniProgramName?.trim()||"当前小程序",r=H1(e.resource),n=`“${t}”想读取你的${r}`,i=F1(e.egress),s=cg[e.egress],o=e.egress==="upload"?"↑":"⊘",c=document.createElement("div");c.className="hb-sdk-user-data-dialog",c.innerHTML=`
|
|
92
|
-
<div class="hb-sdk-user-data-dialog__panel">
|
|
93
|
-
<h2>${Tt(n)}</h2>
|
|
94
|
-
<dl class="hb-sdk-user-data-dialog__meta">
|
|
95
|
-
<dt>范围</dt><dd>${Tt(e.scopeText)}</dd>
|
|
96
|
-
<dt>用途</dt><dd>${Tt(e.purposeText)}</dd>
|
|
97
|
-
</dl>
|
|
98
|
-
<p class="hb-sdk-user-data-dialog__egress" data-egress="${Tt(e.egress)}">
|
|
99
|
-
<span class="hb-sdk-user-data-dialog__egress-label" aria-hidden="true">${Tt(o)}</span>
|
|
100
|
-
<span class="hb-sdk-user-data-dialog__egress-tag">${Tt(i)}</span>
|
|
101
|
-
<span>${Tt(s)}</span>
|
|
102
|
-
</p>
|
|
103
|
-
<p class="hb-sdk-user-data-dialog__browser-note">读取当前登录黑盒账号的真实资料。许可仅适用于本浏览器,不会同步到手机或其他客户端;来源登录需另行完成。</p>
|
|
104
|
-
<div class="hb-sdk-user-data-dialog__actions">
|
|
105
|
-
<button type="button" data-action="deny">拒绝</button>
|
|
106
|
-
<button type="button" data-action="session">本次使用允许</button>
|
|
107
|
-
${e.canPersist===!1?"":'<button type="button" class="primary" data-action="persistent">在此浏览器上始终允许</button>'}
|
|
108
|
-
</div>
|
|
109
|
-
</div>
|
|
110
|
-
`;const u=await Wc({root:c,title:n,method:"user.dataPermission.confirm",mode:"browser",signal:e.signal,cancelAction:"cancelled"});return{decision:j1(u)}}function j1(e){return e==="deny"||e==="session"||e==="persistent"?e:"cancelled"}function V1(){if(document.getElementById(gl))return;const e=document.createElement("style");e.id=gl,e.textContent=`
|
|
111
|
-
.hb-sdk-user-data-dialog {
|
|
112
|
-
position: absolute;
|
|
113
|
-
inset: 0;
|
|
114
|
-
display: grid;
|
|
115
|
-
place-items: center;
|
|
116
|
-
padding: 24px;
|
|
117
|
-
background: rgba(15, 23, 42, 0.45);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
.hb-sdk-user-data-dialog__panel {
|
|
121
|
-
width: min(440px, 100%);
|
|
122
|
-
border-radius: 12px;
|
|
123
|
-
padding: 20px;
|
|
124
|
-
background: #fff;
|
|
125
|
-
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
.hb-sdk-user-data-dialog__panel h2 {
|
|
129
|
-
margin: 0 0 12px;
|
|
130
|
-
font-size: 17px;
|
|
131
|
-
line-height: 1.45;
|
|
132
|
-
color: #1f2933;
|
|
133
|
-
overflow-wrap: anywhere;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
.hb-sdk-user-data-dialog__meta {
|
|
137
|
-
display: grid;
|
|
138
|
-
grid-template-columns: auto 1fr;
|
|
139
|
-
gap: 4px 10px;
|
|
140
|
-
margin: 0 0 12px;
|
|
141
|
-
font-size: 12px;
|
|
142
|
-
line-height: 1.6;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
.hb-sdk-user-data-dialog__meta dt {
|
|
146
|
-
color: #7b8794;
|
|
147
|
-
white-space: nowrap;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
.hb-sdk-user-data-dialog__meta dd {
|
|
151
|
-
white-space: pre-wrap;
|
|
152
|
-
margin: 0;
|
|
153
|
-
color: #1f2933;
|
|
154
|
-
overflow-wrap: anywhere;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
.hb-sdk-user-data-dialog__egress {
|
|
158
|
-
display: flex;
|
|
159
|
-
flex-wrap: wrap;
|
|
160
|
-
align-items: baseline;
|
|
161
|
-
gap: 6px;
|
|
162
|
-
margin: 0 0 10px;
|
|
163
|
-
padding: 10px 12px;
|
|
164
|
-
border: 1px solid #cad5e2;
|
|
165
|
-
border-radius: 8px;
|
|
166
|
-
font-size: 12px;
|
|
167
|
-
line-height: 1.6;
|
|
168
|
-
color: #1f2933;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
.hb-sdk-user-data-dialog__egress[data-egress="upload"] {
|
|
172
|
-
border-color: #e0b34d;
|
|
173
|
-
background: #fff8e6;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
.hb-sdk-user-data-dialog__egress[data-egress="no_network"] {
|
|
177
|
-
border-color: #9fb3c8;
|
|
178
|
-
background: #f2f6fa;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
.hb-sdk-user-data-dialog__egress-label {
|
|
182
|
-
font-weight: 700;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
.hb-sdk-user-data-dialog__egress-tag {
|
|
186
|
-
font-weight: 700;
|
|
187
|
-
white-space: nowrap;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
.hb-sdk-user-data-dialog__browser-note {
|
|
191
|
-
margin: 0 0 16px;
|
|
192
|
-
font-size: 11px;
|
|
193
|
-
line-height: 1.6;
|
|
194
|
-
color: #7b8794;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
.hb-sdk-user-data-dialog__actions {
|
|
198
|
-
display: flex;
|
|
199
|
-
flex-wrap: wrap;
|
|
200
|
-
justify-content: flex-end;
|
|
201
|
-
gap: 8px;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
.hb-sdk-user-data-dialog__actions button {
|
|
205
|
-
min-height: 36px;
|
|
206
|
-
border: 1px solid #cad5e2;
|
|
207
|
-
border-radius: 6px;
|
|
208
|
-
padding: 0 12px;
|
|
209
|
-
background: #fff;
|
|
210
|
-
color: #1f2933;
|
|
211
|
-
cursor: pointer;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
.hb-sdk-user-data-dialog__actions .primary {
|
|
215
|
-
border-color: #2563eb;
|
|
216
|
-
color: #fff;
|
|
217
|
-
background: #2563eb;
|
|
218
|
-
}
|
|
219
|
-
`,document.head.appendChild(e)}function G1(e){let t,r,n,i,s,o=0,c=0,u=0,d=!1,l=Promise.resolve();const f=new Set,h=()=>{const y=e.resolveScope();return y?JSON.stringify(y):void 0},_=()=>{if(!d)for(const y of f)y()},g=async()=>{if(d||u)return;const y=t,L=h(),A=++o;if(!y||!L){r=void 0,i=void 0,_();return}try{const U=await y.getSnapshot();if(d||A!==o||t!==y||L!==h())return;r=U,n=L,i=void 0}catch(U){if(d||A!==o||t!==y||L!==h())return;r=void 0,s=L,i=U instanceof Error?U.message:"许可状态不可用"}_()},b=y=>{const L=t,A=h(),U=c;if(d||!L||!A)return Promise.resolve();const Q=++o;u++;const C=l.then(async()=>{if(!(d||c!==U||A!==h()))try{const P=await y(L);if(d||Q!==o||c!==U||A!==h())return;r=P,n=A,i=void 0}catch(P){if(d||Q!==o||c!==U||A!==h())return;r=void 0,s=A,i=P instanceof Error?P.message:"许可设置失败"}}).finally(()=>{c===U&&u--,_()});return l=C,C},N=()=>{c++,o++,u=0,l=Promise.resolve(),t=void 0,r=void 0,i=void 0};return{snapshot(){const y=h(),L=y&&y===n?r:void 0,A=e.declared?.();return{scenario:"unknown",dataScenario:"unknown",egressTier:e.egressTier(),declaredSource:A?.source??"manifest",permissionStateReady:L!==void 0,stateError:y&&y===s?i:void 0,simulatedSession:[],resources:Sr.map(U=>{const Q=L?.resources.find(P=>P.resource===U.key),C=Q?.allowed===!0;return{resource:U.key,name:U.name,declared:A?.resources.includes(U.key)??!1,decision:Q?.decision??"ask",revision:Q?.revision??0,sessionAllowed:Q?.sessionAllowed??!1,sessionSimulated:!1,licensed:C,...C?{sourceStatus:"unknown"}:{}}})}},subscribe(y){return d||f.add(y),()=>f.delete(y)},bind(y){d||(N(),t=y,g())},refresh:g,revokeSession:()=>b(y=>y.revokeSession()),resetAll:()=>b(y=>y.resetAll()),clearSession(){N(),_()},dispose(){d=!0,N(),f.clear()}}}function Y1(e){const t="hb_user_game_data_consent_",r="hb_browser_real_user_game_data_consent_",n=i=>i.startsWith(t)?`${r}${i.slice(t.length)}`:i;return{getItem(i){return e.getItem(n(i))},setItem(i,s){e.setItem(n(i),s)},get length(){return e.length},key(i){const s=e.key(i);return s?.startsWith(t)?null:s?.startsWith(r)?`${t}${s.slice(r.length)}`:s}}}function Q1(e){const t=ot(e.runtimePermissions);let r={};return t.valid&&t.permissions.user_game_data?.status==="enabled"?r=ci(t.permissions.user_game_data.config.resources):e.runtimePermissions===void 0&&e.declaredPermissions?.user_game_data?.enabled&&(r=ci(e.declaredPermissions.user_game_data.resources)),{resources:$0(r),source:"manifest"}}const q1=Object.freeze({user_game_data_permission_show:["entry","reason"],user_game_data_permission_result:["choice","apply_result"],user_game_data_permission_manage:["operation","apply_result","succeeded_count","failed_count"],user_game_data_action:["stage","action_type","outcome","duration_ms"],user_game_data_access_result:["api","trigger","status","error_code","failure_stage","duration_ms","cache_hit"]}),W1="host.userDataTelemetry",pl=80;function $1(e){return{method:W1,detail:{...e.payload,eventName:e.name,message:K1(e)}}}function K1(e){const t=q1[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}: ${pm(i)}`)}return[e.name,...r].join(" · ")}function pm(e){let t;if(typeof e=="string")t=e;else if(typeof e=="number"||typeof e=="boolean")t=String(e);else if(Array.isArray(e))t=e.map(r=>pm(r)).join(",");else try{t=JSON.stringify(e)??""}catch{t="[无法序列化]"}return t.length>pl?`${t.slice(0,pl)}…`:t}const Z1=44;function X1(e){const t=()=>e.isCapsuleHidden?.()?0:Z1,r=()=>{const n=e.getDeviceMetrics?.();return n?{windowWidth:n.screenWidth,windowHeight:n.screenHeight,screenWidth:n.screenWidth,screenHeight:n.screenHeight,pixelRatio:n.pixelRatio,safeArea:{top:n.safeAreaInsets.top+t(),right:n.screenWidth-n.safeAreaInsets.right,bottom:n.screenHeight-n.safeAreaInsets.bottom,left:n.safeAreaInsets.left}}:{windowWidth:window.innerWidth,windowHeight:window.innerHeight,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}};return{...e.applyDisplay?{applyOrientation:async(n,i)=>(await e.applyDisplay(n,i.signal),{supported:!0})}:{},...e.onViewportChange?{onViewportChange:e.onViewportChange}:{},close:async()=>{await e.close()},reload:async()=>{await e.reload()},getViewportMetrics:()=>e.getViewportMetrics?.()??r(),getNavigationBarHeight:()=>{if(e.getNavigationBarHeight)return e.getNavigationBarHeight();const n=e.getDeviceMetrics?.().statusBarHeight;return n===void 0?0:n+t()},setNavigationBarStyle:n=>{document.documentElement.dataset.navigationBarStyle=n,e.onNavigationBarStyleChange?.(n)},setClipboard:async({text:n})=>{await navigator.clipboard.writeText(n)},showToast:Km,showLoading:$m,hideLoading:Wm,vibrate:qm,openAppPage:C1,openWindow:R1,showShareMenu:L1,captureAndShare:P1,setScreenshotChromeHidden:Qm}}const Tl=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],zi=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],_l={"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 J1{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]:[...Tl];for(const n of r){const i=this.preparations.get(n);for(const s of i?.operation?.timers??[])this.clearSchedule(s);i?.operation?.reject(Ze("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:_l[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:zi[0]),i.operation.promise;let s,o;const c=new Promise((d,l)=>{s=d,o=l}),u={cancelled:!1,listeners:new Set([r.onProgress]),promise:c,reject:o,resolve:s,timers:new Set};{const d={status:{state:"preparing",progress:zi[0]},operation:u};this.preparations.set(n,d),this.diagnostic("prepare.started",n),zi.forEach((l,f)=>{const h=this.schedule(()=>{if(u.timers.delete(h),!u.cancelled){d.status={state:"preparing",progress:l};try{u.listeners.forEach(_=>_(l))}catch(_){u.cancelled=!0;for(const g of u.timers)this.clearSchedule(g);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:_ instanceof Error?_.message:String(_)}),u.reject(_);return}if(this.diagnostic("prepare.progress",n,{phase:l.phase}),f===zi.length-1){if(d.operation=void 0,n==="prepare-fail"){d.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},u.reject(Ze("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",n,{code:"COMPANION_INTEGRITY_FAILED"});return}d.status={state:"ready",preparedAt:this.now()},u.resolve(this.getInfo(n)),this.diagnostic("prepare.ready",n)}}},f+1);u.timers.add(h)})}return c}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(Ze("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(C0,{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 Ze("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw Ze("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw Ze("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:_l[r],state:"running",controllerGeneration:1},s={snapshot:i,stdinClosed:!1,exited:!1,queuedOutput:[]};return this.sessions.set(r,s),this.diagnostic("session.launched",r,{capabilities:[...i.capabilities],sessionId:i.id}),i.capabilities.includes("stdio")&&this.schedule(()=>{this.queueOutput(s,"stdout",1,`fake:ready
|
|
220
|
-
`),this.queueOutput(s,"stderr",1,`fake:diagnostic
|
|
221
|
-
`)},20),r==="normal-exit"&&this.schedule(()=>this.requestExit(s,{reason:"exited",exitCode:0}),40),r==="crash"&&this.schedule(()=>this.requestExit(s,{reason:"crashed",exitCode:1}),40),r==="output-limit"&&this.schedule(()=>this.requestExit(s,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("stdio"))throw Ze("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw Ze("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 Ze("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw Ze("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
|
|
222
|
-
`);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw Ze("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw Ze("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 Ze("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(O0,{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(M0,{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 Ze("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw Ze("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!Tl.includes(t))throw Ze("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 eS=Object.freeze({[fo]:!0,[ho]:!0,[mo]:!0,[Eo]:!0,[go]:!0,[po]:!0,[To]:!0,[_o]:!0,[Ao]:!0,[Io]:!0,[bo]:!0,[yo]:!0,[ii]:!0,[ni]:!0,[si]:!0});function tS(e){return new J1(e)}function Ze(e,t){return Object.assign(new Error(t),{code:e})}const rS=/^[A-Za-z0-9_-]{22}$/,nS="https://api.xiaoheihe.cn/open_inapp/";function iS(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(!rS.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 sS(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`${nS}#${r}`}function oS(e={}){const t=e.source??fS(e.document??document),r=e.readMetadata??hS,n=e.createPreviewUrl??(d=>URL.createObjectURL(d)),i=e.revokePreviewUrl??(d=>URL.revokeObjectURL(d)),s=new WeakMap,o=new Set,c=d=>{if(!(!d||!o.has(d))){o.delete(d);try{i(d)}catch{}}},u=()=>{for(const d of[...o])c(d)};return e.signal?.addEventListener("abort",u,{once:!0}),{async pick(d,l){switch(xn(l.signal),e.getMode?.()??"normal"){case"cancel":throw ze("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");case"system-permission-denied":throw ze("MEDIA_SYSTEM_PERMISSION_DENIED","系统未授予相机或相册权限");case"prepare-failure":throw ze("MEDIA_PREPARE_FAILED","媒体准备失败,未保留部分结果");case"preview-unavailable":throw ze("MEDIA_PREVIEW_UNAVAILABLE","当前 Host 无法提供受控媒体预览")}const f=d.source==="camera"?[await t.capture({mediaType:d.mediaType})]:await aS(t,d);if(xn(l.signal),d.source==="camera"&&f.length!==1)throw ze("MEDIA_PREPARE_FAILED","相机模拟必须恰好返回 1 项");const h=[];try{for(const _ of f)xn(l.signal),h.push(await uS(_,d,l.signal,r,n,s,o));xn(l.signal)}catch(_){for(const g of h)c(s.get(g.file));throw _}return h},release(d){for(const l of d)c(s.get(l.file))}}}async function aS(e,t){const r=await e.pickAlbum({accept:cS(t.mediaType),maxCount:t.maxCount,multiple:t.maxCount>1});if(!r||r.length===0)throw ze("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");if(r.length>t.maxCount)throw ze("MEDIA_PREPARE_FAILED",`本次选择 ${r.length} 项,超过 maxCount ${t.maxCount}`);return r}function cS(e){switch(e){case"image":return"image/*";case"video":return"video/*";default:return"image/*,video/*"}}async function uS(e,t,r,n,i,s,o){const c=dS(e.type);if(!c)throw ze("MEDIA_PREPARE_FAILED",`浏览器未提供可识别的媒体类型: ${e.name}`);if(t.mediaType!=="all"&&t.mediaType!==c)throw ze("MEDIA_PREPARE_FAILED",`所选媒体 ${e.name} 与 mediaType 不匹配`);const u=await n(e);xn(r);const d=Al(u.width),l=Al(u.height);if(d===void 0||l===void 0)throw ze("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的显示尺寸`);if(c==="video"){if(Il(u.durationMs)===void 0)throw ze("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的视频时长`)}else if(u.durationMs!==void 0)throw ze("MEDIA_PREPARE_FAILED",`图片 ${e.name} 不应携带视频时长`);const f=i(e);if(!f)throw ze("MEDIA_PREVIEW_UNAVAILABLE","无法提供受控媒体预览");const h=lS(e);s.set(h,f),o.add(f);const _={type:c,mimeType:e.type,size:e.size,width:d,height:l,previewUrl:f,file:h};return c==="video"?{..._,durationMs:Il(u.durationMs)}:_}function dS(e){if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video"}function lS(e){const t=()=>Promise.reject(Object.assign(new Error("Browser Dev Host 媒体句柄只读"),{code:"FILE_ACCESS_DENIED"}));return{kind:"file",name:e.name,mode:"read",create:t,read:async()=>new Uint8Array(await e.arrayBuffer()),write:t,stat:async()=>({kind:"file",size:e.size,...e.lastModified?{modifiedAt:e.lastModified}:{}})}}function fS(e=document){return{pickAlbum(t){return new Promise(r=>{const n=e.createElement("input");n.type="file",n.accept=t.accept,n.multiple=t.multiple,n.style.display="none";let i=!1;const s=()=>{n.removeEventListener("change",c),n.removeEventListener("cancel",u),n.remove()},o=d=>{i||(i=!0,s(),r(d))},c=()=>o(n.files?Array.from(n.files):[]),u=()=>o(void 0);n.addEventListener("change",c),n.addEventListener("cancel",u),e.body.append(n),n.click()})},capture(t){return t.mediaType==="video"?TS():pS()}}}async function hS(e){return e.type.startsWith("video/")?ES(e):mS(e)}async function mS(e){if(typeof globalThis.createImageBitmap=="function"){const r=await globalThis.createImageBitmap(e),n={width:r.width,height:r.height};return r.close?.(),n}const t=URL.createObjectURL(e);try{const r=new Image;return await new Promise((n,i)=>{r.onload=()=>n(),r.onerror=()=>i(ze("MEDIA_PREPARE_FAILED","无法解码所选图片")),r.src=t}),{width:r.naturalWidth,height:r.naturalHeight}}finally{URL.revokeObjectURL(t)}}async function ES(e){const t=URL.createObjectURL(e),r=document.createElement("video");r.preload="metadata";try{await new Promise((i,s)=>{r.onloadedmetadata=()=>i(),r.onerror=()=>s(ze("MEDIA_PREPARE_FAILED","无法读取所选视频元数据")),r.src=t});let n=r.duration;return Number.isFinite(n)||(n=await gS(r)),{width:r.videoWidth,height:r.videoHeight,durationMs:Number.isFinite(n)?Math.max(0,Math.round(n*1e3)):0}}finally{r.removeAttribute("src"),URL.revokeObjectURL(t)}}function gS(e){return new Promise(t=>{const r=()=>{e.removeEventListener("durationchange",r),e.removeEventListener("timeupdate",r),t(e.duration)};e.addEventListener("durationchange",r),e.addEventListener("timeupdate",r),e.currentTime=1e101})}async function pS(){const e=document.createElement("canvas");e.width=640,e.height=480;const t=e.getContext("2d");if(!t)throw ze("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=t.createLinearGradient(0,0,e.width,e.height);r.addColorStop(0,"#2b2b3a"),r.addColorStop(1,"#0f7b6c"),t.fillStyle=r,t.fillRect(0,0,e.width,e.height),t.fillStyle="#ffffff",t.font="28px sans-serif",t.fillText("Browser Dev Host 模拟拍摄",40,e.height/2);const n=await new Promise(i=>e.toBlob(i,"image/png"));if(!n)throw ze("MEDIA_PREPARE_FAILED","无法生成测试图片");return new File([n],"browser-dev-camera.png",{type:"image/png"})}async function TS(){const e=document.createElement("canvas");e.width=320,e.height=240;const t=e.getContext("2d");if(!t)throw ze("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=e.captureStream?.bind(e),n=globalThis.MediaRecorder;if(!r||!n)throw ze("MEDIA_PREPARE_FAILED","当前浏览器不支持 MediaRecorder 视频模拟");const i=r.call(e,12),s=new n(i,{mimeType:_S(n)}),o=[],c=new Promise((l,f)=>{s.ondataavailable=h=>{h.data.size>0&&o.push(h.data)},s.onstop=()=>l(),s.onerror=()=>f(ze("MEDIA_PREPARE_FAILED","模拟拍摄录制失败"))});s.start();const u=Date.now();await AS(t,e,()=>Date.now()-u<900),s.stop(),await c;for(const l of i.getTracks())l.stop();const d=new Blob(o,{type:s.mimeType||"video/webm"});if(d.size===0)throw ze("MEDIA_PREPARE_FAILED","模拟拍摄未生成视频数据");return new File([d],"browser-dev-camera.webm",{type:d.type})}function _S(e){for(const t of["video/webm;codecs=vp8","video/webm","video/mp4"])if(e.isTypeSupported?.(t))return t;return"video/webm"}async function AS(e,t,r){for(;r();){const n=Math.min(1,Date.now()%900/900);e.fillStyle="#101820",e.fillRect(0,0,t.width,t.height),e.fillStyle=`rgb(${Math.round(40+n*180)}, 120, ${Math.round(200-n*120)})`,e.fillRect(0,t.height*(1-n),t.width,8),e.fillStyle="#ffffff",e.font="18px sans-serif",e.fillText("模拟拍摄中",24,t.height/2),await new Promise(i=>setTimeout(i,60))}}function xn(e){if(e.aborted){const t=new Error("Browser Dev Host 媒体选择已取消");throw t.name="AbortError",t}}function ze(e,t){const r=new Error(t);return r.name="BrowserDevMediaError",r.code=e,r}function Al(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:void 0}function Il(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function IS(e){const t=ot(e.runtimePermissions),r=Dc({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=ot(e.publishedRuntimePermissions),s=ot(r.runtimePermissions);for(const o of wc){const c=o.key,u={network:"Network",companion:"Companion",appProtocol:"AppProtocol"}[c]??o.name;if(!e.declaredPermissions?.[c]?.enabled)continue;const d=t.valid&&t.permissions[c]?.status==="enabled",l=r.temporaryPermissionKeys.some(f=>f===c);n.push({key:c,label:u,state:o.access==="declaration"?"declared":d?"approved":l?"temporary":"unavailable",facts:{platformApproval:o.access==="declaration"?null:d,temporary:l,effective:s.permissions[c]?.status==="enabled",online:i.valid?i.permissions[c]?.status??"missing":"unknown"},...l?{releaseDifference:"本次使用临时授权,发布后仍需平台批准。"}:i.valid&&!i.permissions[c]?{releaseDifference:"线上快照尚未包含该权限,需发布包含声明的新版本。"}:{},...c==="appProtocol"?{highestRisk:!0}:{},...o.access!=="declaration"&&!d&&!l?{reason:c==="appProtocol"?"最高危险权限:可执行任意协议并绕过其他 SDK 能力权限;当前没有有效临时授权,线上未批准":"没有有效的本地临时授权,线上未批准"}:{}})}if(e.declaredPermissions?.network?.useOfficialDomain){const o=t.valid&&t.permissions.network?.status==="enabled"&&t.permissions.network.config.useOfficialDomain===!0;n.push({key:"network.useOfficialDomain",label:"官方域名",state:o?"approved":"unavailable",...o?{}:{reason:"不支持本地临时授权,获得线上批准后才能使用"}})}return n}function yr(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 bl="__hb_sdk_mini_dev_console_installed__",bS=["log","debug","info","warn","error"];function yS(e,t=console){if(t[bl])return;let r=!1;for(const n of bS){const i=t[n];if(typeof i!="function")continue;const s=function(...o){try{e(n,o)}catch{}return i.apply(this,o)};try{t[n]=s,r=!0}catch{break}}r&&(t[bl]=!0)}const Wa=1,yl=64*1024,NS=64,wS=/^[A-Za-z0-9_-]{22}$/;class mt extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function DS(e,t=!1){const r=OS(e,t);switch($a(r,"Server message"),MS(r),r.type){case"grant":return Qn(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),qn(r.connectionEpoch,"connectionEpoch"),Nr(r.nextClientSequence,"nextClientSequence"),Nr(r.nextServerSequence,"nextServerSequence"),Nl(r.snapshot),r;case"event":return Qn(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),qn(r.connectionEpoch,"connectionEpoch"),Nr(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&lr("event must be account.changed or status.changed"),Nl(r.snapshot),r;case"heartbeat":return Qn(r,["version","type","connectionEpoch","sequence"],"heartbeat"),qn(r.connectionEpoch,"connectionEpoch"),Nr(r.sequence,"sequence"),r;default:return lr("Unknown server message type")}}function SS(e){const t=e.connectionEpoch;qn(t,"connectionEpoch"),Nr(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(qn(n.connectionEpoch,"connectionEpoch"),Nr(n.sequence,"sequence"),n.connectionEpoch!==t)throw new mt("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new mt("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new mt("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function OS(e,t){if(t)throw new mt("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new mt("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>yl)throw new mt("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>yl)throw new mt("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return CS(e),JSON.parse(e)}catch(r){throw r instanceof mt?r:new mt("INVALID_JSON","Channel frame must contain strict JSON")}}function Nl(e){$a(e,"snapshot"),Qn(e,["account","permissions"],"snapshot"),$a(e.account,"snapshot.account"),Qn(e.account,["revision"],"snapshot.account"),Nr(e.account.revision,"snapshot.account.revision"),b1(e.permissions)||lr("snapshot.permissions is invalid")}function MS(e){e.version!==Wa&&lr("version must be 1")}function $a(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&lr(`${t} must be a plain JSON object`)}function Qn(e,t,r,n=[]){const i=Object.keys(e);(t.some(s=>!Object.hasOwn(e,s))||i.some(s=>!t.includes(s)&&!n.includes(s)))&&lr(`${r} fields are invalid`)}function Nr(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&lr(`${t} must be a non-negative safe integer`)}function qn(e,t){(typeof e!="string"||!wS.test(e))&&lr(`${t} must be a 22-character base64url value`)}function lr(e){throw new mt("INVALID_MESSAGE",e)}function CS(e){new RS(e).scan()}class RS{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>=NS)throw new mt("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 mt("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 wl=[1e3,2e3,4e3,8e3,15e3];function LS(e){const t=new Set,r=e.webSocketFactory??(z=>new WebSocket(z)),n=e.randomValues??(z=>crypto.getRandomValues(z)),i=e.timers??{clearTimeout:z=>window.clearTimeout(z),setTimeout:(z,te)=>window.setTimeout(z,te)},s=e.onlineTarget??(typeof window>"u"?void 0:window),o=e.visibilityTarget??(typeof document>"u"?void 0:document),c=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let u,d,l,f=!1,h=0,_,g=!1,b=!1;const N=new Set,y=(z,te)=>{if(!(!e.onDiagnostic||N.has(z))){N.add(z);try{e.onDiagnostic({phase:z,...te?{code:te}:{}})}catch{}}},L=(z,te,x=!1)=>{if(l&&z.account.revision<l.account.revision)return;const Y=l&&JSON.stringify(z)===JSON.stringify(l);if(l=z,!(Y&&!x))for(const j of t)j(z,te)},A=()=>{if(f||_!==void 0||u)return;const z=wl[Math.min(h,wl.length-1)];h+=1,_=i.setTimeout(()=>{_=void 0,V()},z)},U=()=>{f||!g||u||(_!==void 0&&(i.clearTimeout(_),_=void 0),V())},Q=()=>{c()&&U()},C=()=>{o&&!o.hidden&&U()},P=()=>{b||(b=!0,s?.addEventListener("online",Q),o?.addEventListener("visibilitychange",C))},M=()=>{b&&(b=!1,s?.removeEventListener("online",Q),o?.removeEventListener("visibilitychange",C))},V=()=>{if(f||u)return;g=!0,P(),_!==void 0&&(i.clearTimeout(_),_=void 0);let z,te;try{z=r(e.url)}catch{y("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),A();return}try{te=vS(n)}catch{y("entropy","NONCE_GENERATION_FAILED");try{z?.close(1011,"channel initialization failed")}catch{}A();return}u=z;let x,Y,j;const H=()=>{z.removeEventListener("open",v),z.removeEventListener("message",R),z.removeEventListener("close",q),z.removeEventListener("error",D),d===H&&(d=void 0)},F=()=>{if(u===z){u=void 0,H();try{z.close(1008,"invalid channel state")}catch{}A()}},v=()=>{if(!(f||u!==z))try{z.send(JSON.stringify({version:Wa,type:"hello",csrfToken:e.csrfToken,clientNonce:te}))}catch{y("send","HELLO_SEND_FAILED"),F()}},R=W=>{if(f||u!==z)return;if(typeof W.data!="string"){y("parse","TEXT_FRAME_REQUIRED"),F();return}let $;try{$=DS(W.data)}catch(m){y("parse",m instanceof mt?m.code:"INVALID_MESSAGE"),F();return}if($.type==="grant"){if(j){y("sequence","DUPLICATE_GRANT"),F();return}x=$.connectionEpoch,Y=$.nextClientSequence,j=SS({connectionEpoch:x,nextSequence:$.nextServerSequence}),h=0,N.clear(),L($.snapshot,{type:"grant"});return}if(!j||!x||Y===void 0){y("sequence","MESSAGE_BEFORE_GRANT"),F();return}try{j.accept($)}catch{y("sequence","INVALID_SEQUENCE"),F();return}if($.type==="heartbeat"){try{z.send(JSON.stringify({version:Wa,type:"heartbeat.ack",connectionEpoch:x,sequence:Y}))}catch{y("send","HEARTBEAT_ACK_SEND_FAILED"),F()}Y=Y===Number.MAX_SAFE_INTEGER?void 0:Y+1;return}L($.snapshot,{type:"event",event:$.event},!0)},q=()=>{u===z&&(y("close","SOCKET_CLOSED"),u=void 0,H(),A())},D=()=>{y("open","SOCKET_ERROR"),F()};z.addEventListener("open",v),z.addEventListener("message",R),z.addEventListener("close",q),z.addEventListener("error",D),d=H};return{connect:V,subscribeUpdates(z){return t.add(z),()=>t.delete(z)},dispose(){if(f)return;f=!0,g=!1,M(),_!==void 0&&i.clearTimeout(_),_=void 0;const z=u;u=void 0,d?.(),z?.close(1e3,"client disposed"),t.clear()}}}function PS(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,s=e[n+1],o=e[n+2];r+=t[i>>2],r+=t[(i&3)<<4|(s??0)>>4],s!==void 0&&(r+=t[(s&15)<<2|(o??0)>>6]),o!==void 0&&(r+=t[o&63])}return r}function vS(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=PS(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let Le=!1,Tm=!1,et;const _m=new AbortController;try{yS((e,t)=>{wr(`console.${e}`,{source:"host",message:t.map(r=>ZS(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const kS="/__hb_sdk_bootstrap__",xS="/__hb_sdk__/mobile-launch-redirect",US="/__hb_sdk__/network",BS="/session/status",HS="/session/request",FS="/session/events",Dl=320,zS=1e3,jS=1e3,VS=15e3,Sl="dark",GS=["windows","macos","linux","unknown"],Am=new URL(location.href).searchParams,Im=Am.get("mini_url"),tt=Am.get("ui_preview")==="1",Be={get device(){return Vi("#device")},get mobileLanSelect(){return Vi("#mobile-lan-select")},get mobileQrImage(){return Vi("#mobile-qr-image")},get mobileQrStatus(){return Vi("#mobile-qr-status")}};if(!Im&&!tt)throw Be.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const bm=Im??"about:blank",ke=await tu(),$c=tt?void 0:await Dt.configure({csrfToken:ke.csrfToken??"",diagnosticsToken:ke.diagnosticsToken??"",signal:_m.signal,query:IO,onDropped:e=>{Z.diagnosticsDropped=e},onOwnershipLost:Om});Z.diagnosticTargetId=$c?.targetId??"";Z.diagnosticOwnerId=$c?.ownerId??"";Z.diagnosticTargetName=$c?.metadata.displayName??"";Z.openPlatformBaseUrl=ke.openPlatformBaseUrl;Z.devReadiness=ke.devReadiness;Z.miniProgramSupportsDesktop=ke.miniProgramSupportsDesktop;Z.miniProgramPlatforms=ke.devContext.platforms??[];Z.desktopLaunch.workspaceCardsEnabled=ke.workspaceCardsEnabled;Ll(ke.hostPlatform);Pl(ke.windowForm);let er=ke.lanAddresses,es=ke.defaultLanAddressId,Wr=ke.mobileLaunchRedirect,Kc=ke.nativeAppLaunchUnavailableReason,Wn=ke.devSessionId,Ka=ke.miniProgramManifestAccessToken,ts=ke.workspaceCardsEnabled,rs=ke,Zc=Fo(ke),Et=ke.devContext,Xr=ke.browserDevContext,$e=Yn(Xr);uo();let dn=Uo($e),Ho=0;const fr=new AbortController;let Xc=0,Ft,Za=0,Xa,Qt=0,zt=!1,oo,ns,Ja,Ea=!1;const ln=l0({apply:f0,waitForLayout:async e=>{await $n(),await Ul(e),await Bl(e)}});let Jc=!1;function ga(e){if(e.throwIfAborted(),Le)throw new Ar("SESSION_CLOSED","调试台已关闭");if(Z.diagnosticOwnershipLost)throw new Ar("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!Jc)throw new Ar("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(Zr)throw new Ar("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const ec=u0({observe:()=>{const e=mi()?{width:as.value.width,height:as.value.height}:{width:Na.value.screenWidth,height:Na.value.screenHeight};return{preset:Z.deviceSelectionId,orientation:mi()?e.width>=e.height?"landscape":"portrait":Z.display.orientation,runtimeStatus:Z.runtimeStatus,viewport:e,instanceId:et?.mounted?et.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:m0()}},async selectPreset(e,t){ga(t),Z.deviceSelectOpen=!1;const r=Z.previewMode,n=et;h0(e),await $n(),t.throwIfAborted(),Z.previewMode!==r&&await Ol(n,t)},async applyOrientation(e,t){ga(t),Z.deviceSelectOpen=!1,await ln.applyDisplay({mode:e,hideCapsule:Z.display.capsuleHidden},t)},async reload(e){ga(e),Z.deviceSelectOpen=!1;const t=et;dr("runtime.restart",{boundary:Xc+1}),kr("manual restart").catch(()=>{}),await Ol(t,e)},async waitForLayout(e){await $n(),e.throwIfAborted(),await Ul(e),await Bl(e)}}),is=A0(),ym={...ec.bridge,prepareCapture:is.prepare,restoreCapture:is.restore,cancel(e){ec.bridge.cancel(e),is.cancel(e)}};window.__HB_SDK_PREVIEW__=ym;async function Ol(e,t){for(;;){if(t.throwIfAborted(),Le)throw new Ar("SESSION_CLOSED","调试台已关闭");if(et!==e&&Ft===void 0){const r=Z.runtimeStatus;if(r==="ready"||tt&&r==="idle")return;if(r==="error")throw new Ar("RUNTIME_START_FAILED","小程序 Runtime 启动失败,请查看调试日志");if(r==="closed")throw new Ar("RUNTIME_CLOSED","预览窗口已关闭或最小化,请先恢复窗口")}await new Promise((r,n)=>{const i=()=>{clearTimeout(s),n(t.reason)},s=setTimeout(()=>{t.removeEventListener("abort",i),r()},20);t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}}let tc,rc,nc,ic,sc,oc,Ml=Date.now(),Zr=!1,Cl=Promise.resolve(),Jr=-1,hi=!1,$t,ac,cc,ss,_r;const ao=new Set,Rl="hb-sdk:browser-dev-host:user-data-device";function YS(){try{const e=localStorage.getItem(Rl)?.trim();if(e)return e;const t=typeof crypto.randomUUID=="function"?crypto.randomUUID():`mock-${Date.now().toString(36)}`;return localStorage.setItem(Rl,t),t}catch{return"browser-mock-device"}}const QS=YS();function qS(){return{miniProgramId:Et.miniProgramId?.trim().toLowerCase()||"anonymous-mini-program",userId:$t?.trim()||"anonymous-user",deviceId:QS,environment:"development"}}function Nm(){return mm($e.runtimePermissions,dn,$e)}function WS(){const e=ot(Nm());return e.valid&&e.permissions.network?.status==="enabled"?"upload":"no_network"}function $S(){return Q1({declaredPermissions:$e.declaredPermissions,runtimePermissions:Nm()})}const jt=G1({resolveScope:qS,egressTier:WS,declared:$S});function fn(){Tm&&d0({...jt.snapshot(),targetId:Z.diagnosticTargetId,instanceId:et?.instanceId})}jt.subscribe(fn);Tm=!0;fn();function pa(){const e=jt.snapshot().stateError;if(e)throw new Error(e)}Zm({async refresh(){await jt.refresh(),pa()},async revokeSession(){await jt.revokeSession(),pa()},async resetAll(){await jt.resetAll(),pa()}});const uc=tS({onDiagnostic:({action:e,alias:t,detail:r})=>dr(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),hn=S1({applyStatus:e=>Pm(e,!0),fetchStatus:e=>Lm(iu(fr.signal,e)),getCanonicalRevision:()=>Jr,onError:yO,reconcile:()=>sO(Ho)}),dc=O1({connectEvents:vm,invalidate:()=>hn.invalidate(),isDisposed:()=>Le,maxDelayMs:VS,minDelayMs:jS,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let Ta=0,ji="",_a=!1,lc,fc;function wm(){tt||Le||Z.diagnosticOwnershipLost||Dt.poll().finally(()=>{!Le&&!Z.diagnosticOwnershipLost&&(fc=window.setTimeout(wm,1e3))})}wm();await co(!1);Um();Hm(Bm(ke));tt&&XS();Ei();tt||await Sm();KS();Dm();dO();await kr("initial");tt||(vm(),nO());Jc=!0;function Dm(){!tt&&!Le&&(lc=window.setTimeout(()=>{Sm().finally(Dm)},1e3))}async function Sm(){if(!(_a||Le)){_a=!0;try{const e=await fetch(`${au}?after=${Ta}&limit=500`,{headers:{"x-hb-sdk-csrf":ke.csrfToken??""},signal:AbortSignal.any([fr.signal,AbortSignal.timeout(5e3)])});if(!e.ok){Z.diagnosticsStale=!0;return}const t=await e.json();if(Le)return;if(ji&&t.epoch!==ji){Ta=0,ji=t.epoch,Xm();return}ji=t.epoch,Z.uploadSessions=t.uploadSessions;const r=await fetch(`${au}?mode=inspect`,{headers:{"x-hb-sdk-csrf":ke.csrfToken??""},signal:AbortSignal.any([fr.signal,AbortSignal.timeout(5e3)])});if(r.ok){const s=await r.json();Z.diagnosticInstances=s.instances,Z.diagnosticTargets=s.targets,Z.diagnosticPrimaryTargetId=s.primaryTargetId;const o=s.targets.find(c=>c.targetId===Z.diagnosticTargetId);o&&(Z.diagnosticTargetName=o.metadata.displayName),o&&(o.state==="closed"||o.ownerId!==Z.diagnosticOwnerId)&&Om()}Z.diagnosticsStale=!r.ok,Z.diagnosticsGap=Z.diagnosticsGap||t.gap===!0;const n=new Map(Z.diagnosticTargets.map(s=>[s.targetId,s.metadata.displayName])),i=new Map(Z.diagnosticInstances.map(s=>[s.instanceId,n.get(s.targetId)]));for(const s of t.items){const o=Jm(s);o&&(o.targetName=n.get(s.targetId)??i.get(s.instanceId),o.uploadSessionId=s.uploadSessionId,o.uploadSessionName=t.uploadSessions.find(c=>c.id===s.uploadSessionId)?.name,o.dedupeKey=void 0,e0(o,s.cursor))}Ta=t.nextCursor}catch{Z.diagnosticsStale=!0}finally{_a=!1}}}function KS(){window.addEventListener("beforeunload",NO),window.addEventListener("hb-sdk:refresh-storage",Ei),window.addEventListener("hb-sdk:qr-open-change",hc),window.addEventListener("hb-sdk:qr-refresh",eu),$n(()=>{Z.qrOpen&&Z.qrMode==="local"&&hc(new CustomEvent("hb-sdk:qr-open-change",{detail:{open:!0}}))}),tc=t0(()=>document.querySelector("#host-fullscreen-exit-mount")),rc=An(()=>[Kn.value,Ia.value,Gi.value?.state,Gi.value?.stale,Gi.value?.capabilities.storage].join("|"),()=>{Z.storage=[],Z.storageError="",Ei()}),nc=An(()=>Z.devicePresetId,()=>ln.notifyViewportChange(),{flush:"post"}),ic=An(()=>Z.previewMode,()=>{Kt("preview mode changed"),vl(!1),r0(!1),mn("preview mode changed")},{flush:"sync"}),sc=An(()=>as.value,()=>ln.notifyViewportChange(),{flush:"post"}),oc=An(()=>Z.desktopWindow.closed,(e,t)=>{if(mi()){if(e){Kt("desktop window closed"),Z.runtimeStatus="closed";return}t&&Z.runtimeStatus==="closed"&&mn("desktop window reopened")}},{flush:"sync"})}function ZS(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
|
|
223
|
-
`).slice(0,4).join(`
|
|
224
|
-
`):"")||`${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 hc(e){const t=e.detail?.open===!0;t!==zt&&(zt=t,Qt+=1,zo(),oo?.abort(),t&&(Be.mobileLanSelect.addEventListener("change",eu),km(),wi()))}function eu(){zt&&wi()}function mn(e){Le||Ft!==void 0||(dr("runtime.restart",{boundary:Xc+1}),Ft=window.setTimeout(()=>{Ft=void 0,Le||kr(e)},0))}async function kr(e,t=bm,r){if(Le||Zr||Z.diagnosticOwnershipLost)return;if(Ft!==void 0&&window.clearTimeout(Ft),Ft=void 0,Kt(e),mi()&&Z.desktopWindow.closed){Z.runtimeStatus="closed";return}const n=document.createElement("iframe");n.dataset.testid="device-iframe",n.title="小程序预览",n.allow="clipboard-read; clipboard-write",n.name="__hb_sdk_mini_dev__";const i=crypto.randomUUID(),s=n0(i,u=>{tt||Dt.event(i,u)}),o={instanceId:i,launchUrl:t,locationBasePath:r,interactions:s,sequence:++Xc,state:"starting",iframe:n,terminal:new AbortController,permissions:Vm(dn),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(o.iframe.dataset.hbSdkInstanceId=o.instanceId,et=o,Z.runtimeStatus="loading",Cm(),tt||Dt.send({operation:"register",instanceId:o.instanceId}),await $n(),!Xe(o))return;const c=Gm("#device");if(!c){Aa(o,new Error("预览容器尚未挂载"));return}if(tt){c.innerHTML='<div class="browser-mock-preview"><span class="browser-mock-preview__icon">UI</span><strong>Browser Mock</strong><small>mp_preview</small></div>',Z.runtimeStatus="idle";return}c.replaceChildren(o.iframe),o.mounted=!0,Dt.send({operation:"activate",instanceId:o.instanceId});try{const u=await f1(JS(o));if(!Xe(o)){u.dispose();return}o.assembly=u,u.ports.companion=uc.port,u.ports.media=oS({getMode:()=>Z.mediaSimulation,signal:o.terminal.signal});const d=T1({signal:o.terminal.signal,csrfToken:()=>ke.csrfToken??""}),l=WD({iframe:o.iframe,authorizationContext:A1({signal:o.terminal.signal,refreshAccount:f=>co(!0,f),request:Rm,readState:()=>({signed:Et,browser:$e,userId:$t,accountRevision:Jr,networkEnabled:o.permissions.networkRequest.status==="enabled"})}),ports:{...u.ports,...d},environment:u.environment,hostCapabilities:{...u.hostCapabilities,"media.pick":!0,...d?{"gameSaves.getFile":!0,"user.data.file":!0,"file.readBytes":!0,"file.readText":!0,"file.stat":!0,"file.exists":!0}:{},...eS},authPresentation:u.authPresentation,userDataPresentation:u.userDataPresentation,companionPresentation:uc.presentation,resolveLaunchConfiguration:async()=>(await u.resolveLaunch()).configuration,dispose:()=>mc(o),onDevDocumentReload:(f,h)=>{Xe(o)&&kr("development document reloaded",f,h)},onDevUploadSession:f=>{Xe(o)&&(o.uploadSessionId=f,En(o,{uploadSessionId:f}))},onReady:()=>{Xe(o)&&(o.state="ready",o.hadReady=!0,gc.value=d?l.diagnostics.gameSaves:void 0,Z.runtimeStatus="ready",En(o),wr("runtime.ready",{generation:o.sequence},Date.now(),void 0,o.instanceId))},onUserDataTelemetry:f=>{jt.refresh();const h=$1(f);wr(h.method,h.detail,Date.now(),"info",o.instanceId)},onTrace:f=>rO(o,f),onError:f=>{Xe(o)&&Aa(o,f)},onCapabilityTrace:f=>{wr(f.method,{...f,source:"host"},f.timestamp,void 0,o.instanceId),Xe(o)&&f.method==="storage.setStorage"&&f.outcome==="success"&&Ei()}});o.runtime=l,await l.start(),Xe(o)&&jt.bind(l.getDataPermissionBridge())}catch(u){if(!Xe(o))return;Aa(o,u),wr("runtime.start.failed",Fm(u,o),Date.now(),"error",o.instanceId),o.terminal.abort(u),o.runtime?.destroy(),o.iframe.remove(),mc(o)}}function Om(){Le||Z.diagnosticOwnershipLost||(Z.diagnosticOwnershipLost=!0,Kt("预览页面授权已失效"),Z.runtimeStatus="closed",Jc=!1)}function Xe(e){return et===e&&!Le&&!e.terminal.signal.aborted&&e.state!=="closed"&&e.state!=="failed"}function En(e,t={}){Dt.send({operation:"update",instanceId:e.instanceId,state:e.state,...t})}function Mm(e,t){e.mounted&&(e.mounted=!1,Dt.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function mc(e){et===e&&(gc.value=void 0),e.interactions.dispose();const t=e.assembly;e.assembly=void 0,t?.dispose()}function Aa(e,t){e.state==="failed"||e.state==="closed"||(e.state="failed",e.interactions.dispose(),En(e,{error:Fm(t,e),...e.uploadSessionId?{uploadSessionId:e.uploadSessionId}:{}}),Mm(e,"Runtime failed"),et===e&&(Z.runtimeStatus="error"))}function Kt(e){const t=et;t&&(et=void 0,gc.value=void 0,jt.clearSession(),t.state!=="failed"&&(t.state="closed",En(t,{reason:e})),Mm(t,e),(!Kn.value||Kn.value===Z.diagnosticTargetId)&&(Za+=1,Xa?.abort()),i0(),uc.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),mc(t),ln.reset())}function XS(){const e=g0();Z.diagnosticTargetId=e.targetId,Z.diagnosticOwnerId=e.ownerId,Z.diagnosticPrimaryTargetId=e.targetId,Z.diagnosticTargetName=e.metadata.displayName,Z.diagnosticTargets=[e],Z.diagnosticInstances=[{instanceId:e.currentInstanceId,targetId:e.targetId,ownerId:e.ownerId,adapterId:e.adapterId,kind:"browser",capabilities:e.capabilities,state:"ready",startedAt:Date.now(),updatedAt:Date.now(),startCursor:0,lastCursor:0,stale:!1}];const t={...e,targetId:"ui-preview-phone",ownerId:"ui-preview-phone-owner",kind:"mobile",currentInstanceId:"ui-preview-phone-instance",metadata:{displayName:"小黑盒",deviceModel:"iPhone 16 Pro",os:"iOS"}};Z.diagnosticTargets.push(t),Z.diagnosticInstances.push({...Z.diagnosticInstances[0],instanceId:t.currentInstanceId,targetId:t.targetId,ownerId:t.ownerId,kind:"mobile"}),ba({...ya("console.error",{source:"app",message:"真机示例:请求超时"},Date.now(),"error"),targetId:t.targetId,instanceId:t.currentInstanceId}),dr("runtime.ready",{generation:1}),ba(ya("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info")),dr("user.getInfo",{durationMs:34,outcome:"success"}),dr("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function JS(e){const t=e.terminal.signal,r=$e,n=Wn,i=mm(r.runtimePermissions,e.permissions,r),s=mi();return{signal:t,account:{async getCurrentUserId(){return(await co(!1,t)).user_id},async ensureAuthenticated({signal:o}){await co(!1,o)},onChange(o){return ao.add(o),()=>ao.delete(o)}},authenticatedRequest:Rm,storage:{area:"local",storage:Y1(localStorage)},presentation:X1({close:async()=>{Xe(e)&&(Kt("mini program closed"),Cm(),Z.runtimeStatus="closed",s&&vl(!0))},reload:()=>{Xe(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:o=>{Xe(e)&&kl(o)},...s?{getViewportMetrics:()=>{const o=as.value;return{windowWidth:o.width,windowHeight:o.height,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio,safeArea:{left:0,right:o.width,top:0,bottom:o.height}}},getNavigationBarHeight:()=>E0}:{getDeviceMetrics:()=>Na.value,applyDisplay:(o,c)=>ln.applyDisplay(o,c),isCapsuleHidden:()=>Z.display.capsuleHidden},onViewportChange:o=>ln.onViewportChange(o)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:o=>{document.title=o}},resolveLaunch:async()=>({configuration:U1({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,firstParty:r.source==="remote"&&r.firstParty===!0,...Z.miniProgram.bound&&Z.miniProgram.name.trim()?{miniProgramName:Z.miniProgram.name}:{},...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:s?Z.hostPlatform:s0.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:o=>x1(o),confirmFollowAuthor:o=>M1(o)},userDataPresentation:{confirmDataPermission:z1},protocol:eO(e)}}function mi(){return Z.previewMode==="desktop"}function eO(e){return{async invoke(t){wr("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:tO(t)},Date.now(),void 0,e.instanceId)}}}function tO(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 lt(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function Cm(){document.documentElement.dataset.navigationBarStyle=Sl,kl(Sl)}function rO(e,t){Xe(e)&&t.type==="document_validation"&&typeof t.documentVerifying=="boolean"&&En(e,{documentVerifying:t.documentVerifying}),Le||Dt.event(e.instanceId,{source:"runtime",level:t.type==="error"||t.type==="security_violation"?"error":"info",timestamp:t.timestamp,phase:t.type,method:t.method??`runtime.${t.type}`,message:JSON.stringify(o0({...t,generation:e.sequence})),...t.errorCode?{errorCode:t.errorCode}:{}}),e.runtimeId!==t.runtimeId&&(e.runtimeId=t.runtimeId,En(e,{runtimeId:t.runtimeId})),Xe(e)&&e.pendingNavigationReload&&t.type==="bridge_response"&&t.method==="navigation.reload"&&t.outcome==="success"&&(e.pendingNavigationReload=!1,mn("navigation.reload"))}async function Rm(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 ru(n?US:HS,{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,security:e.source==="runtime-private"?e.security:void 0,bodyEncoding:e.bodyEncoding,timeout:e.timeout}),signal:t.signal});!n&&i.status===401&&hn.invalidate();const s=await i.json();if(!i.ok)throw s;return s}async function co(e,t){const r=Ho,n=await Lm(iu(fr.signal,t));return zm(r)?Pm(n,e).status:Ec()}async function Lm(e){return await(await fetch(BS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Pm(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Jr)return{changed:!1,status:Ec()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?je(e.nickname):void 0,i=e.authenticated?je(e.avatar):void 0,s=e.revision!==Jr||e.authenticated!==hi||r!==$t||n!==ac||i!==cc;return Jr=e.revision,hi=e.authenticated,$t=r,ac=n,cc=i,Um(),fn(),t&&s&&ao.forEach(o=>o($t)),{changed:s,status:Ec()}}function Ec(){return{authenticated:hi,revision:Jr,...hi&&$t?{user_id:$t}:{}}}function nO(){if(!(!ke.csrfToken||Le))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",_r=LS({csrfToken:ke.csrfToken,onDiagnostic:t=>dr("channel.diagnostic",t),url:e.toString()}),_r.subscribeUpdates((t,r)=>iO(t,r)),_r.connect()}catch{_r?.dispose(),_r=void 0}}function iO(e,t){hn.invalidate(e.account.revision),SO(dn,e.permissions)?t.type==="event"&&t.event==="status.changed"&&kr("status changed"):(dn=Vm(e.permissions),oO())}function vm(){if(ss?.close(),ss=void 0,!$t||Le)return;const e=new EventSource(FS);ss=e,e.addEventListener("account-invalidated",()=>{hn.invalidate()}),e.addEventListener("account-revision",()=>{hn.invalidate()}),e.onopen=()=>{dc.reset()},e.onerror=()=>{e.close(),dc.schedule()}}async function sO(e){zm(e)&&await kr("account revision changed")}async function oO(){Le||(await kr("permission changed"),!Le&&await wi())}async function tu(e){const t=await fetch(kS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:iu(AbortSignal.timeout(5e3),e)});if(!t.ok)throw new Error("Browser Dev Host bootstrap request failed");const r=await t.json();if(!lt(r))throw new Error("Browser Dev Host bootstrap is invalid");const n=jm(r.mobileLaunchRedirect);if(Object.hasOwn(r,"mobileLaunchRedirect")&&r.mobileLaunchRedirect!==void 0&&!n)throw new gn;return{openPlatformBaseUrl:typeof r.openPlatformBaseUrl=="string"?r.openPlatformBaseUrl:void 0,devReadiness:uO(r.devReadiness),csrfToken:typeof r.csrfToken=="string"?r.csrfToken:void 0,diagnosticsToken:typeof r.diagnosticsToken=="string"?r.diagnosticsToken:void 0,defaultLanAddressId:typeof r.defaultLanAddressId=="string"?r.defaultLanAddressId:void 0,devSessionId:typeof r.devSessionId=="string"&&/^[a-f0-9]{32}$/.test(r.devSessionId)?r.devSessionId:void 0,devContext:hl(r.devContext,r.runtimePermissions),browserDevContext:hl(r.browserDevContext??r.devContext,r.runtimePermissions),lanAddresses:Array.isArray(r.lanAddresses)?r.lanAddresses.filter(DO):[],loginAvailable:r.loginAvailable===!0,miniProgram:_O(r.miniProgram),miniProgramSupportsDesktop:r.miniProgramSupportsDesktop===!0,workspaceCardsEnabled:r.workspaceCardsEnabled===!0,mobileLaunchRedirect:n,nativeAppLaunchUnavailableReason:typeof r.nativeAppLaunchUnavailableReason=="string"?r.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof r.miniProgramManifestAccessToken=="string"?r.miniProgramManifestAccessToken:void 0,windowForm:cO(r.windowForm),hostPlatform:aO(r.hostPlatform)}}function aO(e){return GS.includes(e)?e:"unknown"}function cO(e){if(!lt(e))return;const t=o=>typeof o=="number"&&Number.isFinite(o)&&o>0?o:void 0,r=t(e.defaultWidth),n=t(e.defaultHeight),i=t(e.minWidth),s=t(e.minHeight);return{...r===void 0?{}:{defaultWidth:r},...n===void 0?{}:{defaultHeight:n},...i===void 0?{}:{minWidth:i},...s===void 0?{}:{minHeight:s},...typeof e.resizable=="boolean"?{resizable:e.resizable}:{}}}function uO(e){if(!lt(e))return;const t=o=>{if(!(!lt(o)||!["ready","pending","blocked","not-configured"].includes(String(o.state))))return{state:o.state,...typeof o.reason=="string"?{reason:o.reason.slice(0,240)}:{}}},r=t(e.browser),n=t(e.mobile),i=t(e.companion);if(!r||!n||!i||!lt(e.companion))return;const s=e.companion;return{browser:r,mobile:n,companion:{...i,...typeof s.digest=="string"&&/^[a-f0-9]{64}$/.test(s.digest)?{digest:s.digest}:{},artifacts:Array.isArray(s.artifacts)?s.artifacts.filter(o=>lt(o)&&typeof o.alias=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(o.alias)&&["windows-x64","macos-arm64"].includes(String(o.target))).map(({alias:o,target:c})=>({alias:o,target:c})):[]}}}async function ru(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),ke.csrfToken&&r.set("x-hb-sdk-csrf",ke.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function dO(){nu(),tt||(Ja=window.setInterval(()=>{TO()},zS))}function km(e=Be.mobileLanSelect.options.length>0?Be.mobileLanSelect.value:void 0){Be.mobileLanSelect.replaceChildren();for(const t of er){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,Be.mobileLanSelect.appendChild(r)}e&&er.some(({id:t})=>t===e)?Be.mobileLanSelect.value=e:es&&er.some(({id:t})=>t===es)?Be.mobileLanSelect.value=es:er[0]&&(Be.mobileLanSelect.value=er[0].id),Be.mobileLanSelect.disabled=er.length===0}async function wi(){if(Le||!zt)return;const e=++Qt;if(oo?.abort(),Be.mobileQrImage.removeAttribute("src"),Z.mobileQr={status:"loading",expiresAt:0},zo(),tt){const i=await cu.toDataURL("hb-sdk-ui-preview",{width:Dl,margin:1});if(e!==Qt||Le||!zt)return;Be.mobileQrImage.src=i,Z.mobileQr={status:"ready",expiresAt:0},Be.mobileQrStatus.textContent="UI 预览示例,不用于真机连接";return}if(Et.source!=="remote"||!Et.localDevLaunchToken||Et.expiresAt!==void 0&&Et.expiresAt<=Date.now()){Be.mobileQrImage.removeAttribute("src"),Z.mobileQr.status="error",Be.mobileQrStatus.textContent=Kc||"需要有效的本地调试启动票";return}const t=wO();if(!t?.mobileAppQrPayload){Be.mobileQrImage.removeAttribute("src"),Z.mobileQr.status="error",Be.mobileQrStatus.textContent="未发现可用的局域网地址";return}const r=new AbortController;oo=r;const n=AbortSignal.any([r.signal,fr.signal,AbortSignal.timeout(1e4)]);Be.mobileQrStatus.textContent="正在生成二维码...";try{const i=await EO(t,n);if(e!==Qt||Le)return;const s=await lO(i.address,i.expiresAt,n);if(e!==Qt||Le)return;const o=await cu.toDataURL(s.payload,{width:Dl,margin:1});if(e!==Qt||Le)return;if(n.throwIfAborted(),s.expiresAt<=Date.now())throw new Error("二维码已过期,请刷新重试");Be.mobileQrImage.src=o,Z.mobileQr={status:"ready",expiresAt:s.expiresAt},Be.mobileQrStatus.textContent=`${i.address.name} · ${i.address.address}`,pO(s.expiresAt,e)}catch(i){if(e!==Qt||Le)return;if(i instanceof gn){os();return}Be.mobileQrImage.removeAttribute("src"),Z.mobileQr.status="error",Be.mobileQrStatus.textContent=n.aborted&&n.reason?.name==="TimeoutError"?"二维码生成超时,请检查连接后刷新重试":su(i)}}async function lO(e,t,r){const n=e.mobileAppQrPayload;if(!n)throw new Error("Mobile 启动配置不可用");const i=await fO(e,n,r);if(!i)return{expiresAt:t,payload:n};try{return{expiresAt:Math.min(t,i.expiresAt),payload:sS(iS({host:e.address,port:location.port,token:i.token}))}}catch{throw new gn}}async function fO(e,t,r){if(Wr?.addressId===e.id)return Wr;if(!Wr)return;const n=await ru(xS,{signal:r,method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:Wr.token})});if(!n.ok)throw new gn;const i=await n.json(),s=lt(i)?jm({addressId:i.address_id,expiresAt:i.expires_at,token:i.token}):void 0;if(!s||s.addressId!==e.id)throw new gn;return r.throwIfAborted(),Wr=s,rs={...rs,mobileLaunchRedirect:s},Zc=Fo(rs),s}async function hO(e,t){const r=await tu(t);t.throwIfAborted();const n=mO(r,e),i=n?.mobileAppQrPayload;if(!n||!i)throw new Error("Mobile 启动配置不可用");return xm(r),{...n,mobileAppQrPayload:i}}function mO(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function xm(e){const t=yr($e);Z.devReadiness=e.devReadiness,Z.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,Z.miniProgramPlatforms=e.devContext.platforms??[],Ll(e.hostPlatform),Pl(e.windowForm),ts=e.workspaceCardsEnabled,rs=e,Zc=Fo(e),Et=e.devContext,Xr=e.browserDevContext,$e=Yn(Xr),dn=Uo($e),uo(),er=e.lanAddresses,es=e.defaultLanAddressId,Wr=e.mobileLaunchRedirect,Kc=e.nativeAppLaunchUnavailableReason,Wn=e.devSessionId,Ka=e.miniProgramManifestAccessToken,Hm(Bm(e)),zt&&km(),nu(),t!==yr($e)&&(Kt("local permission context changed"),mn("local permission context changed"))}function uo(){if(tt){Z.localPermissions=p0(),Z.devContextWarning="";return}Z.localPermissions=IS($e),Z.devContextWarning=$e.source==="anonymous"?"未连接线上上下文":$e.warning?"本地上下文受限,请检查 CLI 状态":"",fn()}function nu(){let e;try{e=a0(bm)}catch{}const t=Et.miniProgramId?.trim().toLowerCase();let r=Kc?.trim()??"";!r&&(Et.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!Et.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&ts&&!Wn&&(r="本地调试会话尚未就绪"),!r&&Et.expiresAt!==void 0&&Et.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),xl({...e?{address:e}:{},...t?{miniProgramId:t}:{},...ts&&Wn?{devSessionId:Wn}:{},...Ka?{miniProgramManifestToken:Ka}:{},workspaceCardsEnabled:ts,ready:r==="",...r?{unavailableReason:r}:{}})}class gn extends Error{}async function EO(e,t){const r=Cl.then(()=>(t.throwIfAborted(),gO(e,t)));return Cl=r.then(()=>{},()=>{}),r}async function gO(e,t){const r=new URL(e.appUrl),n=new URL(I1,location.origin),i=await ru(n.pathname,{signal:t,method:"POST",body:JSON.stringify({mini_url_origin:r.origin,runtime_permissions:N1(Et)})}),s=await i.json();if(!i.ok||!lt(s)||typeof s.token!="string"||typeof s.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await hO(e.id,t),expiresAt:s.expires_at}}function pO(e,t){ns=window.setTimeout(()=>{!Le&&zt&&t===Qt&&wi()},Math.max(1e3,e-Date.now()-3e4))}async function TO(){if(!(Ea||Le)){Ea=!0;try{const e=await tu();Ml=Date.now();const t=Zr;Zr=!1;const r=Fo(e);if(!t&&r===Zc&&yr(Yn(e.browserDevContext))===yr($e)){Xr=e.browserDevContext,$e=Yn(Xr),uo();return}xm(e),t&&mn("CLI dev session reconnected"),zt&&wi()}catch(e){e instanceof gn&&os();const t=Yn(Xr);yr(t)!==yr($e)&&($e=t,dn=Uo($e),uo(),Kt("local permission context expired"),mn("local permission context expired"),nu(),zt&&os()),Date.now()-Ml>=3e4&&!Zr&&(Zr=!0,Kt("CLI dev session disconnected"),Gm("#device")?.replaceChildren(),Z.runtimeStatus="closed",Z.localPermissions=[],Z.devContextWarning="调试会话已断开",xl({ready:!1,unavailableReason:"调试会话已断开"}),Z.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},zt&&os())}finally{Ea=!1}}}function os(){Qt+=1,oo?.abort(),zo(),Be.mobileQrImage.removeAttribute("src"),Z.mobileQr={status:"error",expiresAt:0},Be.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Fo(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:{platforms:e.devContext.platforms,permissionContext:yr(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,hostPlatform:e.hostPlatform,windowForm:e.windowForm})}function Um(){if(!hi){Z.account={authenticated:!1,avatar:"",nickname:"未登录"};return}Z.account={authenticated:!0,avatar:cc??"",nickname:ac||$t||"已登录"}}function Bm(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Hm(e){if(!!!e?.miniProgramId||!e){Z.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试",description:"",version:""},fn();return}Z.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · "),description:e.description??"",version:e.version??""},fn()}function _O(e){if(e===null)return null;if(!lt(e))return;const t=je(e.miniProgramId)??je(e.mini_program_id);if(t)return{miniProgramId:t,...je(e.description)?{description:je(e.description)}:{},...je(e.name)?{name:je(e.name)}:{},...je(e.iconUrl)??je(e.icon_url)?{iconUrl:je(e.iconUrl)??je(e.icon_url)}:{},...je(e.status)?{status:je(e.status)}:{},...je(e.version)?{version:je(e.version)}:{},...je(e.developerName)??je(e.developer_name)?{developerName:je(e.developerName)??je(e.developer_name)}:{}}}function je(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function Ei(){const e=++Za;Xa?.abort();const t=new AbortController;Xa=t;const r=Kn.value,n=!r||r===Z.diagnosticTargetId,i=Gi.value,s=Ia.value||(n?et?.instanceId:void 0),o=()=>!Le&&e===Za&&r===Kn.value&&s===(Ia.value||(n?et?.instanceId:void 0));if(!n&&(!i||!s||i.stale||i.state!=="attached"||!i.capabilities.storage)){Z.storage=[],Z.storageError=!i||!i.capabilities.storage?"当前设备不支持存储诊断":"当前设备未连接或没有运行实例";return}if(tt){Z.storage=[{area:"local",key:"preferences",serializedValue:'{"theme":"light","language":"zh-CN"}',bytes:36},{area:"local",key:n?"lastOpenedProject":"deviceModel",serializedValue:n?'"demo-project"':'"iPhone 16 Pro"',bytes:n?14:15}],Z.storageError="";return}if(!s){Z.storage=[],Z.storageError="";return}try{const c=await c0({instanceId:s,resource:"storage"},{csrfToken:ke.csrfToken,signal:AbortSignal.any([t.signal,fr.signal])});if(!o())return;if(c.code)throw new Error(c.error??"Storage 诊断查询失败");Z.storage=c.value,Z.storageError=""}catch(c){if(!o())return;Z.storage=[],Z.storageError=su(c)}}function Fm(e,t=et){const r=(u,d)=>{if(!(!u||typeof u!="object"))try{return Object.getOwnPropertyDescriptor(u,d)?.value}catch{return}},n=(u,d)=>{const l=r(u,d);return typeof l=="string"?l.slice(0,8192):void 0},i=r(e,"cause"),s=n(e,"stack")??n(i,"stack"),o=n(e,"name")??n(i,"name"),c=typeof i=="string"?i:[n(i,"name"),n(i,"message")].filter(Boolean).join(": ");return{code:n(e,"code")??"RUNTIME_START_FAILED",message:n(e,"message")??(typeof e=="string"?e:"Runtime 启动失败"),phase:t?.hadReady?"running":"starting",...o?{name:o}:{},...s?{stack:s}:{},...c?{cause:c}:{}}}function wr(e,t,r=Date.now(),n,i){AO(ya(e,t,r,n==="debug"?"log":n),i)}function AO(e,t){if(Le)return;if(tt){ba({...e,targetId:Z.diagnosticTargetId});return}const r=lt(e.detail)?e.detail:{};Dt.event(t,{source:t&&e.source==="runtime"?"runtime":"host",level:e.level,timestamp:e.timestamp,message:e.summary,method:e.method,...typeof r.phase=="string"?{phase:r.phase}:{},...e.callId?{callId:e.callId}:{},...e.outcome?{outcome:e.outcome}:typeof r.outcome=="string"?{outcome:r.outcome}:{},...e.durationMs===void 0?{}:{durationMs:e.durationMs},...typeof r.startedAt=="number"?{startedAt:r.startedAt}:{},...e.errorCode?{errorCode:e.errorCode}:{},...lt(r.network)?{network:r.network}:{}})}async function IO(e){const t=et;if(!t||e.instanceId!==t.instanceId||!Xe(t)||!t.runtime)return{code:"closed",error:"该实例已结束"};if(Date.now()>=e.deadline)return{code:"timeout",error:"查询已超过期限"};if(e.resource==="presentation")return{value:t.interactions.snapshot()};if(e.resource==="sandbox")return{code:"unsupported",error:"Browser Dev Host 不提供文件系统能力"};const r=t.runtime,n=r.diagnostics.storage;if(!n)return{code:"unsupported",error:"当前 Host 不支持 Storage 诊断"};const i=AbortSignal.any([fr.signal,t.terminal.signal,AbortSignal.timeout(Math.max(1,e.deadline-Date.now()))]);let s,o;try{o=await Promise.race([n.getSnapshot(),new Promise((c,u)=>{s=()=>u(i.reason),i.addEventListener("abort",s,{once:!0}),i.aborted&&s()})])}catch{return{code:Date.now()>=e.deadline?"timeout":"closed",error:"实例查询已结束或超过期限"}}finally{s&&i.removeEventListener("abort",s)}return!Xe(t)||r!==t.runtime||e.instanceId!==t.instanceId?{code:"closed",error:"查询期间实例已结束"}:{value:o}}function bO(e,t){dr("host.message",{message:e,status:t})}function yO(e){Le||bO(su(e),"error")}function dr(e,t){wr(e,t)}function NO(){Dt.close(),lc!==void 0&&window.clearTimeout(lc),fc!==void 0&&window.clearTimeout(fc),!Le&&(Le=!0,is.dispose(),ec.dispose(),window.__HB_SDK_PREVIEW__===ym&&delete window.__HB_SDK_PREVIEW__,window.removeEventListener("hb-sdk:refresh-storage",Ei),window.removeEventListener("hb-sdk:qr-open-change",hc),window.removeEventListener("hb-sdk:qr-refresh",eu),Ho+=1,fr.abort(new DOMException("Browser Dev Host disposed","AbortError")),hn.dispose(),Kt("Browser Dev Host disposed"),jt.dispose(),Dt.send({operation:"close-target",reason:"Browser Dev Host disposed"}),window.setTimeout(()=>_m.abort(),2e3),ss?.close(),_r?.dispose(),_r=void 0,dc.dispose(),Ft!==void 0&&window.clearTimeout(Ft),Ft=void 0,zo(),Ja!==void 0&&window.clearInterval(Ja),ao.clear(),tc?.(),tc=void 0,rc?.(),rc=void 0,nc?.(),nc=void 0,ic?.(),ic=void 0,sc?.(),sc=void 0,oc?.(),oc=void 0)}function zo(){ns!==void 0&&window.clearTimeout(ns),ns=void 0}function iu(e,t){return t?AbortSignal.any([e,t]):e}function zm(e){return!Le&&e===Ho}function wO(){return er.find(({id:e})=>e===Be.mobileLanSelect.value)}function DO(e){return lt(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 jm(e){if(!(!lt(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 Vm(e){return{networkRequest:{...e.networkRequest}}}function SO(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function su(e){return e instanceof Error&&e.message?e.message:"操作失败"}function lt(e){return Object.prototype.toString.call(e)==="[object Object]"}function Vi(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function Gm(e){return document.querySelector(e)??void 0}
|