@heybox/hb-sdk 0.10.0-alpha.2 → 0.10.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +13 -0
  3. package/dist/cli-chunks/{build-Be8QI9ma.cjs → build-DJvUpgCG.cjs} +8 -6
  4. package/dist/cli-chunks/{create-CaAGgJXF.cjs → create-CKFbAKsd.cjs} +2 -2
  5. package/dist/cli-chunks/{dev-BS8uwRH2.cjs → dev-DkQ3XT4g.cjs} +19 -11
  6. package/dist/cli-chunks/{doctor-CgdrOrS5.cjs → doctor-CrDV0t0X.cjs} +1 -1
  7. package/dist/cli-chunks/{game-binding-guide-DX8uXx0V.cjs → game-binding-guide-Du9jYSv0.cjs} +3 -3
  8. package/dist/cli-chunks/{game-bindings-CjI0oA1t.cjs → game-bindings-DyUsgTvm.cjs} +4 -4
  9. package/dist/cli-chunks/{games-C8A0PCo-.cjs → games-60o0JlU1.cjs} +1 -1
  10. package/dist/cli-chunks/{index-BTOX41Vr.cjs → index-B3bDDBnX.cjs} +1 -1
  11. package/dist/cli-chunks/{index-CMbVUUpA.cjs → index-oQnW71g6.cjs} +24 -22
  12. package/dist/cli-chunks/{index.esm-D7A_j5MA.cjs → index.esm-B8H9EwB1.cjs} +67 -0
  13. package/dist/cli-chunks/{index.esm-CIBT3Na1.cjs → index.esm-C5mTEO5-.cjs} +9 -9
  14. package/dist/cli-chunks/{login-BWuLgJWT.cjs → login-81EUI3Tp.cjs} +1 -1
  15. package/dist/cli-chunks/{project-vite-FWtHl3XL.cjs → project-vite-BL7txpEs.cjs} +1 -1
  16. package/dist/cli-chunks/{remote-R1jgvh-Z.cjs → remote-BaistJfP.cjs} +13 -9
  17. package/dist/cli-chunks/{runtime-permission-env-BuXOApO4.cjs → runtime-permission-env-ChCGtenG.cjs} +392 -113
  18. package/dist/cli-chunks/{skill-EM-Uv3Rj.cjs → skill-BQUjMV7k.cjs} +2 -2
  19. package/dist/cli-chunks/{version-BXh-cltM.cjs → version-CUuM16X6.cjs} +1 -1
  20. package/dist/cli.cjs +1 -1
  21. package/dist/devtools/browser-dev-host/assets/browser-dev-host-Dho-QHhS.js +224 -0
  22. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-BXVw6d6N.js → desktop-app-launch-CIC_pBdX.js} +1 -1
  23. package/dist/devtools/browser-dev-host/assets/{index-CABlopeJ.js → index-D1Iqs-0N.js} +3 -3
  24. package/dist/devtools/browser-dev-host/index.html +2 -2
  25. package/dist/index.cjs.js +284 -1
  26. package/dist/index.esm.js +284 -1
  27. package/dist/miniapp-publish.cjs.js +215 -116
  28. package/dist/miniapp-publish.esm.js +214 -117
  29. package/dist/protocol.cjs.js +57 -0
  30. package/dist/protocol.esm.js +57 -0
  31. package/dist/vite.cjs.js +238 -96
  32. package/dist/vite.esm.js +238 -96
  33. package/package.json +7 -7
  34. package/skill/skill.json +4 -4
  35. package/types/index.d.ts +76 -3
  36. package/types/miniapp-publish/index.d.ts +30 -15
  37. package/types/vite/index.d.ts +7 -0
  38. package/dist/devtools/browser-dev-host/assets/browser-dev-host-CpphzCg4.js +0 -224
@@ -1,224 +0,0 @@
1
- import{m as Om,H as Qc,a_ as Mm,bA as Cm,a3 as Rm,bh as Lm,bi as Pm,n as Ct,bK as re,ba as El,l as gl,aM as vm,e as qc,aR as km,aD as xm,k as Um,aN as Bm,bE as Tn,aY as qn,aX as ho,aZ as Hi,b2 as pl,b4 as Hm,f as Ji,v as Fm,ap as es,Z as oc,aQ as zm,j as mo,at as Eo,h as jm,be as Tl,aI as Vm,G as Gm,b0 as _l,U as Ym,z as Qm,aF as qm,y as Wm,bb as $m,bC as Al,bB as Il,b6 as Km,g as go,aH as Zm,b as Ar,c as Xm}from"./desktop-app-launch-BXVw6d6N.js";function Jm(){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 e0(){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 bi={device:'[data-preview-target="device"]',screen:'[data-preview-target="screen"]',app:"#device iframe",workbench:'[data-testid="workbench-root"]'},Wc=15e3,t0=32*1024*1024,$c="data-hb-preview-capture-device",Pa="data-hb-preview-capture-ancestor",Kc="data-hb-preview-capture-surface",Zc=64,r0=1024;function n0(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??Wc;if(!Number.isFinite(n)||n<=0||n>Wc)throw it("INVALID_CAPTURE_LEASE","截图租约无效");let i;function s(d,l,h){d.attributes.push({element:l,name:h,previous:l.getAttribute(h)}),l.setAttribute(h,d.token)}function a(d){const l=i;if(!l||l.token!==d)return!1;const h=c(l),f=!!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:E,name:g,previous:b}of l.attributes)E.getAttribute(g)===d&&(b===null?E.removeAttribute(g):E.setAttribute(g,b));return l.overlay.remove(),f&&(r.scrollX!==l.scroll.x||r.scrollY!==l.scroll.y)&&r.scrollTo(l.scroll.x,l.scroll.y),h}function c(d){const{viewport:l,target:h,rect:f}=d;if(!h?.isConnected||!f||Date.now()>=d.expiresAt||r.innerWidth!==l.width||r.innerHeight!==l.height||r.devicePixelRatio!==l.devicePixelRatio)return!1;const E=h.getBoundingClientRect();return["left","top","width","height"].every(g=>Math.abs(E[g]-f[g])<.01)}async function u(d,l){if(l?.throwIfAborted(),!Number.isFinite(d.deadlineAt)||Date.now()>=d.deadlineAt)throw it("PREVIEW_TIMEOUT","截图操作已超时");if(d.scope==="workbench"||!Object.hasOwn(bi,d.scope))throw it("INVALID_CAPTURE_SCOPE","设备像素截图仅支持 device、screen 或 app");if(!d.operationId||d.operationId.length>128)throw it("INVALID_OPERATION","截图操作标识无效");if(!d.previewImage.startsWith("data:image/png;base64,")||d.previewImage.length>t0)throw it("INVALID_CAPTURE_IMAGE","共享窗口冻结图无效或过大");if(i)throw it("PREVIEW_BUSY","已有设备截图正在执行");const h=t.querySelectorAll(bi.device);if(h.length!==1)throw it("DEVICE_NOT_UNIQUE","设备画面不唯一或尚未创建");const f=h[0],E=d.scope==="device"?f:t.querySelector(bi[d.scope]);if(!E||E!==f&&!f.contains(E))throw it("CAPTURE_TARGET_UNAVAILABLE","截图内容尚未创建");const g=f.getBoundingClientRect();if(!(g.width>0&&g.height>0))throw it("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",V=>V.preventDefault(),{passive:!1}),b.addEventListener("touchmove",V=>V.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(()=>a(y.token),Math.max(0,N-Date.now()));const w=()=>a(y.token);l?.addEventListener("abort",w,{once:!0}),y.removeAbort=()=>l?.removeEventListener("abort",w);const I=()=>{const{viewport:V}=y;(r.innerWidth!==V.width||r.innerHeight!==V.height||r.devicePixelRatio!==V.devicePixelRatio)&&a(y.token)};r.addEventListener("resize",I),y.removeResize=()=>r.removeEventListener("resize",I);const x=()=>{if(l?.throwIfAborted(),i!==y||Date.now()>=N)throw it("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{b.src=d.previewImage,await b.decode(),x();const V=y.token,M=`[${$c}="${V}"]`,R=r.getComputedStyle(f),L=new r.DOMMatrixReadOnly(R.transform==="none"?void 0:R.transform),Y=Math.atan2(L.b,L.a),j=f.querySelector(".desktop-window__surface"),ee=j?j.offsetWidth:Number.parseFloat(R.width),k=j?j.offsetHeight:Number.parseFloat(R.height),z=R.backgroundColor,F=r.getComputedStyle(t.body).backgroundColor,U=me=>!me||me==="transparent"||me==="rgba(0, 0, 0, 0)",H=U(z)?U(F)?"#fff":F:z;if(!(ee>0&&k>0))throw it("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");x(),t.body.append(b),s(y,f,$c),j&&s(y,j,Kc);for(let me=f.parentElement;me;me=me.parentElement)s(y,me,Pa);const P=t.createElement("style");y.style=P;const C=`
2
- [${Pa}="${V}"] {overflow:visible!important;scrollbar-width:none!important;}
3
- [${Pa}="${V}"]::-webkit-scrollbar {display:none!important;}
4
- [${Kc}="${V}"] {transform:none!important;transition:none!important;}
5
- `,Q=(me,De,we=0,Oe=0)=>`${M} {position:absolute!important;left:${me}px!important;top:${De}px!important;width:${ee}px!important;height:${k}px!important;transform:translate(${we}px,${Oe}px) rotate(${Y}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${H}!important;}`;P.textContent=C+Q(0,0),x(),t.head.append(P);const S=f.getBoundingClientRect(),q=t.querySelector(bi.app),W=q&&f.contains(q)?q.getBoundingClientRect():void 0,Z=W&&W.width>0&&W.height>0?W:void 0,se=Z?Math.floor(r.innerWidth-1-(Z.left-S.left)):r.innerWidth+64,de=Z?Math.floor(r.innerHeight-1-(Z.top-S.top)):32,Ie=se-S.left,Re=de-S.top;x(),P.textContent=C+Q(Ie,Re);const Ue=f.getBoundingClientRect();P.textContent=C+Q(Ie,Re,se-Ue.left,de-Ue.top),x();const _=E.getBoundingClientRect(),B=Math.floor(xr(_.left+r.scrollX)),K=Math.floor(xr(_.top+r.scrollY)),J={x:B,y:K,width:Math.ceil(xr(_.right+r.scrollX))-B,height:Math.ceil(xr(_.bottom+r.scrollY))-K};if(!(J.width>0&&J.height>0)||J.x<0||J.y<0)throw it("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(Z&&q){const me=q.getBoundingClientRect();if(!(me.left<r.innerWidth&&me.top<r.innerHeight&&me.right>0&&me.bottom>0))throw it("CAPTURE_LAYOUT_INVALID","无法保持 iframe 的最小绘制区域");const De=f.getBoundingClientRect(),we=Math.floor(xr(De.left))-1,Oe=Math.floor(xr(De.top))-1,Pe=r.innerWidth-we,Me=r.innerHeight-Oe;if(we<0||Oe<0||Pe<=0||Me<=0||Pe>Zc||Me>Zc||Pe*Me>r0)throw it("CAPTURE_LAYOUT_INVALID","无法在有界角部保持完整设备绘制,请改用 --scale css");b.style.clipPath=`polygon(0 0,100% 0,100% ${Oe}px,${we}px ${Oe}px,${we}px 100%,0 100%)`,b.setAttribute("data-hb-preview-capture-corner",JSON.stringify({x:we,y:Oe,width:Pe,height:Me}))}const Ee=t.createElement("div");if(Ee.setAttribute("aria-hidden","true"),Ee.style.cssText=`position:absolute;left:${J.x+J.width+2}px;top:${J.y+J.height+2}px;width:1px;height:1px;pointer-events:none;opacity:0;`,y.bounds=Ee,x(),t.body.append(Ee),y.target=E,y.rect=_,await i0(r,l),x(),!c(y))throw it("CAPTURE_LAYOUT_INVALID","截图准备期间布局发生变化,请重新截图");y.observer=new r.ResizeObserver(()=>{i===y&&!c(y)&&a(y.token)});for(const{element:me}of y.attributes)y.observer.observe(me);return{token:V,clip:J,devicePixelRatio:r.devicePixelRatio,expiresAt:N}}catch(V){throw a(y.token),V}}return{prepare:u,restore:a,cancel:d=>i?.operationId!==d?!1:(a(i.token),!0),dispose:()=>{i&&a(i.token)}}}function i0(e,t){return new Promise((r,n)=>{let i=e.requestAnimationFrame(()=>{i=e.requestAnimationFrame(a)});const s=()=>{e.cancelAnimationFrame(i),t?.removeEventListener("abort",s),n(t?.reason)};function a(){t?.removeEventListener("abort",s),r()}t?.addEventListener("abort",s,{once:!0}),t?.aborted&&s()})}function it(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 ra=["post.get","post.comments.list","post.watch"],Wn=["post.setLiked","post.setFavorited","post.comments.openEditor","post.comments.delete","post.comments.setLiked"],cc="user.games.getOverview",ts="user.data.query",kn="user.data.sync",rs="user.data.file",uc="user.dataPermission.request",dc="user.dataPermission.get",lc="user.dataPermission.set",fc="user.dataPermission.openSettings",hc="user.dataPermission.revokeSession",bl=[cc,ts,kn,rs,uc,dc,lc,fc,hc],ns="workspaceCards.requestRefresh",is="auth.getAccountState",ss="auth.login",as="user.getFollowStatus",os="user.requestFollowAuthor",s0="gameSaves.list",a0="gameSaves.sync",o0="gameSaves.getFile",c0="gameSaves.readParsedData",cs="user.getInfo",us="user.revokeAuthorization",ds="user.getSteamGameList",$n="user.showAppreciation",ls="share.copyLink",fs="share.showShareMenu",hs="share.screenshot",ms="share.screenshotLong",Mr="viewport.setDisplay",Es="viewport.getWindowInfo",gs="viewport.setNavigationBarStyle",Kn="storage.getStorage",Zn="storage.setStorage",ps="network.request",Ts="network.download",_s="network.upload",As="files.pickFiles",Is="files.pickDirectory",bs="files.saveFile",Xn="file.create",Jn="file.remove",ys="file.exists",ei="file.readText",Ns="file.writeText",ti="file.readBytes",ws="file.writeBytes",ri="file.stat",Ds="directory.create",ni="directory.remove",Ss="directory.exists",Os="directory.list",ii="media.pick",Ms="ui.showToast",Cs="ui.showLoading",Rs="ui.hideLoading",Ls="device.vibrate",Ps="device.setClipboard",vs="device.executeProtocol",ks="navigation.close",xs="navigation.reload",Us="navigation.openAppPage",Kt="cloud.leaderboard.submit",Mt="cloud.leaderboard.getList",ur="cloud.leaderboard.getCurrentUserEntry",Cr="cloud.leaderboard.deleteCurrentUserEntry",zt="cloud.leaderboard.getInfo",Jr="cloud.storage.getStorage",en="cloud.storage.setStorage",tn="cloud.storage.removeItem",Rr="cloud.storage.getKeys",na="companion.getInfo",ia="companion.getPreparationStatus",sa="companion.prepare",aa="companion.cancelPreparation",oa="companion.getActiveSession",ca="companion.launch",ua="companion.session.write",da="companion.session.closeStdin",la="companion.session.terminate",fa="companion.session.ackOutput",ha="companion.openAttachment",ma="companion.showNotification",dr=[...ra.map(e=>({method:e,module:"post",capability:e,requirement:{kind:"all",permissions:["post"]},risk:"medium"})),...Wn.map(e=>({method:e,module:"post",capability:e,requirement:{kind:"all",permissions:["post"]},risk:"high"})),...[s0,a0,o0,c0].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),...bl.map(e=>({method:e,module:"userGameData",capability:e,requirement:{kind:"all",permissions:["user_game_data"]},risk:"high"})),{method:ns,module:"workspaceCards",capability:ns,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:is,module:"auth",capability:is,requirement:{kind:"none"},risk:"low"},{method:ss,module:"auth",capability:ss,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:as,module:"user",capability:as,requirement:{kind:"none"},risk:"low"},{method:os,module:"user",capability:os,requirement:{kind:"none"},risk:"high"},{method:cs,module:"user",capability:cs,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:us,module:"user",capability:us,requirement:{kind:"none"},risk:"high"},{method:ds,module:"user",capability:ds,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:$n,module:"user",capability:$n,requirement:{kind:"none"},risk:"medium"},{method:ls,module:"share",capability:ls,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:fs,module:"share",capability:fs,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:hs,module:"share",capability:hs,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:ms,module:"share",capability:ms,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Es,module:"viewport",capability:Es,requirement:{kind:"none"},risk:"low"},{method:gs,module:"viewport",capability:gs,requirement:{kind:"none"},risk:"low"},{method:Mr,module:"viewport",capability:Mr,requirement:{kind:"none"},risk:"low"},{method:Kn,module:"storage",capability:Kn,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:Zn,module:"storage",capability:Zn,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:ps,module:"network",capability:ps,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Ts,module:"network",capability:Ts,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:_s,module:"network",capability:_s,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:As,module:"files",capability:As,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Is,module:"files",capability:Is,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:bs,module:"files",capability:bs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Xn,module:"file",capability:Xn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Jn,module:"file",capability:Jn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ys,module:"file",capability:ys,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ei,module:"file",capability:ei,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ns,module:"file",capability:Ns,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ti,module:"file",capability:ti,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ws,module:"file",capability:ws,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ri,module:"file",capability:ri,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ds,module:"directory",capability:Ds,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ni,module:"directory",capability:ni,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ss,module:"directory",capability:Ss,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Os,module:"directory",capability:Os,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ii,module:"media",capability:ii,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:Ms,module:"ui",capability:Ms,requirement:{kind:"none"},risk:"low"},{method:Cs,module:"ui",capability:Cs,requirement:{kind:"none"},risk:"low"},{method:Rs,module:"ui",capability:Rs,requirement:{kind:"none"},risk:"low"},{method:Ls,module:"device",capability:Ls,requirement:{kind:"none"},risk:"low"},{method:Ps,module:"device",capability:Ps,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:vs,module:"device",capability:vs,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:ks,module:"navigation",capability:ks,requirement:{kind:"none"},risk:"medium"},{method:xs,module:"navigation",capability:xs,requirement:{kind:"none"},risk:"medium"},{method:Us,module:"navigation",capability:Us,requirement:{kind:"none"},risk:"medium"},{method:Kt,module:"cloud",capability:Kt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Mt,module:"cloud",capability:Mt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:ur,module:"cloud",capability:ur,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Cr,module:"cloud",capability:Cr,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:zt,module:"cloud",capability:zt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Jr,module:"cloud",capability:Jr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:en,module:"cloud",capability:en,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:tn,module:"cloud",capability:tn,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Rr,module:"cloud",capability:Rr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[na,ia,sa,aa,oa,ca,ua,da,la,fa,ha,ma].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],gr="heybox:miniprogram",yl=2,Nl="hb_mini_bridge_nonce",wl="sdk.handshake",yi="runtime.location.probe",u0="sdk.location.report",d0="sdk.csp.violation",Dl="operation.progress",l0="companion.session.output",f0="companion.session.exit",h0="companion.session.ownershipLost";function m0(e){return!Dt(e)||e.namespace!==gr||e.version!==1&&e.version!==2||!Ge(e.nonce)?!1:e.type==="handshake"?Ge(e.id)&&e.method===wl&&e.error===void 0&&b0(e.payload):e.type==="request"?Ge(e.id)&&Ge(e.method)&&e.error===void 0:e.type==="response"?Ge(e.id)&&(e.method===void 0||Ge(e.method))&&(e.error===void 0||y0(e.error)):e.type==="event"?!Ge(e.method)||e.error!==void 0?!1:e.method===Dl?e.version===2&&Ge(e.id)&&I0(e.payload):e.id===void 0||Ge(e.id):e.type==="cancel"?e.version===2&&Ge(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function mc(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function Sl(e){return Dt(e)?e.kind==="sandbox"?Tt(e,["kind"]):e.kind==="directory"&&Ge(e.handleId)&&Tt(e,["kind","handleId"]):!1}function Dr(e){return!Dt(e)||e.kind!=="file"?!1:Ge(e.handleId)?Tt(e,["kind","handleId"]):Sl(e.root)&&mc(e.relativePath)&&Tt(e,["kind","root","relativePath"])}function Ol(e){return!Dt(e)||e.kind!=="directory"?!1:Ge(e.handleId)?Tt(e,["kind","handleId"]):Sl(e.root)&&(e.relativePath==="."||mc(e.relativePath))&&Tt(e,["kind","root","relativePath"])}function E0(e){return Dt(e)&&e.kind==="file"&&Ge(e.name)&&N0(e.mode)&&Dr(e.ref)&&Tt(e,["kind","name","mode","ref"])}const Ml=20,Xc=["type","mimeType","size","width","height","previewUrl","file"];function g0(e){return e===void 0?!0:!(!Dt(e)||!Tt(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&&(!w0(e.maxCount,1,Ml)||e.source==="camera"&&e.maxCount!==1))}function Cl(e){if(!Dt(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!Tt(e,t?[...Xc,"durationMs"]:Xc)||!Ge(e.mimeType)||!sr(e.size)||!Jc(e.width)||!Jc(e.height)||!Ge(e.previewUrl)||!T0(e.file)?!1:t?sr(e.durationMs):!0}function p0(e){if(!Array.isArray(e)||e.length<1||e.length>Ml)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!Cl(e[t]))return!1;return!0}function T0(e){return!E0(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&Ge(e.ref.handleId)}function Rl(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function _0(e){return!Dt(e)||!sr(e.loaded)||typeof e.lengthComputable!="boolean"||!Tt(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?sr(e.total)&&e.loaded<=e.total:e.total===void 0}function A0(e){return Dt(e)?e.phase==="downloading"?sr(e.loaded)&&(e.total===void 0||sr(e.total)&&e.loaded<=e.total)&&Tt(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:sr(e.processed)&&sr(e.total)&&e.processed<=e.total&&Tt(e,["phase","processed","total"]):!1}function I0(e){return _0(e)||A0(e)||Dt(e)&&Tt(e,["watching"])&&e.watching===!0}function b0(e){return Dt(e)&&Ge(e.href)&&typeof e.userAgent=="string"&&Ge(e.sdkVersion)}function y0(e){return Dt(e)&&Ge(e.code)&&typeof e.message=="string"}function N0(e){return e==="read"||e==="readwrite"}function sr(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Jc(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function w0(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function Ge(e){return typeof e=="string"&&e.length>0}function Tt(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Ll={ark:"明日方舟",black_myth_wukong:"黑神话悟空",task_bar_hero:"任务栏英雄",phantom_blade_zero:"影之刃零"},Pl=Object.keys(Ll),Fi=[{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}],Jt="account.pc_hardware",Ea=[...Fi,{key:Jt,game:null,family:"pc_hardware",name:"PC 硬件档案",disclosureRevision:1,queries:{get:{schema:"account.pc_hardware",version:1}},sync:!1,file:!1}],Ir=Ea.map(e=>e.key),D0=new Set(Ir),S0=new Set(Pl);function nr(e){return D0.has(e)}function eu(e){return S0.has(e)}function Ec(e){const t=Ea.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 O0="同步时,原始存档将上传至小黑盒;向小程序提供原始文件仍需单独许可。",Lr=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards","user_game_data","post"],gc=[{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:"在精确资源声明范围内读取当前用户的游戏资料:明日方舟角色/养成与抽卡,以及黑神话悟空、任务栏英雄、影之刃零的云存档解析结果与文件,以及账号已保存的 PC 硬件档案。",access:"declaration",risk:"high",config:{resources:{type:"resource-map",required:!0,items:Ir,description:"精确资源声明对象;每项必须填写 1~30 个 Unicode 码点的 purpose,不接受通配符或未开放资源。"}},methods:bl,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:[...ra,...Wn],conditions:["显式声明 read / write,省略时为 false;写操作须由用户明确触发,继续执行社区审核和权限校验。"]}];new Set(Lr);const M0=30;function C0(e){if(typeof e!="string")throw new Error("purpose 必须是字符串");const t=e.trim(),r=Array.from(t);if(r.length<1||r.length>M0)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 si(e){return vl(e,!1)}function R0(e){return vl(e,!0)}function vl(e,t){if(!tu(e))throw new Error("resources 必须是资源声明对象;每项资源必须填写 purpose");const r={};for(const n of Object.keys(e).sort()){const i=e[n];if(!tu(i)||Object.keys(i).length!==1||!Object.prototype.hasOwnProperty.call(i,"purpose"))throw new Error(`resources.${n} 必须且只能包含 purpose`);let s;try{s=C0(i.purpose)}catch(a){throw new Error(`resources.${n}: ${a.message}`)}if(!nr(n)){if(t&&/^(?:game\.[a-z0-9_]+|account)\.[a-z0-9_.]+$/.test(n))continue;throw new Error(`resources 包含未开放资源:${n}`)}r[n]={purpose:s}}return r}function L0(e){return Ir.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function tu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kl(e,t,r,n){return JSON.stringify(["user-game-data-purpose-v1",e,t,r,n])}const P0=new Set(Lr);function v0(e){return P0.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),!!v0(s)){if(s==="network"){const a=n.config;if(!Ur(a)||typeof a.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{useOfficialDomain:a.useOfficialDomain}};continue}if(s==="post"){const a=n.config;if(!Ur(a)||typeof a.read!="boolean"||typeof a.write!="boolean")return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{read:a.read,write:a.write}};continue}if(s==="user_game_data"){const a=n.config;if(!Ur(a))return{valid:!1,permissions:{}};try{const c=R0(a.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 zi=["network","companion","appProtocol"];function xl(e){if(!_n(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>zi.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!_n(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(!_n(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(!_n(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!_n(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>zi.indexOf(n.key)-zi.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function k0(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 zi)!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 pc(e){const t=ot(e.runtimePermissions),r=xl(e.localDevGrant),n=t.valid?t.permissions:{};for(const a of Lr)e.declaredPermissions[a]?.enabled!==!0?delete n[a]:gc.some(c=>c.key===a&&c.access==="declaration")?n[a]={key:a,status:"enabled",config:x0(a,e.declaredPermissions)}:a==="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 a of r.grant.entries)e.declaredPermissions[a.key]?.enabled!==!0||n[a.key]?.status==="enabled"||(n[a.key]=a,i.push(a.key));const s=Ul(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:Lr.flatMap(a=>n[a]?[n[a]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function x0(e,t){const r=gc.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"?si(t[e]?.resources):{})}return n}function Ul(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _n(e,t){return Ul(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const rn=["identity","profile","steam_account"],U0=/^[a-z][a-z0-9-]{0,31}$/,Bl=["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 ru;function xe(e,t,r){function n(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const d=a.prototype,l=Object.keys(d);for(let h=0;h<l.length;h++){const f=l[h];f in c||(c[f]=d[f].bind(c))}}const i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function a(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(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class xn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(ru=globalThis).__zod_globalConfig??(ru.__zod_globalConfig={});const nu=globalThis.__zod_globalConfig;function En(e){return e&&Object.assign(nu,e),nu}function B0(e,t){return typeof t=="bigint"?t.toString():t}function H0(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Hl(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const iu=Symbol("evaluating");function lt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==iu)return n===void 0&&(n=iu,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}const Fl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function F0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function su(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function z0(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function St(e){return{}}function j0(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const V0={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 Cn(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 G0(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 zl(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Ni(e){return typeof e=="string"?e:e?.message}function hi(e,t,r){const n=e.message?e.message:Ni(e.inst?._zod.def?.error?.(e))??Ni(t?.error?.(e))??Ni(r.customError?.(e))??Ni(r.localeError?.(e))??"Invalid input",{inst:i,continue:s,input:a,...c}=e;return c.path??(c.path=[]),c.message=n,t?.reportInput&&(c.input=a),c}const jl=(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,B0,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Y0=xe("$ZodError",jl),ga=xe("$ZodError",jl,{Parent:Error}),Q0=e=>(t,r,n,i)=>{const s=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new xn;if(a.issues.length){const c=new(i?.Err??e)(a.issues.map(u=>hi(u,s,En())));throw Fl(c,i?.callee),c}return a.value},q0=Q0(ga),W0=e=>async(t,r,n,i)=>{const s=n?{...n,async:!0}:{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const c=new(i?.Err??e)(a.issues.map(u=>hi(u,s,En())));throw Fl(c,i?.callee),c}return a.value},$0=W0(ga),K0=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 xn;return s.issues.length?{success:!1,error:new(e??Y0)(s.issues.map(a=>hi(a,i,En())))}:{success:!0,data:s.value}},Vl=K0(ga),Z0=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(a=>hi(a,i,En())))}:{success:!0,data:s.value}},Gl=Z0(ga),X0=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},J0=/^-?\d+$/,eE=/^-?\d+(?:\.\d+)?$/,tE=/^null$/i,pa=xe("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Yl={number:"number",bigint:"bigint",object:"date"},rE=xe("$ZodCheckLessThan",(e,t)=>{pa.init(e,t);const r=Yl[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})}}),nE=xe("$ZodCheckGreaterThan",(e,t)=>{pa.init(e,t);const r=Yl[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=xe("$ZodCheckNumberFormat",(e,t)=>{pa.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=V0[t.format];e._zod.onattach.push(a=>{const c=a._zod.bag;c.format=t.format,c.minimum=i,c.maximum=s,r&&(c.pattern=J0)}),e._zod.check=a=>{const c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?a.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}):a.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&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),c>s&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),sE=xe("$ZodCheckStringFormat",(e,t)=>{var r,n;pa.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=()=>{})}),aE=xe("$ZodCheckRegex",(e,t)=>{sE.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})}}),oE={major:4,minor:4,patch:3},Lt=xe("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=oE;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=(a,c,u)=>{let d=Cn(a),l;for(const h of c){if(h._zod.def.when){if(G0(a)||!h._zod.def.when(a))continue}else if(d)continue;const f=a.issues.length,E=h._zod.check(a);if(E instanceof Promise&&u?.async===!1)throw new xn;if(l||E instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await E,a.issues.length!==f&&(d||(d=Cn(a,f)))});else{if(a.issues.length===f)continue;d||(d=Cn(a,f))}}return l?l.then(()=>a):a},s=(a,c,u)=>{if(Cn(a))return a.aborted=!0,a;const d=i(c,n,u);if(d instanceof Promise){if(u.async===!1)throw new xn;return d.then(l=>e._zod.parse(l,u))}return e._zod.parse(d,u)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){const d=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(l=>s(l,a,c)):s(d,a,c)}const u=e._zod.parse(a,c);if(u instanceof Promise){if(c.async===!1)throw new xn;return u.then(d=>i(d,n,c))}return i(u,n,c)}}lt(e,"~standard",()=>({validate:i=>{try{const s=Vl(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Gl(e,i).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),cE=xe("$ZodString",(e,t)=>{Lt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??X0(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}}),Ql=xe("$ZodNumber",(e,t)=>{Lt.init(e,t),e._zod.pattern=e._zod.bag.pattern??eE,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}}),uE=xe("$ZodNumberFormat",(e,t)=>{iE.init(e,t),Ql.init(e,t)}),dE=xe("$ZodNull",(e,t)=>{Lt.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}}),lE=xe("$ZodNever",(e,t)=>{Lt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function au(e,t,r){e.issues.length&&t.issues.push(...zl(r,e.issues)),t.value[r]=e.value}const fE=xe("$ZodArray",(e,t)=>{Lt.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 a=0;a<i.length;a++){const c=i[a],u=t.element._zod.run({value:c,issues:[]},n);u instanceof Promise?s.push(u.then(d=>au(d,r,a))):au(u,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function Bs(e,t,r,n,i,s){const a=r in n;if(e.issues.length){if(i&&s&&!a)return;t.issues.push(...zl(r,e.issues))}if(!a&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?a&&(t.value[r]=void 0):t.value[r]=e.value}function hE(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=j0(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function mE(e,t,r,n,i,s){const a=[],c=i.keySet,u=i.catchall._zod,d=u.def.type,l=u.optin==="optional",h=u.optout==="optional";for(const f in t){if(f==="__proto__"||c.has(f))continue;if(d==="never"){a.push(f);continue}const E=u.run({value:t[f],issues:[]},n);E instanceof Promise?e.push(E.then(g=>Bs(g,r,f,t,l,h))):Bs(E,r,f,t,l,h)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}const EE=xe("$ZodObject",(e,t)=>{if(Lt.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=H0(()=>hE(t));lt(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 h of l.values)u[d].add(h)}}return u});const i=F0,s=t.catchall;let a;e._zod.parse=(c,u)=>{a??(a=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=[],h=a.shape;for(const f of a.keys){const E=h[f],g=E._zod.optin==="optional",b=E._zod.optout==="optional",N=E._zod.run({value:d[f],issues:[]},u);N instanceof Promise?l.push(N.then(y=>Bs(y,c,f,d,g,b))):Bs(N,c,f,d,g,b)}return s?mE(l,d,c,u,n.value,e):l.length?Promise.all(l).then(()=>c):c}});function ou(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=>!Cn(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(a=>hi(a,n,En())))}),t)}const gE=xe("$ZodUnion",(e,t)=>{Lt.init(e,t),lt(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),lt(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),lt(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),lt(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=>Hl(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 a=[];for(const c of t.options){const u=c._zod.run({value:n.value,issues:[]},i);if(u instanceof Promise)a.push(u),s=!0;else{if(u.issues.length===0)return u;a.push(u)}}return s?Promise.all(a).then(c=>ou(c,n,e,i)):ou(a,n,e,i)}}),pE=xe("$ZodLiteral",(e,t)=>{if(Lt.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"?su(n):n?su(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 cu(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const TE=xe("$ZodOptional",(e,t)=>{Lt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",lt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),lt(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Hl(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(a=>cu(a,i)):cu(s,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),_E=xe("$ZodLazy",(e,t)=>{Lt.init(e,t),lt(e._zod,"innerType",()=>{const r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),lt(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),lt(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),lt(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),lt(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)});function AE(e,t){return new e({type:"string",...St()})}function IE(e,t){return new e({type:"number",checks:[],...St()})}function bE(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...St()})}function yE(e,t){return new e({type:"null",...St()})}function NE(e,t){return new e({type:"never",...St()})}function ge(e,t){return new rE({check:"less_than",...St(),value:e,inclusive:!0})}function pe(e,t){return new nE({check:"greater_than",...St(),value:e,inclusive:!0})}function Te(e,t){return new aE({check:"string_format",format:"regex",...St(),pattern:e})}En({jitless:!0});function ql(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 Lr){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:si(n.resources)};continue}t[r]={enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!Lr.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 wE(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return ql(t)===e?t:void 0}catch{return}}const Qt=xe("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Lt.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>q0(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Vl(e,r,n),e.parseAsync=async(r,n)=>$0(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Gl(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)=>z0(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),DE=xe("ZodMiniString",(e,t)=>{cE.init(e,t),Qt.init(e,t)});function D(e){return AE(DE)}const Wl=xe("ZodMiniNumber",(e,t)=>{Ql.init(e,t),Qt.init(e,t)});function X(e){return IE(Wl)}const SE=xe("ZodMiniNumberFormat",(e,t)=>{uE.init(e,t),Wl.init(e,t)});function _e(e){return bE(SE)}const OE=xe("ZodMiniNull",(e,t)=>{dE.init(e,t),Qt.init(e,t)});function fe(e){return yE(OE)}const ME=xe("ZodMiniNever",(e,t)=>{lE.init(e,t),Qt.init(e,t)});function CE(e){return NE(ME)}const RE=xe("ZodMiniArray",(e,t)=>{fE.init(e,t),Qt.init(e,t)});function ue(e,t){return new RE({type:"array",element:e,...St()})}const LE=xe("ZodMiniObject",(e,t)=>{EE.init(e,t),Qt.init(e,t),lt(e,"shape",()=>t.shape)});function le(e,t){return new LE({type:"object",shape:e,catchall:CE(),...St()})}const PE=xe("ZodMiniUnion",(e,t)=>{gE.init(e,t),Qt.init(e,t)});function O(e,t){return new PE({type:"union",options:e,...St()})}const vE=xe("ZodMiniLiteral",(e,t)=>{pE.init(e,t),Qt.init(e,t)});function Ae(e,t){return new vE({type:"literal",values:Array.isArray(e)?e:[e],...St()})}const kE=xe("ZodMiniOptional",(e,t)=>{TE.init(e,t),Qt.init(e,t)});function $(e){return new kE({type:"optional",innerType:e})}const xE=xe("ZodMiniLazy",(e,t)=>{_E.init(e,t),Qt.init(e,t)});function ae(e){return new xE({type:"lazy",getter:e})}const oe={PcHardwareInfo:le({updatedAt:X(),cpu:$(le({name:D()})),gpu:$(le({name:D()})),memory:$(le({name:$(D()),capacityGiB:$(X())})),motherboard:$(le({name:D()})),disks:$(ue(le({name:D()})))}),ArkProfile:le({uid:D(),name:D(),level:X(),avatar:$(ae(()=>oe.ArkPlayerAvatar)),characterCount:X(),totalCharacterCount:X(),mainStageProgress:D(),rogueLevel:X(),campaignFullKillCount:X(),tag:D(),observedAt:$(O([D(),X()])),lastOnlineTs:$(O([D(),X()])),registerTs:$(O([D(),X()])),changeTime:$(O([D(),X()])),operators:$(ue(ae(()=>oe.ArkOperator)))}),ArkPlayerAvatar:le({url:D(),type:D(),id:D()}),ArkOperator:le({characterId:D(),name:D(),profession:D(),evolvePhase:X(),potentialRank:X()}),ArkGachaAnalysis:le({uid:D(),year:X(),total:X(),srCount:X(),upCount:X(),missCount:X(),careerEvaluation:D(),careerIsLucky:O([Ae(!1),Ae(!0)]),pools:ue(ae(()=>oe.ArkGachaPoolStat)),records:ue(ae(()=>oe.ArkGachaAnalysisRecord)),luckyLottery:ue(X())}),ArkGachaPoolStat:le({poolId:D(),totalCost:X(),ssrCount:X(),ssrCost:X(),records:ue(ae(()=>oe.ArkGachaAnalysisRecord))}),ArkGachaAnalysisRecord:le({name:D(),timestamp:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),diff:X(),negativeDiff:X(),tag:D(),missUp:O([Ae(!1),Ae(!0)])}),GachaRecord:le({id:D(),name:D(),pool:D(),rarity:X(),timestamp:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),BlackMythWukongSave:le({level:$(X()),newGamePlusCount:$(X()),gameTotalTime:$(X()),playerDeathCount:$(X()),totalMoney:$(D()),meditationList:$(O([fe(),ue(X())])),monsterCollectionList:$(O([fe(),ue(X())])),returnPointList:$(O([fe(),ue(X())])),activatedWeaponIdList:$(O([fe(),ue(D())])),activatedEquipIdList:$(O([fe(),ue(X())])),magicArtifactList:$(O([fe(),ue(X())])),soulSkillIdList:$(O([fe(),ue(X())])),huluIdLits:$(O([fe(),ue(X())])),wineIdList:$(O([fe(),ue(X())])),wineIdPartnerList:$(O([fe(),ue(X())])),cropIdList:$(O([fe(),ue(X())])),recipeIdList:$(O([fe(),ue(X())])),wearedWaeponId:$(D()),wearedMagicArtifact:$(X()),wearedSoulSkill:$(X()),wearedHead:$(X()),wearedUpware:$(X()),wearedArm:$(X()),wearedFoot:$(X()),wearedHulu:$(X()),wearedAccessoryList:$(O([fe(),ue(X())])),spellQishu:$(O([fe(),ue(X())])),spellShenfa:$(O([fe(),ue(X())])),spellHaomao:$(O([fe(),ue(X())])),spellBianshen:$(O([fe(),ue(X())])),bossRushBossgroup:$(ae(()=>oe.BlackMythWukongBossRushData)),bossRushRefight:$(ae(()=>oe.BlackMythWukongBossRefightData))}),BlackMythWukongBossRushData:le({bossGroups:$(O([fe(),ue(ae(()=>oe.BlackMythWukongBossRushRecord))]))}),BlackMythWukongBossRushRecord:le({bossGroupId:$(X()),isPassed:$(O([Ae(!1),Ae(!0)])),bestRecords:$(O([fe(),ue(ae(()=>oe.BlackMythWukongBattleRecord))])),encounterBossIndex:$(X()),battleCount:$(X())}),BlackMythWukongBattleRecord:le({battleId:$(D()),battleData:$(ae(()=>oe.BlackMythWukongBattleData))}),BlackMythWukongBattleData:le({totalTime:$(X()),score:$(X()),debuffList:$(O([fe(),ue(X())])),targetId:$(X()),archiveTime:$(D()),roleBase:$(ae(()=>oe.BlackMythWukongRoleBase)),battleStyleInfo:$(ae(()=>oe.BlackMythWukongBattleStyleInfo)),damageInfo:$(ae(()=>oe.BlackMythWukongDamageInfo))}),BlackMythWukongRoleBase:le({level:$(X()),atk:$(X()),hpMax:$(X()),staminaMax:$(X()),mpMax:$(X())}),BlackMythWukongBattleStyleInfo:le({spellList:$(O([fe(),ue(ae(()=>oe.BlackMythWukongCast))])),fabaoInfo:$(ae(()=>oe.BlackMythWukongCast)),soulInfo:$(ae(()=>oe.BlackMythWukongCast)),itemCount:$(X()),wineCount:$(X()),rollCount:$(X()),defuseCount:$(X()),fourPeCount:$(X())}),BlackMythWukongCast:le({castId:$(X()),castCount:$(X())}),BlackMythWukongDamageInfo:le({totalDamage:$(O([D(),X()])),hightestDamage:$(O([D(),X()])),criticalDmgRate:$(X()),totalBeDamaged:$(O([D(),X()])),criticalDmgTotal:$(O([D(),X()])),elemDotDmgTotal:$(O([D(),X()])),elemDotDmgRate:$(X())}),BlackMythWukongBossRefightData:le({bossList:$(O([fe(),ue(ae(()=>oe.BlackMythWukongBossRefightRecord))]))}),BlackMythWukongBossRefightRecord:le({bossId:$(X()),passedMaxLevel:$(X()),lastChallengeLevel:$(X()),bestRecords:$(O([fe(),ue(ae(()=>oe.BlackMythWukongBattleRecord))])),refightStatisticsList:$(O([fe(),ue(ae(()=>oe.BlackMythWukongRefightStatistic))]))}),BlackMythWukongRefightStatistic:le({challengeLevel:$(X()),battleCount:$(X())}),TaskBarHeroSave:le({update_time:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),game_version:D(),account_version:D(),play_time:X(),last_saved_time:D(),common:ae(()=>oe.TaskBarHeroCommon),summary:ae(()=>oe.TaskBarHeroSummary),heroes:O([fe(),ue(ae(()=>oe.TaskBarHeroHero))]),rune_save_data:O([fe(),ue(ae(()=>oe.TaskBarHeroRune))]),pets:O([fe(),ue(ae(()=>oe.TaskBarHeroPet))]),attributes:O([fe(),ue(ae(()=>oe.TaskBarHeroAttribute))]),inventory_slots:O([fe(),ue(ae(()=>oe.TaskBarHeroItemSlot))]),stash_slots:O([fe(),ue(ae(()=>oe.TaskBarHeroItemSlot))]),item_instances:O([fe(),ue(ae(()=>oe.TaskBarHeroItemInstance))]),values:ae(()=>oe.TaskBarHeroValueSummary)}),TaskBarHeroCommon:le({max_completed_stage:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_key:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_wave:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),arranged_hero_keys:O([fe(),ue(O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),arranged_pet_key:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroSummary:le({max_hero_level:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),learned_rune_count:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unlocked_hero:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total_hero:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_count:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inventory_slots:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stash_slots:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroHero:le({hero_key:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),hero_level:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:O([Ae(!1),Ae(!0)]),hero_exp:X(),ability_point:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),allocated_hero_ability_point:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),equipped_item_ids:O([fe(),ue(D())]),equipped_skill_keys:O([fe(),ue(O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),unlocked_attribute_group_keys:O([fe(),ue(O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]))])}),TaskBarHeroRune:le({rune_key:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroPet:le({pet_key:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:O([Ae(!1),Ae(!0)])}),TaskBarHeroAttribute:le({key:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroItemSlot:le({index:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_unique_id:D(),is_unlock:O([Ae(!1),Ae(!0)]),is_unlocked_by_rune:O([Ae(!1),Ae(!0)])}),TaskBarHeroItemInstance:le({item_key:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unique_id:D(),is_chaotic:O([Ae(!1),Ae(!0)]),is_blocked:O([Ae(!1),Ae(!0)]),is_server_pending_item:O([Ae(!1),Ae(!0)]),enchant_count:O([fe(),ue(O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),enchant_data:O([fe(),ue(ae(()=>oe.TaskBarHeroEnchantData))]),item_get_source_type:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),decoration_applied_total_count:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),engraving_applied_total_count:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inscription_applied_total_count:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroEnchantData:le({stat_mod_key:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),tier:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),value:X(),recipe_type:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),mod_type:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),material_key:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stat_type:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroValueSummary:le({market_value:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),price_state:D(),currency:D()}),PhantomBladeZeroSave:le({defaultSlot:D(),slots:ue(ae(()=>oe.PhantomBladeZeroSaveSlot))}),PhantomBladeZeroSaveSlot:le({slot:D(),head:ae(()=>oe.PhantomBladeZeroSlotHead),firstClear:ae(()=>oe.PhantomBladeZeroSlotFirstClear),progress:ae(()=>oe.PhantomBladeZeroSlotProgress),combat:ae(()=>oe.PhantomBladeZeroSlotCombat),achievements:ae(()=>oe.PhantomBladeZeroSlotAchievementSummary),bosses:ae(()=>oe.PhantomBladeZeroSlotBossSummary),collectibles:ae(()=>oe.PhantomBladeZeroSlotCollectibles),quest_details:O([fe(),ae(()=>oe.PhantomBladeZeroQuestDetails)]),inventory_details:O([fe(),ue(ae(()=>oe.PhantomBladeZeroInventoryItem))]),detail:ae(()=>oe.PhantomBladeZeroSlotDetail)}),PhantomBladeZeroSlotHead:le({saveTime:D(),currentLevel:D(),cycle:D(),difficulty:ae(()=>oe.PhantomBladeZeroSlotDifficulty)}),PhantomBladeZeroSlotDifficulty:le({raw:X(),name:D()}),PhantomBladeZeroSlotFirstClear:le({clearDate:ae(()=>oe.PhantomBladeZeroUnavailableValue),cycles:O([fe(),ue(ae(()=>oe.PhantomBladeZeroClearanceRecord))])}),PhantomBladeZeroUnavailableValue:le({value:fe(),reason:D()}),PhantomBladeZeroClearanceRecord:le({Cycle:$(O([fe(),X()])),Ending:X(),Difficulty:X(),GameTime:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),Completion:X(),DiedTimes:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotProgress:le({playTimeSeconds:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),playTime:D(),lastLaunch:ae(()=>oe.PhantomBladeZeroUnavailableValue),narrativePercentage:X(),chapter:D(),remainingDays:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCombat:le({loadout:$(ae(()=>oe.PhantomBladeZeroSlotLoadout)),totalDeaths:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),cycleDeaths:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bossKillTotal:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),currentMainWeapon:$(O([fe(),ae(()=>oe.PhantomBladeZeroNamedItem)])),mainWeapon:ae(()=>oe.PhantomBladeZeroCollectionCount),currentShaqi:$(O([fe(),ae(()=>oe.PhantomBladeZeroNamedItem)])),shaqi:ae(()=>oe.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroSlotLoadout:le({states:$(O([fe(),ue(ae(()=>oe.PhantomBladeZeroLoadoutState))])),main_weapons:O([fe(),ue(D())]),shaqi_weapons:O([fe(),ue(D())]),accessory_ids:O([fe(),ue(D())]),top_medicine:D(),bottom_medicine:D(),current_weapon_index:X(),current_shaqi_weapon_index:X()}),PhantomBladeZeroLoadoutState:le({category:D(),id:D(),level:$(X()),soul_forged:$(O([Ae(!1),Ae(!0)])),reincarnation_count:$(X())}),PhantomBladeZeroNamedItem:le({id:D(),name:D()}),PhantomBladeZeroCollectionCount:le({unknown:$(O([D(),X()])),done:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotAchievementSummary:le({unlocked:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:D()}),PhantomBladeZeroSlotBossSummary:le({groups:O([fe(),ue(ae(()=>oe.PhantomBladeZeroBossGroup))])}),PhantomBladeZeroBossGroup:le({map:D(),mapName:D(),count:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bosses:O([fe(),ue(ae(()=>oe.PhantomBladeZeroBoss))])}),PhantomBladeZeroBoss:le({id:D(),classPath:D(),map:D(),mapName:D(),encountered:O([Ae(!1),Ae(!0)]),killed:O([Ae(!1),Ae(!0)]),kill:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),records:O([fe(),ue(ae(()=>oe.PhantomBladeZeroBossRecord))])}),PhantomBladeZeroBossRecord:le({cycle:D(),diff:D(),diffName:D(),kill:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCollectibles:le({overall:ae(()=>oe.PhantomBladeZeroCollectionSummary),craneBellCount:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),byBigMap:O([fe(),ue(ae(()=>oe.PhantomBladeZeroBigMapProgress))]),currentChapter:ae(()=>oe.PhantomBladeZeroChapterProgress)}),PhantomBladeZeroCollectionSummary:le({bell:ae(()=>oe.PhantomBladeZeroCollectionCount),weapon:ae(()=>oe.PhantomBladeZeroCollectionCount),shaqi:ae(()=>oe.PhantomBladeZeroCollectionCount),accessory:ae(()=>oe.PhantomBladeZeroCollectionCount),medicine:ae(()=>oe.PhantomBladeZeroCollectionCount),challenge:ae(()=>oe.PhantomBladeZeroCollectionCount),hupo:ae(()=>oe.PhantomBladeZeroCollectionCount),heishi:ae(()=>oe.PhantomBladeZeroCollectionCount),flower:ae(()=>oe.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroBigMapProgress:le({unknown:$(O([D(),X()])),mapID:D(),name:D(),pct:X(),done:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),subMaps:O([fe(),ue(D())])}),PhantomBladeZeroChapterProgress:le({unknown:$(O([D(),X()])),mapID:D(),pct:X(),done:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:D()}),PhantomBladeZeroQuestDetails:le({CurrentMainQuestPath:D(),CurrentTutorialQuestPath:D(),TrackedQuestPath:D(),TrackedBranchID:D(),TrackedTaskPointID:D(),ManualTrackingOptOut:O([Ae(!1),Ae(!0)]),NarrativeSavedQuests:O([fe(),ue(ae(()=>oe.PhantomBladeZeroQuest))])}),PhantomBladeZeroQuest:le({QuestClass:D(),QuestCompletion:D(),QuestBranches:O([fe(),ue(ae(()=>oe.PhantomBladeZeroQuestBranch))]),CompletedBranches:O([fe(),ue(D())]),ReachedStateNames:O([fe(),ue(D())])}),PhantomBladeZeroQuestBranch:le({BranchID:D(),TasksProgress:O([fe(),ue(O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),BranchType:D()}),PhantomBladeZeroInventoryItem:le({id:D(),amount:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotDetail:le({bell:O([fe(),ue(ae(()=>oe.PhantomBladeZeroBellDetail))]),weapon:O([fe(),ue(ae(()=>oe.PhantomBladeZeroItemDetail))]),shaqi:O([fe(),ue(ae(()=>oe.PhantomBladeZeroItemDetail))]),accessory:O([fe(),ue(ae(()=>oe.PhantomBladeZeroItemDetail))]),medicine:O([fe(),ue(ae(()=>oe.PhantomBladeZeroItemDetail))]),challenge:O([fe(),ue(ae(()=>oe.PhantomBladeZeroChallengeDetail))]),hupo:O([fe(),ue(ae(()=>oe.PhantomBladeZeroWorldItemDetail))]),heishi:O([fe(),ue(ae(()=>oe.PhantomBladeZeroWorldItemDetail))]),flower:O([fe(),ue(ae(()=>oe.PhantomBladeZeroItemDetail))]),achievements:O([fe(),ue(ae(()=>oe.PhantomBladeZeroAchievementDetail))])}),PhantomBladeZeroBellDetail:le({unknown:$(O([Ae(!1),Ae(!0)])),id:D(),done:O([Ae(!1),Ae(!0)]),equip:O([Ae(!1),Ae(!0)])}),PhantomBladeZeroItemDetail:le({level:$(X()),soul_forged:$(O([Ae(!1),Ae(!0)])),reincarnation_count:$(X()),unknown:$(O([Ae(!1),Ae(!0)])),id:D(),name:D(),done:O([Ae(!1),Ae(!0)]),equip:O([Ae(!1),Ae(!0)]),locs:O([fe(),ue(ae(()=>oe.PhantomBladeZeroLocation))])}),PhantomBladeZeroLocation:le({map:D(),mapName:D(),x:X(),y:X(),z:X()}),PhantomBladeZeroChallengeDetail:le({key:$(D()),unknown:$(O([Ae(!1),Ae(!0)])),index:O([_e().check(pe(-9007199254740991),ge(9007199254740991)),D().check(Te(new RegExp("^-?(0|[1-9][0-9]*)$")))]),guids:O([fe(),ue(D())]),done:O([Ae(!1),Ae(!0)]),locs:O([fe(),ue(ae(()=>oe.PhantomBladeZeroLocation))])}),PhantomBladeZeroWorldItemDetail:le({key:$(D()),unknown:$(O([Ae(!1),Ae(!0)])),id:D(),saveGuid:D(),mobDomain:D(),done:O([Ae(!1),Ae(!0)]),locs:O([fe(),ue(ae(()=>oe.PhantomBladeZeroLocation))])}),PhantomBladeZeroAchievementDetail:le({id:D(),name:D(),desc:D(),grade:D(),hidden:O([Ae(!1),Ae(!0)]),done:O([Ae(!1),Ae(!0)])}),UserGameDataSaveFilePage:le({items:ue(ae(()=>oe.UserGameDataSaveInfo)),hasMore:Ae(!1)}),UserGameDataSaveInfo:le({saveId:D(),createdAt:D(),files:ue(ae(()=>oe.UserGameDataSaveFileInfo))}),UserGameDataSaveFileInfo:le({fileId:D(),name:D(),sizeBytes:X(),modifiedAt:D()})},UE=new Map([["account.pc_hardware",ae(()=>oe.PcHardwareInfo)],["ark.profile",ae(()=>oe.ArkProfile)],["ark.gacha-analysis",ae(()=>oe.ArkGachaAnalysis)],["ark.gacha-record-page",le({items:ue(ae(()=>oe.GachaRecord)),nextCursor:$(D()),hasMore:O([Ae(!1),Ae(!0)]),total:$(X())})],["black_myth_wukong.save",ae(()=>oe.BlackMythWukongSave)],["task_bar_hero.save",ae(()=>oe.TaskBarHeroSave)],["phantom_blade_zero.save",ae(()=>oe.PhantomBladeZeroSave)],["save-file-page",ae(()=>oe.UserGameDataSaveFilePage)]]);function BE(e,t){return UE.get(e)?.safeParse(t).success??!1}dr.map(e=>e.method);function ji(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Ce(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:ji()}function $l(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 Kl="METHOD_FORBIDDEN";function Nt(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Kl,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 HE=/^[A-Za-z0-9_-]{1,64}$/,uu=1e3;function Zl(e){return HE.test(e)?e:VE(e)}function FE(e){return`id_${Zl(e.trim())}`}function Br(e,t){return`hb_miniprogram_${e}_${t}`}function wi(e){return`hb_miniprogram_keys_${e}`}const zE="hb_user_game_data_consent_";function jE(e){return`${zE}${e}`}function VE(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 GE=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 Tc(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),a=new DataView(n.buffer);for(let c=0;c<r;c+=64){for(let N=0;N<16;N+=1)s[N]=a.getUint32(c+N*4,!1);for(let N=16;N<64;N+=1){const y=s[N-15],w=s[N-2],I=vt(y,7)^vt(y,18)^y>>>3,x=vt(w,17)^vt(w,19)^w>>>10;s[N]=s[N-16]+I+s[N-7]+x>>>0}let[u,d,l,h,f,E,g,b]=i;for(let N=0;N<64;N+=1){const y=b+(vt(f,6)^vt(f,11)^vt(f,25))+(f&E^~f&g)+GE[N]+s[N]>>>0,w=(vt(u,2)^vt(u,13)^vt(u,22))+(u&d^u&l^d&l);b=g,g=E,E=f,f=h+y>>>0,h=l,l=d,d=u,u=y+w>>>0}[u,d,l,h,f,E,g,b].forEach((N,y)=>{i[y]=i[y]+N>>>0})}return Array.from(i,c=>c.toString(16).padStart(8,"0")).join("")}function vt(e,t){return e>>>t|e<<32-t}const YE=Object.freeze({upload:"你允许读取的数据可能会被上传至开发者服务器。",no_network:"此小程序未获准将你允许读取的数据上传至开发者服务器。"});function QE(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 a=s;if(a.decision!=="ask"&&a.decision!=="allow"&&a.decision!=="deny"||typeof a.revision!="number"||!Number.isSafeInteger(a.revision)||a.revision<1||a.consentFingerprint!==void 0&&!$E(a.consentFingerprint))return;n[i]={decision:a.decision,revision:a.revision,...a.decision==="allow"&&a.consentFingerprint!==void 0?{consentFingerprint:a.consentFingerprint}:{}}}return{schema_version:1,records:n}}function qE(e){return Tc(`${e.miniProgramId}\0${e.userId}\0${e.environment}`).slice(0,32)}function WE(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 $E(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function Le(e,t,r){return{code:e,message:t,data:r}}function Hs(e){return KE(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?Le("RUNTIME_ERROR",e.message):Le("UNKNOWN_ERROR","小程序运行时异常",e)}function KE(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}const pr=["account.getCurrentUserId","account.onChange","storage.getRaw","storage.setRaw"],va=[...pr,"network.request"],du={"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"],[ns]:["workspaceCards.requestRefresh"],[is]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[ss]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[as]:["account.getCurrentUserId","account.onChange","network.request"],[os]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[cs]:["account.getCurrentUserId","account.onChange","network.request"],[us]:["account.getCurrentUserId","account.onChange","network.request"],[ds]:["account.getCurrentUserId","account.onChange","network.request"],[ls]:["presentation.setClipboard"],[fs]:["presentation.showShareMenu"],[hs]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ms]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Mr]:["presentation.applyOrientation"],[Es]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[gs]:["presentation.setNavigationBarStyle"],[Kn]:["storage.getRaw"],[Zn]:["storage.setRaw"],[ps]:["network.request"],[Ts]:["network.stream","files.transfer","files.access"],[_s]:["network.upload","files.access"],[As]:["files.external"],[Is]:["files.external"],[bs]:["files.save"],[Xn]:["files.access"],[Jn]:["files.removeFile"],[ys]:["files.access"],[ei]:["files.access"],[Ns]:["files.access"],[ti]:["files.access"],[ws]:["files.access"],[ri]:["files.access"],[Ds]:["files.access"],[ni]:["files.removeDirectory"],[Ss]:["files.access"],[Os]:["files.access"],[ii]:["media.pick"],[$n]:["presentation.showAppreciation"],[Ms]:["presentation.showToast"],[Cs]:["presentation.showLoading"],[Rs]:["presentation.hideLoading"],[Ls]:["presentation.vibrate"],[Ps]:["presentation.setClipboard"],[vs]:["protocol.invoke"],[ks]:["presentation.close"],[xs]:["presentation.reload"],[Us]:["presentation.openAppPage"],[Kt]:["account.getCurrentUserId","account.onChange","network.request"],[Mt]:["account.onChange","network.request"],[ur]:["account.getCurrentUserId","account.onChange","network.request"],[Cr]:["account.getCurrentUserId","account.onChange","network.request"],[zt]:["account.onChange","network.request"],[Jr]:["account.getCurrentUserId","account.onChange","network.request"],[en]:["account.getCurrentUserId","account.onChange","network.request"],[tn]:["account.getCurrentUserId","account.onChange","network.request"],[Rr]:["account.getCurrentUserId","account.onChange","network.request"],[na]:["companion.getInfo"],[ia]:["companion.getPreparationStatus"],[sa]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[aa]:["companion.cancelPreparation"],[oa]:["companion.getActiveSession"],[ca]:["companion.getInfo","companion.launch"],[ua]:["companion.session.write"],[da]:["companion.session.closeStdin"],[la]:["companion.session.terminate"],[fa]:["companion.session.ackOutput"],[ha]:["companion.openAttachment"],[ma]:["companion.showNotification"],[cc]:pr,[ts]:va,[kn]:va,[rs]:[...va,"files.sandbox","files.removeFile","network.stream","files.transfer"],[uc]:[...pr,"presentation.confirmDataPermission"],[dc]:pr,[lc]:pr,[fc]:[...pr,"presentation.openDataPermissions"],[hc]:pr},ZE=new Set([$n]);function Xl(e,t){if(t[e]!==!0)throw ZE.has(e)?Le("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):Nt(e)}const XE=32*1024*1024,JE=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function eg(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 a;try{const c=await t(s.body,{maxBytes:XE},i);return tg(s,c)}catch(c){throw a=c,c}finally{try{await r.release(s.body)}catch(c){if(a===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:rg(t,ig(e,"content-type"))}}function rg(e,t){ng(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||!JE.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function ng(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 ce(e){return typeof e=="function"}function lu(e){return(...t)=>{throw Nt(e)}}function Ye(e){return async(...t)=>{throw Nt(e)}}const sg=(e,t)=>{},ag=()=>()=>{};function og(e){const t={request:ce(e.network?.request)?e.network.request.bind(e.network):Ye("network.request")},r={...ce(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:ce(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):Ye("account.getCurrentUserId"),ensureAuthenticated:ce(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Ye("account.ensureAuthenticated"),onChange:ce(e.account?.onChange)?e.account.onChange.bind(e.account):ag},n={...e.storage?.withLock?{withLock:e.storage.withLock.bind(e.storage)}:{},getRaw:ce(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Ye("storage.getRaw"),setRaw:ce(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Ye("storage.setRaw")},i={...ce(e.presentation?.showSteamLoginRequired)?{showSteamLoginRequired:e.presentation.showSteamLoginRequired.bind(e.presentation)}:{},...ce(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...ce(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:ce(e.presentation?.close)?e.presentation.close.bind(e.presentation):Ye("presentation.close"),reload:ce(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Ye("presentation.reload"),openAppPage:ce(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Ye("presentation.openAppPage"),openWindow:ce(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Ye("presentation.openWindow"),getViewportMetrics:ce(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):lu("presentation.getViewportMetrics"),getNavigationBarHeight:ce(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):lu("presentation.getNavigationBarHeight"),setNavigationBarStyle:ce(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Ye("presentation.setNavigationBarStyle"),showShareMenu:ce(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Ye("presentation.showShareMenu"),setScreenshotChromeHidden:ce(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):sg,supportsLongScreenshot:e.presentation?.supportsLongScreenshot===!0,captureAndShare:ce(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Ye("presentation.captureAndShare"),openPostCommentEditor:ce(e.presentation?.openPostCommentEditor)?e.presentation.openPostCommentEditor.bind(e.presentation):void 0,showAppreciation:ce(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw Le("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:ce(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Ye("presentation.showToast"),showLoading:ce(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Ye("presentation.showLoading"),hideLoading:ce(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Ye("presentation.hideLoading"),vibrate:ce(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Ye("presentation.vibrate"),setClipboard:ce(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Ye("presentation.setClipboard")},s=ce(e.storageDiagnostics?.listRaw)?{listRaw:e.storageDiagnostics.listRaw.bind(e.storageDiagnostics)}:void 0,a=Object.fromEntries(["getInfo","getPreparationStatus","prepare","cancelPreparation","getActiveSession","launch","write","closeStdin","terminate","ackOutput","openAttachment","showNotification"].map(u=>[u,ce(e.companion?.[u])?e.companion[u].bind(e.companion):Ye(`companion.${u}`)]));ce(e.companion?.onSessionEvent)&&(a.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const c={invoke:ce(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:a,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 cg(e,t={}){const r=ug(e.files?.sandbox),n=ce(e.picker?.pickFiles)&&ce(e.picker?.pickDirectory),i=ce(e.picker?.saveFile),s=r||n||i||ce(e.companion?.openAttachment),a=r?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":ce(e.account?.getAccountKey),"account.getCurrentUserId":ce(e.account?.getCurrentUserId),"account.ensureAuthenticated":ce(e.account?.ensureAuthenticated),"account.onChange":ce(e.account?.onChange),"network.request":ce(e.network?.request),"network.stream":ce(e.transfer?.network.open)&&ce(e.transfer?.network.release),"network.upload":ce(e.transfer?.upload?.upload),"files.sandbox":r,"files.external":n,"files.save":i,"files.access":s,"files.removeFile":ce(a?.remove),"files.removeDirectory":ce(e.files?.sandbox.remove),"files.transfer":ce(e.transfer?.files.writeResource),"media.pick":ce(e.media?.pick),"storage.getRaw":ce(e.scopedStorage?.get)||ce(e.storage?.getRaw),"storage.setRaw":ce(e.scopedStorage?.set)||ce(e.storage?.setRaw),"presentation.close":ce(e.presentation?.close),"presentation.reload":ce(e.presentation?.reload),"presentation.openAppPage":ce(e.presentation?.openAppPage),"presentation.applyOrientation":ce(e.presentation?.applyOrientation),"presentation.openWindow":ce(e.presentation?.openWindow),"presentation.getViewportMetrics":ce(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":ce(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":ce(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":ce(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":ce(e.presentation?.captureAndShare),"presentation.openPostCommentEditor":ce(e.presentation?.openPostCommentEditor),"presentation.showAppreciation":ce(e.presentation?.showAppreciation),"presentation.showToast":ce(e.presentation?.showToast),"presentation.showLoading":ce(e.presentation?.showLoading),"presentation.hideLoading":ce(e.presentation?.hideLoading),"presentation.vibrate":ce(e.presentation?.vibrate),"presentation.setClipboard":ce(e.presentation?.setClipboard),"workspaceCards.requestRefresh":ce(e.workspaceCards?.requestRefresh),"companion.getInfo":ce(e.companion?.getInfo),"companion.getPreparationStatus":ce(e.companion?.getPreparationStatus),"companion.prepare":ce(e.companion?.prepare),"companion.cancelPreparation":ce(e.companion?.cancelPreparation),"companion.getActiveSession":ce(e.companion?.getActiveSession),"companion.launch":ce(e.companion?.launch),"companion.session.write":ce(e.companion?.write),"companion.session.closeStdin":ce(e.companion?.closeStdin),"companion.session.terminate":ce(e.companion?.terminate),"companion.session.ackOutput":ce(e.companion?.ackOutput),"companion.openAttachment":ce(e.companion?.openAttachment),"companion.showNotification":ce(e.companion?.showNotification),"protocol.invoke":ce(e.protocol?.invoke),"presentation.confirmDataPermission":t.hasUserDataPresentation===!0,"presentation.openDataPermissions":t.hasUserDataSettings===!0}}function ug(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&ce(t.file)&&ce(t.directory)&&ce(t.create)&&ce(t.stat)&&ce(t.list)}function fu(e,t){return t?.[e]!==!1}function dg(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function Jl(e,t={}){const r={};for(const n of Object.keys(du)){const s=du[n].every(c=>e[c]),a=!dg(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=fu(n,t.callerCapabilities)&&fu(n,t.hostCapabilities)&&s&&a}return r}function ef(e={},t={}){const r=cg(e,t),n=Jl(r,t);return{ports:og(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function ke(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]):lg(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function lg(e,t){const r=new AbortController,n=()=>{e.removeEventListener("abort",s),t.removeEventListener("abort",a)},i=c=>{r.signal.aborted||(n(),r.abort(c.reason))},s=()=>i(e),a=()=>i(t);return e.aborted?i(e):t.aborted?i(t):(e.addEventListener("abort",s,{once:!0}),t.addEventListener("abort",a,{once:!0})),r.signal}function fg(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 hg=4,mg=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Eg=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),gg=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],pg=["/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 Tg(e,t){const r=Ig(e);return r===null||hu(r,gg)?!0:t&&hu(r,pg)}function _g(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return mg.some(r=>t===r||t.endsWith(`.${r}`))}function Ag(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||Eg.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Ig(e){let t=e;for(let r=0;r<hg;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 hu(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 bg(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 tf(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw ka("网络策略格式无效");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 ka("网络策略格式无效");const n=new Set;for(const i of r){const s=bg(i&&typeof i=="object"?i.domain:void 0);if(!s)throw ka("网络策略包含无效域名");n.add(s)}return Object.freeze({revision:t.revision,enforcement:t.enforcement,entries:Object.freeze([...n].sort().map(i=>Object.freeze({domain:i})))})}function ka(e){return Object.assign(new TypeError(e),{code:"NETWORK_POLICY_INVALID"})}function Eu(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(ji());let n;try{n=e()}catch(i){return Promise.reject(Eu(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(ji())):new Promise((i,s)=>{let a=!1;const c=d=>{a||(a=!0,t.removeEventListener("abort",u),d())},u=()=>c(()=>s(ji()));t.addEventListener("abort",u,{once:!0}),Promise.resolve(n).then(d=>c(()=>i(d)),d=>c(()=>s(Eu(d))))})}async function yg(e,t,r){Ce(r);const i=e.ownerDocument.defaultView;if(!i||!e.isConnected)throw new Error("长图容器不可用");const s=e.getAttribute("style"),a=i.scrollX,c=i.scrollY,u=e.getBoundingClientRect().width,d=()=>{s===null?e.removeAttribute("style"):e.setAttribute("style",s),i.scrollTo(a,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(h=>i.requestAnimationFrame(()=>i.requestAnimationFrame(()=>h()))),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 h=e.parentElement;h;h=h.parentElement){const f=i.getComputedStyle(h),E=h.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(f.overflowY)&&(l.top+t.top<E.top-1||l.top+t.top+t.height>E.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 Ng(e,t,r,n=1e4){const i=new AbortController;return new Promise((s,a)=>{let c=!1;const u=h=>{c||(c=!0,clearTimeout(l),r.signal.removeEventListener("abort",d),i.abort(h),a(h))},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(h=>{if(typeof h!="function"){u({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 未完成严格网络策略初始化"});return}if(c){try{h()}catch{}return}c=!0,clearTimeout(l),s(()=>{r.signal.removeEventListener("abort",d),i.abort(),h()})},u)})}function rf(e,t){return wg(t)??Dg(e.pathname)}function wg(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Dg(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const Sg=2,nf="allow-scripts allow-same-origin allow-pointer-lock",Og="",Mg="no-referrer";function Cg(e=nf){return!e.split(/\s+/).includes("allow-same-origin")}function gu(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Rg=new Set(["javascript:","data:","blob:","file:"]),pu="xiaoheihe.cn";function Lg(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(Rg.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!vg(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Pg(e,t){const r=new URL(e);return r.searchParams.set(Nl,t),r.toString()}function sf(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const s=rf(n,r);return i.pathname.startsWith(s)}catch{return!1}}function Tu(e){const t=new URL(e);return _c(t)?"loopback":Ac(t)?"lan":"production"}function vg(e,t,r){return kg(e)||_c(e)||Ac(e)&&Ug(t,r)}function kg(e){return e.protocol==="https:"&&Fg(e.hostname)}function _c(e){return e.protocol==="http:"&&xg(e.hostname)}function xg(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Ac(e){return e.protocol==="http:"&&Bg(e.hostname)}function Ug(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return _c(r)||Ac(r)}catch{return!1}}function Bg(e){const t=Hg(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Hg(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 Fg(e){return e===pu||e.endsWith(`.${pu}`)}function zg(e){let t,r=!1,n=!1;const i=new URL(e.launchUrl).origin,s=a=>{const c=a.data;if(n||!e.iframe.contentWindow||a.source!==e.iframe.contentWindow||a.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||!sf(e.launchUrl,c.href,e.locationBasePath))return;const u=new URL(c.href);if(!(u.username||u.password||u.searchParams.get(Nl)!==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 af(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 a=ra.includes(n)?"read":Wn.includes(n)?"write":void 0;if(!a||s.config[a]!==!0)return{allowed:!1,code:"PERMISSION_DENIED",message:`关联帖子未声明 ${a??n} 权限`,data:{permission:i,method:n}}}}return{allowed:!0}}}function jg(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 Vg(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Gg=1e3;function Yg(e,t=Vg()){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<=Gg}const Qg="runtime.gate.probe",of=new Set(dr.map(e=>e.method));class qg{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=yl;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:Dl,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{const i=navigator.userActivation;if(i==null){this.handleRequest(r,this.iframe.isConnected&&document.visibilityState==="visible");return}n=Yg(this.iframe,{activeElement:document.activeElement,userActivation:i,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&&m0(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:wl,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===Qg){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,Le("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!of.has(t.method)){this.postResponse(t,void 0,Le("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,Le("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=Hs(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})||!Wg(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 Wg(e){return typeof e=="string"&&of.has(e)}function p(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function he(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ic(){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 cf(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?(a,c)=>e.create(a,c):po,remove:s?a=>e.remove(a):df,read:a=>e.read(a),...typeof e.readPrefix=="function"?{readPrefix:(a,c)=>e.readPrefix(a,c)}:{},write:i?(a,c)=>e.write(a,c):po,stat:a=>e.stat(a)})}function uf(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",s=r.allowRemove!==!1,a=s&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:n,file:c=>cf(e.file(c),n,{allowRemove:s}),directory:c=>uf(e.directory(c),n,{allowRemove:s}),create:i?(c,u)=>e.create(c,u):po,remove:a?(c,u)=>e.remove(c,u):df,stat:c=>e.stat(c),list:(c,u)=>e.list(c,u)})}function po(){return Promise.reject(p("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function df(){return Promise.reject(p("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const $g=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"]),Kg={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 nn(e){const t=bc(e),r=t&&$g.has(t)?p(t,Kg[t]??"文件操作失败"):p("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function qt(e){try{return e()}catch(t){throw nn(t)}}function bc(e){try{if(!he(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const _u=1024;class yc{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new yc(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 Di(i.handle,{kind:"file",handleId:s})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const s=qt(()=>{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>_u)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}),a=this.registerMany(s);return s.map((c,u)=>Di(c.handle,{kind:"file",handleId:a[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 Iu(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=Xg(t);if("handleId"in r){const a=this.readDirect(r.handleId,"file");return{ref:r,...a}}const n=this.resolveRoot(r.root),i=ai(r.relativePath);xa(n.origin,i);const s=this.prepareFile(qt(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...s}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Jg(t);if("handleId"in r){const a=this.readDirect(r.handleId,"directory");return{ref:r,...a}}const n=this.resolveRoot(r.root),i=r.relativePath==="."?".":ai(r.relativePath);xa(n.origin,i);const s=this.prepareDirectory(i==="."?n.hostHandle:qt(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...s}}describeFile(t,r){return yu(t),Di(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),qt(()=>{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 a=0;a<i;a+=1){if(!Object.prototype.hasOwnProperty.call(r,a))throw p("FILE_IO_FAILED","Host 返回了稀疏目录列表");const c=r[a];t.origin==="sandbox"&&he(c)&&typeof c.name=="string"&&lf(c.name)||s.push(this.describeListedEntry(t,c))}return this.assertCanonicalDetail(),s})}describeListedEntry(t,r){return qt(()=>{if(he(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Di(n.handle,Au(t.ref,n.handle.name))}if(he(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return Iu(n.handle,Zg(t.ref,n.handle.name))}throw p("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=mi(r);xa(t.origin,n);const i=this.prepareFile(qt(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:Au(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw p("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return qt(()=>{yu(t);const i=n??t.mode;return bu(t.mode,i),{handle:cf(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return qt(()=>{rp(t,i);const s=n??t.mode;return bu(t.mode,s),{handle:uf(t,s,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>_u)throw p("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const s=Ic();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(!ep(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 Nt("files.sandbox");return this.prepareDirectory(qt(()=>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 Nt("files")}}function ai(e){if(!mc(e))throw p("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function xa(e,t){if(e==="sandbox"&&lf(t))throw p("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function lf(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function mi(e,t="文件名"){const r=ai(e);if(r.includes("/"))throw p("INVALID_PARAMS",`${t} 只能是 basename`);return r}function Au(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:ai(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Zg(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:ai(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Di(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function Iu(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function bu(e,t){if(t==="readwrite"&&e!=="readwrite")throw p("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Xg(e){return Dr(e)||ff(),e}function Jg(e){return Ol(e)||ff(),e}function ff(){throw p("INVALID_PARAMS","文件引用不合法")}function ep(e){return/^[0-9a-f]{32}$/.test(e)}function tp(e){return he(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 yu(e){if(!tp(e))throw p("FILE_IO_FAILED","Host 返回了无效 File handle");mi(e.name,"Host File name")}function rp(e,t=!1){if(!he(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&&mi(e.name,"Host Directory name")}const np=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"]),sp=new Set(["range","if-range","a-im"]),ap=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"]),op=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Si={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class cp{constructor(t){this.signal=t}phase="initial";transition(t){if(Si[t]<=Si[this.phase])throw p("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Si[this.phase]<Si.committed&&this.signal.aborted)throw Ef()}normalizeHostError(t,r){return this.throwIfCancelled(),wc(t,r,this.signal)}}async function hf(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Nt("network.download");const s=ke(r.operationContext,t.signal),a=new cp(s.signal);a.transition("target"),a.throwIfCancelled();let c;try{c=await fp(e,i,s)}catch(l){throw a.normalizeHostError(l,"file")}a.throwIfCancelled();let u;a.transition("open");try{u=await n.network.open(e.request,s)}catch(l){throw a.normalizeHostError(l,"network")}let d=!1;try{a.throwIfCancelled(),a.transition("validate");const l=mp(u);Ep(u,l);const h=gp(u.status,l);if(e.maxBytes!==void 0&&h.expectedBytes!==void 0&&h.expectedBytes>e.maxBytes)throw p("FILE_TOO_LARGE","下载响应超过 maxBytes");a.throwIfCancelled();const f=hp(e,c,l,i);let E=0;const g=dp(h.expectedBytes,e.maxBytes);Ba(t,Ua(0,h));const b={...s,onProgress(w){!Number.isSafeInteger(w)||w<E||g!==void 0&&w>g||(E=w,Ba(t,Ua(E,h)))}};a.transition("transfer"),d=!0;let N;try{N=await n.files.writeResource(f.hostHandle,u.body,{mode:f.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...h.expectedBytes===void 0?{}:{expectedBytes:h.expectedBytes}},b)}catch(w){throw a.normalizeHostError(w,"transfer")}a.transition("committed"),E=up(N,h,E,e.maxBytes),Ba(t,Ua(E,h));const y=i.describeFile(f.handle,f.ref);return a.transition("completed"),y}finally{d||lp(n.network,u.body)}}function up(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 dp(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function lp(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function fp(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return To(i.handle.mode),await yp(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return To(n.handle.mode),await Np(n.handle,r),{kind:"directory",...n}}function hp(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Tp(e,r),s=n.deriveFile(t,i);return To(s.handle.mode),{...s,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function mp(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(!he(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()||!np.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 Ep(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:bp(t,ip)});if((t["content-range"]?.length??0)>0)throw p("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function gp(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,a=pp(t["content-encoding"]),c=e===204||e===205?0:n.length===0&&a?s:void 0,u=c!==void 0;return{...c===void 0?{}:{expectedBytes:c},...u?{total:c}:{},lengthComputable:u}}function pp(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Ua(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Ba(e,t){try{e.postProgress(t)}catch{}}function Tp(e,t){const r=t["content-disposition"]??[];for(const i of r){const s=_p(i);if(s&&Vi(s))return s}for(const i of r){const s=Ap(i);if(s&&Vi(s))return s}if(e.suggestedName!==void 0)return Nc(e.suggestedName);const n=Ip(e.url);return n&&Vi(n)?n:"download.bin"}function _p(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 Ap(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 Ip(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Nc(e){try{mi(e,"suggestedName")}catch{throw p("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Vi(e))throw p("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Vi(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||op.test(e))}function bp(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function yp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw mf()}catch(r){throw wc(r,"file",t.signal)}}async function Np(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw mf()}catch(r){throw wc(r,"file",t.signal)}}function To(e){if(e!=="readwrite")throw p("FILE_ACCESS_DENIED","下载目标只允许读取")}const wp={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 wc(e,t,r){if(r.aborted)return Ef();const n=Dp(e);if(n&&ap.has(n)){const s=p(n,wp[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 Dp(e){return he(e)&&typeof e.code=="string"?e.code:void 0}function mf(){return p("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Ef(){return p("DOWNLOAD_CANCELLED","下载已取消")}function Sp(e){if(!e)return;const t=Object.keys(e).find(r=>sp.has(r.trim().toLowerCase()));if(t)throw p("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Nu=8*1024*1024,Op=32*1024*1024;function Dc(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 a=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>Nu)throw p("FILE_TOO_LARGE","存档文件超过 8 MiB");const h={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:c.download_url},timeout:6e4};if(!$l(h)||new URL(c.download_url).pathname!==`/cloud_archive/${l.file_id}.zip`||c.expires_at<=Date.now())throw p("INVALID_RESPONSE","存档下载地址无效");a(d);const f=Math.min(Nu,Op-r);if(f<=0)throw p("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达上限");const E=e.files.sandbox.file(`.hb-game-saves/${Ic()}.zip`);if(!E.remove)throw p("REQUEST_UNSUPPORTED","宿主不支持私有存档清理");r+=f;let g=!1;try{await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},d),await E.create({recursive:!0,exclusive:!0},d);const b=e.registry.createTransferScope();try{const I=b.registerFile(E,"game-save","readwrite");await hf({request:h,url:new URL(c.download_url),to:I.ref,targetKind:"file",maxBytes:f},{...d,trustedUserGesture:!1,postEvent:()=>{},postProgress:()=>{}},{transfer:e.transfer,fileRegistry:b,operationContext:d})}finally{b.dispose()}a(d);const N=(await E.stat(d)).size;if(!Number.isSafeInteger(N)||N<0||N>f)throw p("FILE_TOO_LARGE","存档实际大小超过限额");await u(d),a(d);const y=async()=>{throw p("FILE_ACCESS_DENIED","存档文件只读")},w={kind:"file",mode:"read",name:l.name,create:y,write:y,async read(I){a(I),await u(I);const x=await E.read(I);try{if(a(I),await u(I),x.byteLength!==N)throw p("INVALID_RESPONSE","私有存档副本长度不匹配");return x}catch(V){throw x.fill(0),V}},async stat(I){return a(I),await u(I),await E.stat(I),a(I),await u(I),{kind:"file",size:N,...typeof l.modified_at=="number"&&Number.isSafeInteger(l.modified_at)?{modifiedAt:l.modified_at}:{}}}};return r-=f-N,t.set(w,{target:E,size:N}),g=!0,w}finally{g||(r-=f,await i(E))}}}}const Mp=/^(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 Cp(e){if(!e?.minimumSdkVersion)throw Le("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=br(e.minimumSdkVersion),r=e.sdkVersion?br(e.sdkVersion):void 0;if(!t)throw Le("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw Le("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=br("0.6.0");if(!r){if(Gi(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw Le("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0&&e.allowPublicPrerelease!==!0)throw Le("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(Gi(r,t)<0)throw Le("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Gi(r,br("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Rp(e,t){if(typeof t!="string"||!br(t))throw Le("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw Le("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function Ta(e,t){const r=br(e),n=br(t);if(!(!r||!n))return Gi(r,n)}function br(e){const t=Mp.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 Gi(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 Lp(e){return{[$n]:async(t,r)=>{const n=ke(e.operationContext,r.signal);if(Ce(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 wu(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function gf(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,s=new Map,a=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 h(b,N){return b.flatMap((y,w)=>{const I=JSON.stringify(b.slice(0,w+1));return[JSON.stringify([I]),JSON.stringify([I,N])]})}function f(b,N){return JSON.stringify(h(b,N).map(y=>n.get(y)??0))}async function E(b,N){const y=l(b),w=JSON.stringify([JSON.stringify(y),...N?[N]:[]]),I=(n.get(w)??0)+1;n.set(w,I),i.add(w);for(const x of c)x(y,N);if(!e.store){i.delete(w),d(N??"*","invalidation");return}try{await e.store.invalidate(y,N)}catch(x){throw d(N??"*","storage_error"),x}n.get(w)===I&&i.delete(w),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}),w=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)}),I=b.namespace;for(const P of[y.ttlMs,y.memoryMaxEntries,y.diskMaxEntries,y.diskMaxBytes,y.maxEntryBytes])if(!Number.isFinite(P)||P<0)throw new Error("Invalid runtime cache policy");const x=new Map,V=new Map,M=new Map;let R=!1;function L(P,C,Q){if(u||R||P.aborted||f(C,I)!==Q)throw Hr()}function Y(P){return y.ttlMs>0&&y.persistence==="memory-and-disk"&&!!e.store&&!h(P,I).some(C=>i.has(C))}function j(P,C,Q){const S=t();return P.envelopeVersion===1&&JSON.stringify(P.address)===JSON.stringify(C)&&wu(P.revisions,Q)&&P.payload.byteLength<=y.maxEntryBytes&&Number.isFinite(P.cachedAt)&&Number.isFinite(P.expiresAt)&&P.cachedAt<=S&&P.cachedAt>=0&&P.expiresAt>P.cachedAt&&Math.min(P.expiresAt,P.cachedAt+y.ttlMs)>S}function ee(P,C,Q,S,q){if(!(y.ttlMs<=0||y.memoryMaxEntries<1)){for(const[W,Z]of x)Math.min(Z.entry.expiresAt,Z.entry.cachedAt+y.ttlMs)<=t()&&x.delete(W);for(x.delete(P);x.size>=Math.floor(y.memoryMaxEntries);){const W=x.keys().next();if(W.done)break;x.delete(W.value)}x.set(P,{entry:C,value:Q,epoch:S,persistent:q})}}async function k(P,C,Q,S){const q={namespace:I,codecVersion:w.version,scopeIds:C,key:P.key},W=JSON.stringify(q);let Z=[],se=Y(C);if(se)try{Z=await e.store.readRevisions(C,I)}catch{se=!1,d(I,"storage_error")}L(S.signal,C,Q);async function de(){if(!se)return!0;try{return wu(Z,await e.store.readRevisions(C,I))}catch{return se=!1,d(I,"storage_error"),!1}}const Ie=x.get(W);if(y.ttlMs>0&&Ie&&Ie.epoch===Q&&j(Ie.entry,q,Z)&&Ie.persistent===se&&await de())return L(S.signal,C,Q),d(I,"memory_hit"),Ie.value;if(x.delete(W),se){let _,B;try{_=await e.store.read(q,y.maxEntryBytes),_&&j(_,q,Z)?B=w.decode(_.payload):_=void 0}catch{_=void 0,d(I,"storage_error")}if(L(S.signal,C,Q),_&&await de())return L(S.signal,C,Q),ee(W,_,B,Q,!0),d(I,"disk_hit"),B}d(I,"miss");const Re=w.validate(await P.load(S.signal));L(S.signal,C,Q);const Ue=w.clone(Re);if(!await de()&&se)throw Hr();if(L(S.signal,C,Q),y.ttlMs>0){const _=t();let B;try{B=w.encode(Ue)}catch{return Ue}const K={envelopeVersion:1,address:q,revisions:se?Z:[],cachedAt:_,expiresAt:_+y.ttlMs,payload:B};if(se&&B.byteLength<=y.maxEntryBytes){let J=!0,Ee=!1;try{J=await e.store.publish(K,y),Ee=J}catch{d(I,"storage_error")}if(L(S.signal,C,Q),!J)throw Hr();Ee&&d(I,"published")}L(S.signal,C,Q),ee(W,K,Ue,Q,se)}return Ue}async function z(P){if(u||R||P.signal?.aborted)return Promise.reject(Hr());const C=l(P.scope),Q=f(C,I);let S;if(Y(C)){const se=new AbortController;M.set(se,C);const de=()=>se.abort();P.signal?.addEventListener("abort",de,{once:!0});let Ie=()=>{};try{S=await Promise.race([e.store.readRevisions(C,I),new Promise((Re,Ue)=>{const _=()=>Ue(Hr());se.signal.addEventListener("abort",_,{once:!0}),Ie=()=>se.signal.removeEventListener("abort",_)})])}catch{se.signal.aborted||d(I,"storage_error")}finally{Ie(),M.delete(se),P.signal?.removeEventListener("abort",de)}}L(P.signal??new AbortController().signal,C,Q);const q=JSON.stringify([C,P.key,Q,S]);let W=V.get(q);if(W?.controller.signal.aborted&&(W=void 0),!W){const se=new AbortController;W={ids:C,controller:se,waiters:0,promise:Promise.resolve(void 0)};const de=W;de.promise=k(P,C,Q,se).finally(()=>{V.get(q)===de&&V.delete(q)}),V.set(q,de)}const Z=W;return Z.waiters+=1,new Promise((se,de)=>{let Ie=!1;function Re(_){Ie||(Ie=!0,P.signal?.removeEventListener("abort",Ue),Z.controller.signal.removeEventListener("abort",Ue),Z.waiters-=1,Z.waiters===0&&Z.controller.abort(),_())}function Ue(){Re(()=>de(Hr()))}P.signal?.addEventListener("abort",Ue,{once:!0}),Z.controller.signal.addEventListener("abort",Ue,{once:!0}),Z.promise.then(_=>Re(()=>{try{L(P.signal??new AbortController().signal,C,Q),se(w.clone(_))}catch(B){de(B)}}),_=>Re(()=>de(_)))})}function F(P,C){if(C&&C!==I)return;const Q=S=>P.every((q,W)=>S[W]===q);for(const[S,q]of x)Q(q.entry.address.scopeIds)&&x.delete(S);for(const[S,q]of V)Q(q.ids)&&(q.controller.abort(),V.delete(S));for(const[S,q]of M)Q(q)&&S.abort()}function U(){if(!R){R=!0,x.clear();for(const P of M.keys())P.abort();M.clear();for(const P of V.values())P.controller.abort();V.clear(),a.delete(U),c.delete(F),s.get(I)?.cache===H&&s.delete(I)}}const H={read:z,invalidateScope:P=>E(P,I),dispose:U};return a.add(U),c.add(F),s.set(I,{definition:{namespace:I,codec:w,policy:y},sourceCodec:b.codec,cache:H}),H}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=>E(b),dispose(){if(!u){u=!0;for(const b of[...a])b();s.clear(),n.clear(),i.clear()}}}}function Pp(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 vp=".hb-runtime-cache-v1",kp=1e3,Ha=64*1024,Fr=1e3,xp=2048,An=32*1024*1024,Up=1024,Yi=new TextEncoder,Du=new TextDecoder("utf-8",{fatal:!0});function In(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Oi(e){const t=await globalThis.crypto.subtle.digest("SHA-256",Yi.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function kt(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Su(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function Bp(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function Ou(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function Hp(e,t){const r=e.sandbox.directory(vp),n=r.directory("revisions"),i=r.directory("entries");for(const k of[r,n,i,i.directory("capability-check")])Ou(k,["directory","file","create","stat","list","remove"]),Ou(k.file("capability-check"),["create","stat","read","write","remove"]);const s=new AbortController,a=()=>s.abort();t.signal.aborted?a():t.signal.addEventListener("abort",a,{once:!0});const c={...t,signal:s.signal};let u=Promise.resolve(),d;function l(k){d=k,s.abort(),t.signal.removeEventListener("abort",a)}function h(k){if(Bp(k))throw l(k),k}function f(){if(d)throw d;if(c.signal.aborted)throw In()}function E(k,z=c.signal){const F=u.then(()=>{if(z.aborted)throw d??In();return f(),k()},()=>{if(z.aborted)throw d??In();return f(),k()}).catch(C=>{throw h(C),C});if(u=F.catch(()=>{}),z.aborted)return Promise.reject(d??In());let U=()=>{};const H=new Promise((C,Q)=>{const S=()=>Q(d??In());z.addEventListener("abort",S,{once:!0}),U=()=>z.removeEventListener("abort",S)}),P=setTimeout(()=>{l(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},kp);return Promise.race([F,H]).finally(()=>{clearTimeout(P),U()})}async function g(){f(),await n.create({recursive:!0,exclusive:!1},c),f(),await i.create({recursive:!0,exclusive:!1},c),f()}async function b(k,z){const F=n.file(`${await Oi([k,z??null])}.revision`);await y(F);let U=!1;try{await F.create({recursive:!1,exclusive:!0},c),U=!0}catch(C){h(C),f()}if(U){const C=Su();return await F.write(Yi.encode(C),c),f(),C}const H=await F.stat(c);if(H.size<1||H.size>128)throw new Error("缓存 revision 文件损坏");const P=Du.decode(await F.read(c));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(P))throw new Error("缓存 revision 文件损坏");return f(),P}async function N(k){const z=await k.list({limit:Fr},c);if(z.length>=Fr)throw new Error("缓存目录超过治理上限");return z}async function y(k){try{await k.stat(c);return}catch(F){if(!Mi(F))throw F}if((await N(n)).length>=Fr-1)throw new Error("缓存 metadata 超过治理上限")}async function w(k,z){await g();const F=[];for(let U=0;U<k.length;U+=1){const H=k.slice(0,U+1);F.push(await b(H),await b(H,z))}return F}async function I(k){return r.directory(`entries/${await Oi([k.namespace,k.codecVersion,k.scopeIds])}`)}async function x(k){return(await I(k)).file(`${await Oi(k.key)}.cache`)}async function V(k,z){const F=await k.stat(c);if(F.size<5||F.size>z+Ha+4)throw new Error("缓存条目超过大小限制");const U=await k.read(c);if(f(),U.length!==F.size)throw new Error("缓存条目读取不完整");const H=new DataView(U.buffer,U.byteOffset,U.byteLength).getUint32(0);if(H<1||H>Ha||H+4>U.length)throw new Error("缓存信封损坏");const P=JSON.parse(Du.decode(U.subarray(4,H+4))),C=U.slice(H+4);if(P.envelopeVersion!==1||!P.address||!Array.isArray(P.address.scopeIds)||!P.address.scopeIds.every(Q=>typeof Q=="string")||typeof P.address.namespace!="string"||typeof P.address.codecVersion!="string"||typeof P.address.key!="string"||!Array.isArray(P.revisions)||P.revisions.length!==P.address.scopeIds.length*2||!P.revisions.every(Q=>typeof Q=="string"&&Q.length>0)||!Number.isSafeInteger(P.cachedAt)||!Number.isSafeInteger(P.expiresAt)||P.cachedAt<0||P.expiresAt<=P.cachedAt||P.payloadBytes!==C.length||C.length>z)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:P.address,revisions:P.revisions,cachedAt:P.cachedAt,expiresAt:P.expiresAt,payload:C}}async function M(k){if(!k.remove)throw new Error("Host 不支持缓存文件删除");await k.remove(c)}async function R(k){try{if((await k.file.stat(c)).size!==k.size)return!1;const z=await V(k.file,An);return!kt(z.address,k.entry.address)||!kt(z.revisions,k.entry.revisions)||z.cachedAt!==k.entry.cachedAt||z.expiresAt!==k.entry.expiresAt||!kt(await L(z.payload),await L(k.entry.payload))?!1:(await M(k.file),!0)}catch(z){if(Mi(z))return!0;throw z}}async function L(k){const z=await globalThis.crypto.subtle.digest("SHA-256",k);return Array.from(new Uint8Array(z),F=>F.toString(16).padStart(2,"0")).join("")}async function Y(){const k=await N(n);let z=0;for(const P of k)if(P.kind==="file"&&(z+=(await P.stat(c)).size,z>An))throw new Error("缓存扫描超过字节上限");const F=[];let U=0,H=z;for(const P of await N(i)){if(P.kind!=="directory")throw new Error("缓存目录结构损坏");for(const C of await N(P)){if(C.kind!=="file"||++U>xp)throw new Error("缓存文件超过治理上限");const Q=(await C.stat(c)).size;if(H+=Q,H>An)throw new Error("缓存扫描超过字节上限");try{const S=await V(C,An);F.push({file:C,entry:S,size:(await C.stat(c)).size,bucketName:P.name})}catch(S){h(S),f(),Mi(S)||await M(C)}}}return{entries:F,metadataBytes:z}}async function j(){for(const k of await N(i))if(k.kind==="directory"&&k.remove&&(await N(k)).length===0)try{await k.remove({recursive:!1},c)}catch(z){h(z),f()}}function ee(k){const{payload:z,...F}=k,U=Yi.encode(JSON.stringify({...F,payloadBytes:z.length}));if(U.length>Ha)throw new Error("缓存信封过大");const H=new Uint8Array(4+U.length+z.length);return new DataView(H.buffer).setUint32(0,U.length),H.set(U,4),H.set(z,U.length+4),H}return{readRevisions:(k,z)=>E(()=>w(k,z)),read:(k,z)=>E(async()=>{f();const F=await x(k);let U;try{U=await V(F,z)}catch(H){if(f(),Mi(H))return;throw H}if(!(!kt(U.address,k)||U.expiresAt<=Date.now())&&kt(U.revisions,await w(k.scopeIds,k.namespace)))return U}),publish:(k,z)=>E(async()=>{f();const{address:F}=k;if(!kt(k.revisions,await w(F.scopeIds,F.namespace)))return!1;const U=ee(k);if(k.payload.length>z.maxEntryBytes||U.length>z.diskMaxBytes||z.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await g();const H=await I(F),P=await x(F),C=await Y(),Q=[],S=new Map;for(const Z of C.entries){if(Z.bucketName===H.name&&Z.file.name===P.name)continue;const se=JSON.stringify([Z.entry.address.scopeIds,Z.entry.address.namespace]);let de=S.get(se);if(de||(de=await w(Z.entry.address.scopeIds,Z.entry.address.namespace),S.set(se,de)),Z.entry.expiresAt<=Date.now()||!kt(Z.entry.revisions,de)){if(!await R(Z))throw new Error("缓存治理期间条目已变化")}else Q.push(Z)}Q.sort((Z,se)=>Z.entry.cachedAt-se.entry.cachedAt);function q(){const Z=Q.filter(se=>se.bucketName===H.name);return Q.length+1>Up||U.length+C.metadataBytes+Q.reduce((se,de)=>se+de.size,0)>An||Z.length+1>Math.min(z.diskMaxEntries,Fr-1)||U.length+Z.reduce((se,de)=>se+de.size,0)>z.diskMaxBytes}for(;q();){const Z=Q.filter(Ie=>Ie.bucketName===H.name),de=Z.length+1>Math.min(z.diskMaxEntries,Fr-1)||U.length+Z.reduce((Ie,Re)=>Ie+Re.size,0)>z.diskMaxBytes?Z[0]:Q[0];if(!de||!await R(de))throw new Error("缓存容量不足或条目已变化");Q.splice(Q.indexOf(de),1)}await j();const W=await N(i);if(!W.some(Z=>Z.name===H.name)&&W.length>=Fr-1)throw new Error("缓存目录超过治理上限");if(await H.create({recursive:!0,exclusive:!1},c),!kt(k.revisions,await w(F.scopeIds,F.namespace)))return!1;try{await P.create({recursive:!1,exclusive:!0},c)}catch(Z){h(Z),await P.stat(c)}return await P.write(U,c),f(),kt(k.revisions,await w(F.scopeIds,F.namespace))}),invalidate:(k,z)=>E(async()=>{await g();const F=n.file(`${await Oi([k,z??null])}.revision`);await y(F);try{await F.create({recursive:!1,exclusive:!0},c)}catch(U){h(U),await F.stat(c)}await F.write(Yi.encode(Su()),c),f();try{const{entries:U}=await Y();for(const H of U){if(z!==void 0&&H.entry.address.namespace!==z||!k.every((C,Q)=>H.entry.address.scopeIds[Q]===C))continue;const P=await w(H.entry.address.scopeIds,H.entry.address.namespace);kt(H.entry.revisions,P)||await R(H)}await j()}catch(U){h(U),f()}})}}function Mi(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const Fp="RATE_LIMITED_BY_RUNTIME",zp="RATE_LIMITED",pf=20,Tf=40,_f=150,Af=20,If=1e4,bf=45e3,yf=1,jp=300*1e3,Vp=64;function zr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Gp(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Yp(e={}){const t=e.now??Date.now,r=Gp(e.coalesceWindowMs,_f),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,zr(e.budget?.ratePerSecond,pf)),burst:Math.max(1,Math.floor(zr(e.budget?.burst,Tf)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(zr(e.loopDetection?.maxCalls,Af))),windowMs:Math.max(1,Math.floor(zr(e.loopDetection?.windowMs,If)))},s=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(zr(e.circuitBreaker?.failureThreshold,yf))),openMs:Math.max(1,Math.floor(zr(e.circuitBreaker?.openMs,bf)))},a=new Map,c=new Map,u=new Set,d=new Map,l=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},h={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let f=!1;function E(R){try{e.onReport?.(R)}catch{}}function g(R,L){if(!i)return{exceeded:!1,count:0};const Y=c.get(R)??[],j=L-i.windowMs;let ee=0;for(;ee<Y.length&&Y[ee]<=j;)ee+=1;ee>0&&Y.splice(0,ee);const k=Y.length>=i.maxCalls;return k||(Y.push(L),Y.length>i.maxCalls+1&&Y.splice(0,Y.length-(i.maxCalls+1))),c.set(R,Y),{exceeded:k,count:Y.length}}function b(R){if(!n)return!0;const L=Math.max(0,R-l.updatedAt)/1e3;return l.tokens=Math.min(n.burst,l.tokens+L*n.ratePerSecond),l.updatedAt=R,l.tokens<1?!1:(l.tokens-=1,!0)}function N(R){if(!n)return 0;const L=Math.max(0,R-l.updatedAt)/1e3,Y=Math.min(n.burst,l.tokens+L*n.ratePerSecond);return Math.max(0,Math.ceil((1-Y)/n.ratePerSecond*1e3))}function y(R,L,Y,j,ee){if(!s)return;const k=d.get(L),z=(k?.open?0:k?.failures??0)+1;if(z<s.failureThreshold){d.set(L,{open:!1,openedAt:0,openMs:0,failures:z});return}const F=Math.min(Math.max(s.openMs,j),jp);d.set(L,{open:!0,openedAt:ee,openMs:F,failures:z}),h.circuitOpened+=1,E({type:"circuit_opened",capability:R,endpointId:L,status:Y,openMs:F,timestamp:ee})}function w(R){const L=d.get(R);L&&!L.open&&d.delete(R)}function I(R){for(const[L,Y]of a)!Y.pending&&Y.expiresAt<=R&&a.delete(L);for(;a.size>=Vp;){const L=[...a].find(([,Y])=>!Y.pending);if(!L)break;a.delete(L[0])}}function x(R,L){if(R===void 0)return;const Y=a.get(R);Y?.promise===L&&(Y.pending=!1)}function V(R,L){if(R===void 0)return;a.get(R)?.promise===L&&a.delete(R)}async function M(R){if(f)return R.load();const L=t();if(s){const k=d.get(R.endpointId);if(k?.open){const z=k.openedAt+k.openMs-L;if(z>0)throw h.circuitRejected+=1,E({type:"circuit_rejected",capability:R.capability,endpointId:R.endpointId,retryAfterMs:z,timestamp:L}),Wp("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:R.endpointId,retryAfterMs:z});d.delete(R.endpointId)}}const Y=g(R.endpointId,L);Y.exceeded&&i?u.has(R.endpointId)||(u.add(R.endpointId),E({type:"loop_detected",capability:R.capability,endpointId:R.endpointId,count:Y.count,windowMs:i.windowMs,timestamp:L})):u.delete(R.endpointId);const j=r>0?R.coalesceKey:void 0;if(j!==void 0){const k=a.get(j);if(k&&(k.pending||k.expiresAt>L))return h.coalesced+=1,E({type:"coalesced",capability:R.capability,endpointId:R.endpointId,timestamp:L}),k.promise;k&&a.delete(j)}if(Y.exceeded&&i)throw h.loopRejected+=1,Mu("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:R.capability,endpointId:R.endpointId,count:Y.count,windowMs:i.windowMs});if(!b(L)){h.budgetRejected+=1;const k=N(L);throw E({type:"budget_exhausted",capability:R.capability,endpointId:R.endpointId,retryAfterMs:k,timestamp:L}),Mu("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:R.capability,endpointId:R.endpointId,retryAfterMs:k})}j!==void 0&&I(L);const ee=R.load().then(k=>(x(j,ee),w(R.endpointId),k),k=>{V(j,ee);const z=Qp(k);throw z!==void 0&&y(R.capability,R.endpointId,z,qp(k),L),k});return j!==void 0&&a.set(j,{endpointId:R.endpointId,promise:ee,expiresAt:L+r,pending:!0}),ee}return{execute:M,invalidateCoalescing(R){if(R===void 0){a.clear();return}for(const[L,Y]of a)R.includes(Y.endpointId)&&a.delete(L)},snapshot(){return{...h,openCircuits:[...d.entries()].filter(([,R])=>R.open).map(([R])=>R)}},dispose(){f||(f=!0,a.clear(),c.clear(),u.clear(),d.clear())}}}function Qp(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 qp(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 Mu(e,t){return{code:Fp,message:e,data:t}}function Wp(e,t){return{code:zp,message:e,data:t}}const Nf=3e4,wf=6e4,_o=1440*60*1e3;function $p(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??Nf)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??wf)):0,steamGameListTtlMs:t?Kp(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:pf,burst:Tf},coalesceWindowMs:r?.coalesceWindowMs??_f,loopDetection:r?.loopDetection??{maxCalls:Af,windowMs:If},circuitBreaker:r?.circuitBreaker??{failureThreshold:yf,openMs:bf}}}}function Kp(e){return e===void 0||!Number.isFinite(e)?_o:Math.max(0,Math.floor(e))}function Df(e){return typeof e=="object"&&e!==null}function Sf(e,t){const r=e.data;if(!Df(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 He(e,t){const r=e.data;if(!Df(r)||typeof r.status!="string")throw new Error(t);return r}const Of={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Zp={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}:{},...e.include_first_publish_post_reminder?{include_first_publish_post_reminder:"true"}:{}}},parse(e,t){return He(e,"工坊小程序详情加载失败")}};function Ei(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Xp(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Jp(e){const t=He(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=Xp(r.consent_challenge)),{...t,result:n}}const eT={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=>({...Ei(e.runtimeContext),challenge:e.challenge}),parse:e=>He(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=>Ei(e.runtimeContext),parse:e=>He(e,"小程序授权撤销接口响应异常")},rT={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=>Ei(e.runtimeContext),parse(e){const t=He(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}:{}}}}},nT={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=>({...Ei(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Jp(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=>({...Ei(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=He(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},sT=64;function Mf(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??sT)),n=e.now??Date.now,i=new Map,s=new Map;let a=0,c=!1;function u(h){for(const[f,E]of i)E.expiresAt<=h&&i.delete(f)}function d(h,f,E){if(c||t<=0||E!==a)return;const g=n();for(u(g),i.delete(h);i.size>=r;){const b=i.keys().next();if(b.done)break;i.delete(b.value)}i.set(h,{expiresAt:g+t,value:f})}function l(h,f){if(c)return f();if(t>0){const N=i.get(h);if(N&&N.expiresAt>n())return Promise.resolve(N.value);N&&i.delete(h)}const E=s.get(h);if(E)return E;const g=a,b=f().then(N=>(d(h,N,g),N)).finally(()=>{s.get(h)===b&&s.delete(h)});return s.set(h,b),b}return{read:l,invalidate(){a+=1,i.clear(),s.clear()},dispose(){c||(c=!0,a+=1,i.clear(),s.clear())},get size(){return i.size}}}function aT(e,t){return t?e?"server":"local":"legacy"}function oT(e,t){if(e==="local")throw p("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const cT=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],uT=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),dT=/authorization|cookie|pkey|password|secret|token/i,Cf=/authorization|cookie|pkey|token|password|secret/i;function xt(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function lT(e){for(const t of Object.keys(e))if(!uT.has(t))throw new qe(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of cT)if(Object.prototype.hasOwnProperty.call(e,t)&&xt(e,t)!==void 0)throw new qe(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(xt(e,"bodyEncoding")!==void 0&&xt(e,"bodyEncoding")!=="json"&&xt(e,"bodyEncoding")!=="form")throw new qe("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(xt(e,"failurePresentation")!==void 0&&xt(e,"failurePresentation")!=="none")throw new qe("endpoint failurePresentation 必须为 none");if(xt(e,"auth")!==void 0&&xt(e,"auth")!=="none"&&xt(e,"auth")!=="optional"&&xt(e,"auth")!=="required")throw new qe("endpoint auth 必须为 none、optional 或 required")}function Fs(e){if(Array.isArray(e))return e.map(Fs);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))dT.test(n)||(r[n]=Fs(i));return r}function Cu(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Cf.test(r)||(t[r]=n);return t}function fT(e){if(!e)return;const t=Object.keys(e).find(r=>Cf.test(r));if(t)throw new qe(`endpoint 禁止声明 credential-bearing header: ${t}`)}class gi 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 Ru=1440*60*1e3,hT=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function mT(e,t=Date.now){if(!e)return;const r=Object.entries(e).find(([a])=>a.trim().toLowerCase()==="retry-after")?.[1];if(typeof r!="string"||!r.trim())return;const n=r.trim();if(/^\d+$/.test(n)){const a=Number(n)*1e3;return a>0?Math.min(a,Ru):void 0}if(!hT.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const s=i-t();return s>0?Math.min(s,Ru):void 0}function ET(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 Rf(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class sn extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Rf(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class pi extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Rf(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function gT(e,t,r,n,i,s,a,c){return{config:{auth:e.auth,body:Fs(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:a.credentials,headers:Cu(s),method:e.method,metadata:{endpointId:e.id},query:Fs(n),timeout:e.timeout,url:r},data:c.data,headers:Cu(c.headers)||{},status:c.status,statusText:c.statusText}}async function _a(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(lT(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,a=t.body?await t.body(r):void 0,c=t.headers?await t.headers(r):void 0;fT(c);const u=async()=>{let h;try{h=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...s===void 0?{}:{params:s},...a===void 0?{}:{data:a},...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(E){throw E instanceof qe?E:new sn({endpointId:t.id,cause:E})}if(h.status<200||h.status>=300)throw new gi({endpointId:t.id,status:h.status,responseData:h.data,retryAfterMs:mT(h.headers)});const f=gT(t,r,i,s,a,c,n,h);if(t.parse)try{return await t.parse(f,r)}catch(E){throw new pi({endpointId:t.id,cause:E})}return f.data},d=n.gate;if(!d)return u();const l=ET(t,s,a,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...l===void 0?{}:{coalesceKey:l},load:u})}const pT=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),TT=new Set(rn),Sc="steam_account",Lf=new Set(rn.filter(e=>e!==Sc)),_T=1e3;function AT(e){const t=new Set,r=Mf({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??Nf))}),n=new Set;let i=0,s=!1,a=Promise.resolve(),c;const u=e.steamAccount===!0,d=e.userDataMode??aT(e.networkEnabled===!0,u),l=e.requestPolicyEnabled!==!1,h=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function f(){if(!u&&!e.authorizationContext)return{};if(!e.authorizationContext)throw p("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let C;try{C=await e.authorizationContext.get(e.operationContext)}catch(S){throw Io(S)?Fa(S.code,S.message,S):Fa("REQUEST_FAILED","读取 Runtime auth context 失败",S)}if(C.steamAccount!==u||C.userDataMode!==d)throw p("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const Q=C.token.trim();if(!Q)throw p("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:Q}}const E=e.account.onChange(C=>{if(g(),b("heybox_app_login_change",C?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),C&&e.account.getAccountKey){const Q=i;V().then(S=>{!s&&i===Q&&b("heybox_app_login_change",S)}).catch(()=>{})}});function g(){i+=1,c?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function b(C,Q){C==="user_info_authorization_change"&&DT(Q)&&r.invalidate();for(const S of t)try{S(C,Q)}catch{}}function N(){const C=e.identity.get()?.miniProgramId?.trim();if(!C)throw p("INVALID_STATE","当前能力缺少 canonical 小程序身份");return C}function y(){if(s||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function w(){y();let C;try{C=await e.account.getCurrentUserId(e.operationContext)}catch(Q){throw ku(Q,e.operationContext.signal,"读取小黑盒账号失败")}return typeof C=="string"&&C.trim()?C.trim():void 0}async function I(C,Q){const S=await w();if(i!==Q||S!==C)throw p("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function x(C,Q,S=N()){if(!e.account.getAccountKey)throw p("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let q;try{q=await e.account.getAccountKey(S,C,e.operationContext)}catch{throw y(),p("REQUEST_FAILED","读取本地账号标识失败")}if(await I(C,Q),N()!==S)throw p("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof q!="string"||!q.trim())throw p("INVALID_RESPONSE","Host 返回了无效的账号标识");return q}async function V(){const C=N(),Q=i,S=await w();if(y(),i!==Q)throw p("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return S?{isHeyboxAppLoggedIn:!0,accountKey:await x(S,Q,C)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function M(C){y();try{await e.account.ensureAuthenticated({trustedUserGesture:C,reason:"runtime_auth",signal:e.operationContext.signal})}catch(S){throw ku(S,e.operationContext.signal,"小黑盒登录失败")}const Q=await w();if(!Q)throw p("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return Q}async function R(C,Q,S=e.operationContext.signal){try{if(S.aborted)throw Ao();return await wT(_a(e.network,C,Q,{...e.operationContext,credentials:"heybox-session",signal:S,...h?{gate:h}:{}}),S)}catch(q){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):q instanceof qe?p("REQUEST_UNSUPPORTED",q.message):q instanceof pi?p("INVALID_RESPONSE","授权接口响应不合法"):q instanceof sn?p("REQUEST_FAILED","授权请求失败"):q instanceof gi?l&&(q.status===403||q.status===429)?p("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:q.status,...q.retryAfterMs===void 0?{}:{retryAfterMs:q.retryAfterMs}}):p("REQUEST_FAILED",q.message):Io(q)?q:p("REQUEST_FAILED","授权请求失败")}}async function L(C,Q){await R(eT,{runtimeContext:{miniProgramId:C,...await f()},challenge:Q}).catch(()=>{})}function Y(C){const Q=async()=>{const q=Pu(e.operationContext.signal);c=q;try{return await C(q.signal)}finally{c===q&&(c=void 0),q.abort()}},S=a.then(Q,Q);return a=S.then(()=>{},()=>{}),S}async function j(C,Q,S,q,W){if(!S)throw await L(C,Q.challenge),p("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await L(C,Q.challenge),p("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return Y(async Z=>{await I(q,W);const se=await ee(C,Q.displayedScopes,Z);await I(q,W);let de;try{de=await e.authPresentation.confirmAuthorization({miniProgramId:C,scopes:Q.displayedScopes,...se,signal:Z})}catch(Re){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await I(q,W),await L(C,Q.challenge),Fa("REQUEST_FAILED","授权确认界面执行失败",Re))}if(await I(q,W),de.status!=="granted")throw await L(C,Q.challenge),p("AUTHORIZATION_CANCELLED","用户取消授权");const Ie=yT(de.grantedScopes,Q.displayedScopes,u);if(!Ie.includes("identity"))throw await L(C,Q.challenge),p("AUTHORIZATION_CANCELLED","用户拒绝授权");return Ie})}async function ee(C,Q,S){const q=Pu(S),W=setTimeout(()=>q.abort(),_T);try{const Z=NT(e.miniProgramPresentation),[se,de]=await Promise.all([Z?Promise.resolve(Z):k(C,q.signal),Q.includes("profile")?z(q.signal):Promise.resolve(void 0)]);return{...se?{miniProgram:se}:{},...de?{userProfile:de}:{}}}finally{clearTimeout(W),q.abort()}}async function k(C,Q){try{const S=e.identity.get()?.version?.trim(),q=await R(Zp,{mini_program_id:C,...S?{miniprogram_version:S}:{}},Q),W=jr(q,"小程序公开资料"),Z=Wr(W.name),se=Wr(W.icon_url);return Z||se?{...Z?{name:Z}:{},...se?{avatarUrl:se}:{}}:void 0}catch{return}}async function z(C){try{const Q=await R(Of,void 0,C),S=jr(Q,"账号基础信息"),q=Wr(S.display_username),W=Wr(S.display_avatar);return q||W?{...q?{nickname:q}:{},...W?{avatar:W}:{}}:void 0}catch{return}}async function F(C,Q){if(oT(d,"auth.login"),!u&&C.includes(Sc))throw p("INVALID_PARAMS","auth.login 参数不合法");const S=N(),q=await M(Q),W=i,Z=await R(nT,{runtimeContext:{miniProgramId:S,...await f()},scopes:C});await I(q,W);const se=jr(Z,"小程序登录"),de=vu(se,"loginCode"),Ie=vu(se,"consentChallenge");if(de===Ie)throw p("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let Re;if(de)Re=Lu(se.loginCode,u);else{const _=IT(se.consentChallenge,u),B=await j(S,_,Q,q,W);await I(q,W);const K=await R(iT,{runtimeContext:{miniProgramId:S,...await f()},challenge:_.challenge,selectedScopes:B});if(await I(q,W),Re=Lu(jr(K,"小程序登录确认"),u),Re.scopes.some(J=>!B.includes(J)))throw p("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const _ of Re.scopes)n.add(_);r.invalidate();const Ue=e.account.getAccountKey?await x(q,W,S):void 0;return b("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...Ue===void 0?{}:{accountKey:Ue}}),b("user_info_authorization_change",za(n,u)),{...Re,...Ue===void 0?{}:{accountKey:Ue}}}async function U(C,Q){const S=i,q=await R(rT,{runtimeContext:{miniProgramId:Q,...await f()}});await I(C,S);const W=bT(jr(q,"用户本地身份"),u);for(const Z of u?rn:Lf)n.add(Z);return b("user_info_authorization_change",za(n,u)),W}function H(C){y();const Q=N(),S=`${C}\0${Q}\0${i}\0${u}`;return r.read(S,()=>U(C,Q))}async function P(C){if(!C)throw p("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const Q=N(),S=i,q=await w();if(!q)throw p("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const W=await R(tT,{runtimeContext:{miniProgramId:Q,...await f()}});await I(q,S),jr(W,"用户授权撤销"),g(),b("user_info_authorization_change",{identity:"denied",profile:"denied",...u?{steam_account:"denied"}:{}})}return{getAccountState:V,login:F,async confirmGameSaves(C){if(!C)throw p("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw p("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const Q=N(),S=await M(C),q=i;await Y(async W=>{await I(S,q);const Z=await ee(Q,["identity"],W),se=await e.authPresentation.confirmAuthorization({miniProgramId:Q,scopes:["identity","game_saves"],...Z,signal:W});if(await I(S,q),se.status!=="granted"||!se.grantedScopes.includes("game_saves")||!se.grantedScopes.includes("identity"))throw p("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:H,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>za(n,u),revoke:P,onEvent(C){return t.add(C),()=>t.delete(C)},dispose(){s||(s=!0,g(),r.dispose(),E(),t.clear())}}}function Fa(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(!he(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":pT.has(r)?r:"REQUEST_FAILED";throw p(n,r)}if(!he(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Lu(e,t){if(!he(e))throw p("INVALID_RESPONSE","login code 必须是对象");const r=zs(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 IT(e,t){if(!he(e))throw p("INVALID_RESPONSE","授权 challenge 必须是对象");const r=zs(e.requestedScopes,"challenge requestedScopes",t),n=zs(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 bT(e,t){if(!he(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 yT(e,t,r){const n=zs(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw p("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Wr(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function NT(e){const t=Wr(e?.name),r=Wr(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Pu(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 wT(e,t){return t.aborted?Promise.reject(Ao()):new Promise((r,n)=>{let i=!1;const s=c=>{i||(i=!0,t.removeEventListener("abort",a),c())},a=()=>s(()=>n(Ao()));t.addEventListener("abort",a,{once:!0}),e.then(c=>s(()=>r(c)),c=>s(()=>n(c)))})}function Ao(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function zs(e,t,r){const n=r?TT:Lf;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 za(e,t){const r=t?rn:rn.filter(n=>n!==Sc);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function vu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function DT(e){return he(e)?Object.values(e).some(t=>t==="denied"):!1}function Io(e){return he(e)&&typeof e.code=="string"&&typeof e.message=="string"}function ku(e,t,r){return t.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Io(e)?e:p("REQUEST_FAILED",r)}const ST=new Set(rn);function OT(e){return{[is]:async t=>{if(t!==void 0)throw p("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[ss]:async(t,r)=>e.authorization.login(MT(t),r.trustedUserGesture)}}function MT(e){if(e===void 0)return["identity"];if(!he(e)||Object.keys(e).some(t=>t!=="scopes"))throw xu();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!ST.has(t))||new Set(e.scopes).size!==e.scopes.length)throw xu();return[...e.scopes]}function xu(){return p("INVALID_PARAMS","auth.login 参数不合法")}const CT={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 He(e,"排行榜记录删除接口响应异常")}},RT={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 He(e,"当前排行榜记录接口响应异常")}},LT={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 He(e,"排行榜信息接口响应异常")}},PT={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 He(e,"排行榜列表接口响应异常")}},vT={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 He(e,"排行榜提交接口响应异常")}},kT={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 Ti(e,t,r){e.assertUsable();const n={request:async(i,s)=>(e.assertUsable(),e.network.request(i,s))};try{return await be(()=>_a(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(Gs(i)||Rn(i,"REQUEST_UNSUPPORTED")||Rn(i,"RATE_LIMITED")||Rn(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof qe)throw ie("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof sn&&Rn(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof gi){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw ie("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw ie("UNAUTHORIZED","当前用户未登录");const s=xT(i.responseData);if(Se(s)&&typeof s.status=="string"&&s.status!=="ok"){const a=Se(s.result)?Wt(s.result.error_code):void 0;if(s.status==="login"||s.status==="relogin"||js(s.result)||js(s)||a&&/^[A-Z][A-Z0-9_]+$/.test(a))throw Pf(s,e.subject)}throw ie("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof sn?Vs(e.subject):i instanceof pi?ye(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):ye(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function rt(e,t,r){if(!Se(e)||typeof e.status!="string")throw ye(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Pf(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw ye(`${t} 响应缺少 result`);return e.result}function _i(e,t){try{return e.onChange(t)}catch(r){if(Rn(r,Kl))return()=>{};throw r}}function Pf(e,t){if(e.status==="login"||e.status==="relogin")throw ie("UNAUTHORIZED",Wt(e.msg)||"当前用户未登录");if(Se(e.result)){const i=Wt(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw ie(i,Wt(e.result.message)||Wt(e.msg)||`${t}请求失败`)}const r=js(e.result)??js(e),n=Wt(r?.user_message)||Wt(e.msg)||Wt(r?.developer_message)||`${t}请求失败`;throw r?ie(UT(r),n,{status:e.status,sbe:r}):ie("HEYBOX_API_ERROR",n,{status:e.status})}function xT(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function js(e){return Se(e)&&Se(e.sbe)?e.sbe:void 0}function UT(e){const t=Wt(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 kT[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 Wt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Rn(e,t){return Se(e)&&e.code===t}function ie(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function ye(e){return ie("INVALID_RESPONSE",e)}function Vs(e){return ie("REQUEST_FAILED",`${e}请求失败`)}function Gs(e){return e instanceof Error&&e.name==="AbortError"}const BT="default",mr="排行榜",HT=/^[A-Za-z0-9_-]{1,64}$/,FT=300*1e3,zT=250,jT=3;class VT{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=_i(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(vT,{miniProgramId:n,...t});this.assertAccountGeneration(r);const s=rt(i,Kt,mr);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),ja(s,Kt)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=bn("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const s=await this.request(PT,{miniProgramId:r,...t}),a=rt(s,Mt,mr);if(!Se(a)||!Array.isArray(a.entries)||typeof a.has_more!="boolean")throw ye(`${Mt} 返回值不合法`);if(a.cursor!==void 0&&a.cursor!==null&&typeof a.cursor!="string")throw ye(`${Mt} 返回的 cursor 必须是字符串`);return{entries:a.entries.map(c=>ja(c,Mt)),...typeof a.cursor=="string"&&a.cursor?{cursor:a.cursor}:{},hasMore:a.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),a=bn("current",i);return this.read(s,"current",a,async()=>{const c=await this.request(RT,{miniProgramId:n,...t}),u=rt(c,ur,mr);if(!Se(u))throw ye(`${ur} 返回值必须是对象`);return u.entry===void 0||u.entry===null?void 0:ja(u.entry,ur)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(CT,{miniProgramId:n,...t});this.assertAccountGeneration(r);const s=rt(i,Cr,mr);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Se(s)||typeof s.deleted!="boolean")throw ye(`${Cr} 返回的 deleted 必须是布尔值`);return{deleted:s.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",bn("info"),async()=>{const i=await this.request(LT,{miniProgramId:r,...t}),s=rt(i,zt,mr);if(!Se(s)||typeof s.key!="string"||!HT.test(s.key))throw ye(`${zt} 返回的 key 不合法`);if(t.key!==void 0&&s.key!==t.key)throw ye(`${zt} 返回的 key 与请求不一致`);if(s.order!=="asc"&&s.order!=="desc")throw ye(`${zt} 返回的 order 必须是 asc 或 desc`);if(typeof s.rank_limit!="number"||!Number.isInteger(s.rank_limit)||s.rank_limit<0)throw ye(`${zt} 返回的 rankLimit 必须是非负整数`);return{key:s.key,order:s.order,rankLimit:s.rank_limit}})}read(t,r,n,i){this.assertUsable();const s=this.getOrCreateBucket(t),a=s?.caches[r],c=a?.get(n);if(c&&c.expiresAt>Date.now())return Promise.resolve(c.value);a?.delete(n);const u=bn(t,n),d=this.inflight.get(u);if(d)return d.promise;const l=this.accountGeneration,h=s?.generation,f=i().then(E=>(this.assertAccountGeneration(l),s&&a&&s.generation===h&&(r==="list"?a.size>=zT&&a.delete(a.keys().next().value):a.clear(),a.set(n,{expiresAt:Date.now()+FT,value:E})),E)).finally(()=>{this.inflight.get(u)?.promise===f&&this.inflight.delete(u),s&&this.removeEmptyBucket(t,s)});return this.inflight.set(u,{bucketKey:t,promise:f}),f}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=jT)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)Uu(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){Uu(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 Gs(n)?n:Vs(mr)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ie("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ie("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return bn(t,r??BT)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ie("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return Ti({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(Ce(this.options.operationContext.signal),this.disposed)throw ie("INVALID_STATE","Cloud capability 已释放")}}function GT(e){return new VT(e)}function ja(e,t){if(!Se(e))throw ye(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw ye(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw ye(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw ye(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw ye(`${t} 返回的 score 必须是有限数字`);if(!Se(e.extra))throw ye(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw ye(`${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 Uu(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function bn(...e){return JSON.stringify(e)}const YT={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 He(e,"云端存储删除接口响应异常")}},Bu={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 He(e,"云端存储读取接口响应异常")}},Hu={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 He(e,"云端存储 key 列表接口响应异常")}},QT={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 He(e,"云端存储写入接口响应异常")}},Er="云端存储",qT=3e4,WT=128,$T=500;class KT{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=_i(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(a=>a.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=rt(await this.request(Hu,{}),Rr,Er);if(this.assertAccountGeneration(t),!Se(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw ye("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,a)=>{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:a});else{const d={kind:t,key:r,value:n,generation:this.accountGeneration,readyAt:Date.now()+(t==="set"?$T:0),waiters:[{resolve:s,reject:a}]};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=rt(await this.request(YT,{key:t}),tn,Er);if(this.assertAccountGeneration(r.generation),!Se(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw ye("删除结果不合法");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 ye("云存储版本超出安全整数范围");const s=rt(await this.request(QT,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),en,Er);if(this.assertAccountGeneration(r.generation),!Se(s)||s.success!==!0)throw ye("云存储写入结果不合法");const a=Fu({...s,found:!0,value:r.value});if(a.version!==i.version+1||i.found&&a.revision!==i.revision)throw ye("写入版本凭证不匹配");this.writeCache(t,a)}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 a=this.keyGenerations.get(t)??0,c=this.request(Bu,{key:t}).then(u=>{this.assertAccountGeneration(r);const d=Fu(rt(u,Jr,Er));return(this.keyGenerations.get(t)??0)===a&&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>=WT&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+qT,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([Bu.id,Hu.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(ie("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(ie("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 Gs(s)?s:Vs(Er)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),ie("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),ie("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw ie("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ie("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ie("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw ie("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await be(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(a){throw Gs(a)?a:Vs(Er)}this.assertAccountGeneration(n);const s=i.token.trim();if(!s||i.expiresAt<=Date.now())throw ie("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return Ti({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(Ce(this.options.operationContext.signal),this.disposed)throw ie("INVALID_STATE","Cloud capability 已释放")}}function ZT(e){return new KT(e)}function Fu(e){if(!Se(e))throw ye("云存储读取结果必须是对象");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 ye("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw ye("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const XT=/^[A-Za-z0-9_-]{1,64}$/,zu=20,JT=100,ju=2048,e_=/^[A-Za-z0-9_-]{1,128}$/,Vu=16*1024;function t_(e){const t=GT(e),r=ZT(e);return{handlers:{[Kt]:async i=>t.submit(r_(i)),[Mt]:async i=>t.getList(n_(i)),[ur]:async i=>t.getCurrentUserEntry(Va(i,ur)),[Cr]:async i=>t.deleteCurrentUserEntry(Va(i,Cr)),[zt]:async i=>t.getInfo(Va(i,zt)),[Jr]:async i=>r.getItem(Gu(i,Jr)),[en]:async i=>{const{key:s,value:a}=i_(i);return r.setItem(s,a)},[tn]:async i=>r.removeItem(Gu(i,tn)),[Rr]:async i=>(a_(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function r_(e){const t=gn(e,Kt,!1);if(pn(t,["key","score","extra"],Kt),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw ht("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Oc(t.key,Kt),score:t.score,...t.extra===void 0?{}:{extra:o_(t.extra)}}}function n_(e){if(e===void 0)return{limit:zu};const t=gn(e,Mt,!0);pn(t,["key","limit","cursor"],Mt);const r=t.limit===void 0?zu:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>JT)throw ht("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw ht("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Oc(t.key,Mt),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Va(e,t){if(e===void 0)return{};const r=gn(e,t,!0);return pn(r,["key"],t),Oc(r.key,t)}function Gu(e,t){const r=gn(e,t,!1);return pn(r,["key"],t),vf(r.key,t)}function i_(e){const t=en,r=gn(e,t,!1);pn(r,["key","value"],t);const n=vf(r.key,t);if(typeof r.value!="string")throw ht("INVALID_PARAMS",`${t} value 必须是字符串`);if(s_(r.value))throw ht("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>Vu)throw ht("INVALID_PARAMS",`${t} value 不能超过 ${Vu} 字节`);return{key:n,value:r.value}}function s_(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 a_(e){const t=gn(e,Rr,!0);pn(t,[],Rr)}function vf(e,t){if(typeof e!="string"||!e_.test(e))throw ht("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function gn(e,t,r){if(e===void 0&&r)return{};if(!kf(e))throw ht("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function pn(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw ht("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Oc(e,t){if(e===void 0)return{};if(typeof e!="string"||!XT.test(e))throw ht("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function o_(e){if(!kf(e))throw ht("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw ht("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw ht("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>ju)throw ht("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${ju} 字节`);return e}function kf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ht(e,t){return{code:e,message:t}}const c_={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 He(e,"游戏存档接口响应异常")}},u_=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function bo(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=>bo(r,t+1)):Se(e)&&Object.values(e).every(r=>bo(r,t+1))}function d_(e,t){const r=u_.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 ie(String(e.error_code),"账号或授权已变化");if(e.status==="ready"&&Se(e.data)&&bo(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function xf(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 h=n(u),f=r.get(h)??Promise.resolve();let E;const g=new Promise(N=>{E=N}),b=f.then(()=>g);r.set(h,b);try{return await be(()=>f,d.signal),Ce(d.signal),e?.withLock?await e.withLock(h,l):await l()}finally{E(),r.get(h)===b&&b.then(()=>{r.get(h)===b&&r.delete(h)})}}async function s(u,d,l=!1){const h=n(u);if(!l&&t.has(h)||!e)return t.get(h);try{const f=await be(()=>e.getRaw(h,d),d.signal);if(!f)return;const E=JSON.parse(f);if(!E||typeof E!="object")return;const g=E;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(h,g),g)}catch(f){if(Ce(d.signal),l)throw f;return t.get(h)}}async function a(u,d,l){Ce(l.signal);const h=n(u),f=d?{...u,version:1,taskId:d}:void 0;if(t.set(h,f),!!e)try{await be(()=>e.setRaw(h,f?JSON.stringify(f):"",l),l.signal)}catch{Ce(l.signal)}}async function c(u,d,l){await i(u,l,async()=>{const h=n(u),f=t.get(h),E=f?.taskId===d&&f.accountId===u.accountId;let g;try{g=await s(u,l,!0)}catch{Ce(l.signal),E&&t.set(h,void 0);return}g?.taskId===d&&g.accountId===u.accountId?(await a(u,void 0,l),f&&!E&&t.set(h,f)):E&&t.set(h,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:a,remove:c,clear(u){for(const d of t.values())d&&c(d,d.taskId,u).catch(()=>{})}}}const l_=2e3,f_=5*6e4;function h_(e){const t=xf(e.storage);let r=0,n=!1,i;const s=e.fileDownloads??(e.files&&e.transfer?Dc({files:e.files,transfer:e.transfer,registry:e.fileRegistry,signal:e.operationContext.signal}):void 0),a=new Set,c=new Map,u={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},d=L=>s?.release(L)??Promise.resolve(),l=new Set;let h=new AbortController,f;const E=()=>{h.abort(),h=new AbortController,f=void 0},g=(L=!0)=>{L&&t.clear(u),r++,E();for(const Y of l)Y.abort();for(const Y of a)d(Y).catch(()=>{});a.clear(),c.clear()},b=_i(e.account,L=>{i&&L!==i&&(g(),i=void 0)}),N=e.authorization.onEvent(()=>g());function y(L,Y,j,ee){if(w(j),ee.signal.aborted||!L.account_id||!e.presentation?.showSteamLoginRequired)return;const k=`${L.account_id}:${L.game_id}:${L.task_id??"sync"}`;if(f!==k){f=k;try{e.presentation.showSteamLoginRequired({userId:Y,accountId:L.account_id},ke(e.operationContext,h.signal))}catch{}}}function w(L){if(n||e.operationContext.signal.aborted)throw ie("RUNTIME_DESTROYED","小程序已关闭");if(L!==r)throw ie("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function I(L,Y,j){if(w(Y),await e.account.getCurrentUserId(j)!==L)throw g(),ie("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");w(Y)}async function x(L,Y,j,ee){if(await I(Y,j,ee),!e.authorizationContext)throw ie("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const k=await e.authorizationContext.get(ee);if(!k.token||k.expiresAt<=Date.now())throw ie("UNAUTHORIZED","小程序运行上下文已过期");const z=await Ti({network:e.network,operationContext:ee,subject:"游戏存档",assertUsable:()=>w(j),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},c_,{...L,runtime_auth_context_token:k.token});if(await I(Y,j,ee),z.status==="failed"&&Se(z.result)&&z.result.error_code==="RECENT_SAVE_AVAILABLE")throw ie("RECENT_SAVE_AVAILABLE",typeof z.msg=="string"&&z.msg?z.msg:"已有近期存档,请直接查询使用");const F=rt(z,L.action,"游戏存档");if(!Se(F))throw ie("INVALID_RESPONSE","存档响应不合法");return F}async function V(L,Y,j){const ee=m_(L,Y),k=r;if(w(k),L==="file"&&(!e.transfer||!e.files))throw ie("METHOD_FORBIDDEN","宿主不支持存档文件读取");const z=new AbortController;l.add(z);let F=!1;const U=L==="sync"?setTimeout(()=>{F=!0,z.abort()},f_):void 0,H=ke(ke(e.operationContext,j.signal),z.signal);try{const P=await e.account.getCurrentUserId(H);if(!P)throw ie("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==P)throw g(),ie("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=P,L==="sync"||L==="parsed"){if(L==="sync"&&E(),!ee.account_id){const W=await x({action:"check",game_id:ee.game_id},P,k,H);ee.account_id=oi(W.account_id)}if(L==="sync")return await M(ee,P,k,H)}const C=await x({action:L,...ee},P,k,H);if(L==="list")return E_(C);if(L==="parsed")return d_(C.parsed_data,ee.game_id);if(Uf(C.file).fileId!==ee.file_id)throw ie("INVALID_RESPONSE","文件标识不匹配");if(!s)throw ie("REQUEST_UNSUPPORTED","宿主不支持存档下载");const S=await s.download(C,async W=>{try{w(k),await x({action:"check",game_id:ee.game_id,account_id:ee.account_id},P,k,W)}catch(Z){const se=Se(Z)?String(Z.code):"";throw["RUNTIME_DESTROYED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED","UNAUTHORIZED"].includes(se)?(g(),ie("FILE_ACCESS_REVOKED","游戏存档授权已失效")):Z}},H);let q=!1;try{if(await I(P,k,H),w(k),H.signal.aborted)throw ie("DOWNLOAD_CANCELLED","存档下载已取消");const W=e.fileRegistry.registerFile(S,"game-save","read");return a.add(S),c.set(Ic(),{file:S,sizeBytes:s.sizeOf(S)}),q=!0,W}finally{q||await s.release(S)}}catch(P){throw F?ie("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):P}finally{U!==void 0&&clearTimeout(U),l.delete(z)}}async function M(L,Y,j,ee){const k=e.identity.get()?.miniProgramId;if(!k)throw ie("INVALID_STATE","小程序身份尚未确认");const z={miniProgramId:k,userId:Y,gameId:L.game_id,accountId:L.account_id},F=H=>x({action:"status",...L,task_id:H},Y,j,ee);let U;try{const H=await t.run(z,ee,async()=>{await I(Y,j,ee);const C=await t.get(z,ee);if(C){U=C;try{return{taskId:C,status:await F(C)}}catch(S){if(!Se(S)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(S.code)))throw S;await t.set(z,void 0,ee),U=void 0}}const Q=await x({action:"sync",...L},Y,j,ee);return U=oi(Q.task_id),await t.set(z,U,ee),await I(Y,j,ee),{taskId:U,status:void 0}});U=H.taskId;let P=H.status;for(;;){if(w(j),ee.signal.aborted)throw ie("REQUEST_CANCELLED","已停止等待存档同步");if(P??=await F(U),P.state==="succeeded"||P.state==="failed"){if(await t.remove(z,U,ee),await I(Y,j,ee),P.state==="succeeded")return{state:"succeeded"};throw ie(P.error_code?Ys(P.error_code):"SYNC_FAILED",P.message?Ys(P.message):"存档同步失败")}if(P.state!=="syncing"&&P.state!=="uploading")throw ie("INVALID_RESPONSE","同步状态不合法");P=void 0,await g_(l_,ee.signal)}}catch(H){if(Se(H)){const P=String(H.code);P==="STEAM_LOGIN_REQUIRED"&&y({...L,task_id:U},Y,j,ee),U&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(P)&&await t.remove(z,U,u)}throw H}}return{handlers:{"gameSaves.list":(L,Y)=>V("list",L,Y),"gameSaves.sync":(L,Y)=>V("sync",L,Y),"gameSaves.readParsedData":(L,Y)=>V("parsed",L,Y),"gameSaves.getFile":(L,Y)=>V("file",L,Y)},diagnostics:{async getSnapshot(){const L=r;return i&&await I(i,L,e.operationContext),w(L),Array.from(c,([Y,j])=>({id:Y,name:j.file.name,sizeBytes:j.sizeBytes}))},async readFile(L,Y){const j=r;w(j);const ee=c.get(L);if(!ee)throw ie("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const k=ke(e.operationContext,Y);k.signal.throwIfAborted();const z=await ee.file.read(k);try{return k.signal.throwIfAborted(),w(j),{name:ee.file.name,bytes:z}}catch(F){throw z.fill(0),F}}},allowsRead(L,Y){return["file.readBytes","file.readText","file.stat","file.exists"].includes(L)&&Se(Y)&&e.fileRegistry.isGameSaveRef(Y.target)},dispose(){n||(n=!0,g(!1),b(),N())}}}function m_(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!Se(t)||Object.keys(t).some(i=>!r.includes(i)))throw ie("INVALID_PARAMS","存档参数不合法");const n=Ln(t.gameId);if(Number(n)>2147483647)throw ie("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:Ln(t.accountId)}:{},...e==="file"?{save_id:Ln(t.saveId),file_id:Ln(t.fileId)}:{}}}function Ln(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw ie("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function oi(e){try{return Ln(e)}catch{throw ie("INVALID_RESPONSE","服务端存档标识无效")}}function Ys(e){if(typeof e!="string")throw ie("INVALID_RESPONSE","服务端存档字段无效");return e}function yo(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw ie("INVALID_RESPONSE","服务端存档数值无效");return e}function Uf(e){if(!Se(e))throw ie("INVALID_RESPONSE","存档文件信息无效");return{fileId:oi(e.file_id),name:Ys(e.name),originalPath:Ys(e.original_path),sizeBytes:yo(e.size_bytes),modifiedAt:yo(e.modified_at)}}function E_(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw ie("INVALID_RESPONSE","存档列表无效");return{accountId:oi(e.account_id),saves:e.saves.map(t=>{if(!Se(t)||!Array.isArray(t.files)||t.files.length>200)throw ie("INVALID_RESPONSE","存档文件列表无效");return{saveId:oi(t.save_id),createdAt:yo(t.created_at),files:t.files.map(Uf)}})}}function g_(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(s),t.removeEventListener("abort",i),n(ie("REQUEST_CANCELLED","已停止等待存档同步"))},s=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}function Bf(e,t){return{auth:"optional",channel:"api",id:e,method:"GET",path:t,query(r){return{...r}},parse(r){return Sf(r,"赛事中心接口响应异常")}}}function Hf(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 Sf(r,"赛事中心接口响应异常")}}}const p_=Bf("heybox.bbs.app.link.tree.get","/bbs/app/link/tree"),T_=Bf("heybox.bbs.app.comment.sub.comments.get","/bbs/app/comment/sub/comments"),__=Hf("heybox.bbs.app.comment.support.post","/bbs/app/comment/support"),A_=Hf("heybox.bbs.app.comment.delete.post","/bbs/app/comment/delete");function Aa(e){return He(e,"社区评论响应异常")}const Yu={...p_,parse:Aa},I_={...T_,parse:Aa},b_={...__,bodyEncoding:"form",body:e=>Object.fromEntries(Object.entries(e.body).map(([t,r])=>[t,String(r)])),parse:Aa},y_={...A_,bodyEncoding:"form",body:e=>Object.fromEntries(Object.entries(e.body).map(([t,r])=>[t,String(r)])),parse:Aa},N_={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=>He(e,"社区操作响应异常")},w_={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=>He(e,"社区操作响应异常")},D_={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=>He(e,"关联帖子响应异常")},S_=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]),ze="�";var m;(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"})(m||(m={}));const dt={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function Ff(e){return e>=55296&&e<=57343}function O_(e){return e>=56320&&e<=57343}function M_(e,t){return(e-55296)*1024+9216+t}function zf(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function jf(e){return e>=64976&&e<=65007||S_.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 C_=65536;class R_{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=C_,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,a=i+r,c=s+r;return{code:t,startLine:n,endLine:n,startCol:a,endCol:a,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(O_(r))return this.pos++,this._addGap(),M_(t,r)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,m.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,m.EOF;const n=this.html.charCodeAt(r);return n===m.CARRIAGE_RETURN?m.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,m.EOF;let t=this.html.charCodeAt(this.pos);return t===m.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,m.LINE_FEED):t===m.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,Ff(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===m.LINE_FEED||t===m.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){zf(t)?this._err(G.controlCharacterInInputStream):jf(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 ve;(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"})(ve||(ve={}));function Vf(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 L_=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୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢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;怳Ādp໩໮uct;戏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ǣጓ\0጖y;䐎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Ā;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀ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Ā;e᜚᜜lƀ;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\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩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ↄⅪ←ٖ↛ǰ↉\0↎proø₞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;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\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\0⹻m;櫳;櫽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))),P_=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 v_(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=P_.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 k_=32;var ar;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(ar||(ar={}));function No(e){return e>=We.ZERO&&e<=We.NINE}function x_(e){return e>=We.UPPER_A&&e<=We.UPPER_F||e>=We.LOWER_A&&e<=We.LOWER_F}function U_(e){return e>=We.UPPER_A&&e<=We.UPPER_Z||e>=We.LOWER_A&&e<=We.LOWER_Z||No(e)}function B_(e){return e===We.EQUALS||U_(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 $t;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})($t||($t={}));class H_{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=$t.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)|k_)===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(No(i)||x_(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(No(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===$t.Strict)return 0;return this.emitCodePoint(v_(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&ar.VALUE_LENGTH)>>14;for(;r<t.length;r++,this.excess++){const a=t.charCodeAt(r);if(this.treeIndex=F_(n,i,this.treeIndex+Math.max(1,s),a),this.treeIndex<0)return this.result===0||this.decodeMode===$t.Attribute&&(s===0||B_(a))?0:this.emitNotTerminatedNamedEntity();if(i=n[this.treeIndex],s=(i&ar.VALUE_LENGTH)>>14,s!==0){if(a===We.SEMI)return this.emitNamedEntityData(this.treeIndex,s,this.consumed+this.excess);this.decodeMode!==$t.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]&ar.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]&~ar.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!==$t.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 F_(e,t,r,n){const i=(t&ar.BRANCH_LENGTH)>>7,s=t&ar.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 a=r,c=a+i-1;for(;a<=c;){const u=a+c>>>1,d=e[u];if(d<n)a=u+1;else if(d>n)c=u-1;else return e[u+i]}return-1}var te;(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/"})(te||(te={}));var Sr;(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"})(Sr||(Sr={}));var It;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"})(It||(It={}));var v;(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"})(v||(v={}));var o;(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"})(o||(o={}));const z_=new Map([[v.A,o.A],[v.ADDRESS,o.ADDRESS],[v.ANNOTATION_XML,o.ANNOTATION_XML],[v.APPLET,o.APPLET],[v.AREA,o.AREA],[v.ARTICLE,o.ARTICLE],[v.ASIDE,o.ASIDE],[v.B,o.B],[v.BASE,o.BASE],[v.BASEFONT,o.BASEFONT],[v.BGSOUND,o.BGSOUND],[v.BIG,o.BIG],[v.BLOCKQUOTE,o.BLOCKQUOTE],[v.BODY,o.BODY],[v.BR,o.BR],[v.BUTTON,o.BUTTON],[v.CAPTION,o.CAPTION],[v.CENTER,o.CENTER],[v.CODE,o.CODE],[v.COL,o.COL],[v.COLGROUP,o.COLGROUP],[v.DD,o.DD],[v.DESC,o.DESC],[v.DETAILS,o.DETAILS],[v.DIALOG,o.DIALOG],[v.DIR,o.DIR],[v.DIV,o.DIV],[v.DL,o.DL],[v.DT,o.DT],[v.EM,o.EM],[v.EMBED,o.EMBED],[v.FIELDSET,o.FIELDSET],[v.FIGCAPTION,o.FIGCAPTION],[v.FIGURE,o.FIGURE],[v.FONT,o.FONT],[v.FOOTER,o.FOOTER],[v.FOREIGN_OBJECT,o.FOREIGN_OBJECT],[v.FORM,o.FORM],[v.FRAME,o.FRAME],[v.FRAMESET,o.FRAMESET],[v.H1,o.H1],[v.H2,o.H2],[v.H3,o.H3],[v.H4,o.H4],[v.H5,o.H5],[v.H6,o.H6],[v.HEAD,o.HEAD],[v.HEADER,o.HEADER],[v.HGROUP,o.HGROUP],[v.HR,o.HR],[v.HTML,o.HTML],[v.I,o.I],[v.IMG,o.IMG],[v.IMAGE,o.IMAGE],[v.INPUT,o.INPUT],[v.IFRAME,o.IFRAME],[v.KEYGEN,o.KEYGEN],[v.LABEL,o.LABEL],[v.LI,o.LI],[v.LINK,o.LINK],[v.LISTING,o.LISTING],[v.MAIN,o.MAIN],[v.MALIGNMARK,o.MALIGNMARK],[v.MARQUEE,o.MARQUEE],[v.MATH,o.MATH],[v.MENU,o.MENU],[v.META,o.META],[v.MGLYPH,o.MGLYPH],[v.MI,o.MI],[v.MO,o.MO],[v.MN,o.MN],[v.MS,o.MS],[v.MTEXT,o.MTEXT],[v.NAV,o.NAV],[v.NOBR,o.NOBR],[v.NOFRAMES,o.NOFRAMES],[v.NOEMBED,o.NOEMBED],[v.NOSCRIPT,o.NOSCRIPT],[v.OBJECT,o.OBJECT],[v.OL,o.OL],[v.OPTGROUP,o.OPTGROUP],[v.OPTION,o.OPTION],[v.P,o.P],[v.PARAM,o.PARAM],[v.PLAINTEXT,o.PLAINTEXT],[v.PRE,o.PRE],[v.RB,o.RB],[v.RP,o.RP],[v.RT,o.RT],[v.RTC,o.RTC],[v.RUBY,o.RUBY],[v.S,o.S],[v.SCRIPT,o.SCRIPT],[v.SEARCH,o.SEARCH],[v.SECTION,o.SECTION],[v.SELECT,o.SELECT],[v.SOURCE,o.SOURCE],[v.SMALL,o.SMALL],[v.SPAN,o.SPAN],[v.STRIKE,o.STRIKE],[v.STRONG,o.STRONG],[v.STYLE,o.STYLE],[v.SUB,o.SUB],[v.SUMMARY,o.SUMMARY],[v.SUP,o.SUP],[v.TABLE,o.TABLE],[v.TBODY,o.TBODY],[v.TEMPLATE,o.TEMPLATE],[v.TEXTAREA,o.TEXTAREA],[v.TFOOT,o.TFOOT],[v.TD,o.TD],[v.TH,o.TH],[v.THEAD,o.THEAD],[v.TITLE,o.TITLE],[v.TR,o.TR],[v.TRACK,o.TRACK],[v.TT,o.TT],[v.U,o.U],[v.UL,o.UL],[v.SVG,o.SVG],[v.VAR,o.VAR],[v.WBR,o.WBR],[v.XMP,o.XMP]]);function Ia(e){var t;return(t=z_.get(e))!==null&&t!==void 0?t:o.UNKNOWN}const ne=o,j_={[te.HTML]:new Set([ne.ADDRESS,ne.APPLET,ne.AREA,ne.ARTICLE,ne.ASIDE,ne.BASE,ne.BASEFONT,ne.BGSOUND,ne.BLOCKQUOTE,ne.BODY,ne.BR,ne.BUTTON,ne.CAPTION,ne.CENTER,ne.COL,ne.COLGROUP,ne.DD,ne.DETAILS,ne.DIR,ne.DIV,ne.DL,ne.DT,ne.EMBED,ne.FIELDSET,ne.FIGCAPTION,ne.FIGURE,ne.FOOTER,ne.FORM,ne.FRAME,ne.FRAMESET,ne.H1,ne.H2,ne.H3,ne.H4,ne.H5,ne.H6,ne.HEAD,ne.HEADER,ne.HGROUP,ne.HR,ne.HTML,ne.IFRAME,ne.IMG,ne.INPUT,ne.LI,ne.LINK,ne.LISTING,ne.MAIN,ne.MARQUEE,ne.MENU,ne.META,ne.NAV,ne.NOEMBED,ne.NOFRAMES,ne.NOSCRIPT,ne.OBJECT,ne.OL,ne.P,ne.PARAM,ne.PLAINTEXT,ne.PRE,ne.SCRIPT,ne.SECTION,ne.SELECT,ne.SOURCE,ne.STYLE,ne.SUMMARY,ne.TABLE,ne.TBODY,ne.TD,ne.TEMPLATE,ne.TEXTAREA,ne.TFOOT,ne.TH,ne.THEAD,ne.TITLE,ne.TR,ne.TRACK,ne.UL,ne.WBR,ne.XMP]),[te.MATHML]:new Set([ne.MI,ne.MO,ne.MN,ne.MS,ne.MTEXT,ne.ANNOTATION_XML]),[te.SVG]:new Set([ne.TITLE,ne.FOREIGN_OBJECT,ne.DESC]),[te.XLINK]:new Set,[te.XML]:new Set,[te.XMLNS]:new Set},wo=new Set([ne.H1,ne.H2,ne.H3,ne.H4,ne.H5,ne.H6]);v.STYLE,v.SCRIPT,v.XMP,v.IFRAME,v.NOEMBED,v.NOFRAMES,v.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 ft={DATA:T.DATA,RCDATA:T.RCDATA,RAWTEXT:T.RAWTEXT,SCRIPT_DATA:T.SCRIPT_DATA,PLAINTEXT:T.PLAINTEXT,CDATA_SECTION:T.CDATA_SECTION};function V_(e){return e>=m.DIGIT_0&&e<=m.DIGIT_9}function Pn(e){return e>=m.LATIN_CAPITAL_A&&e<=m.LATIN_CAPITAL_Z}function G_(e){return e>=m.LATIN_SMALL_A&&e<=m.LATIN_SMALL_Z}function er(e){return G_(e)||Pn(e)}function Qu(e){return er(e)||V_(e)}function Ci(e){return e+32}function Gf(e){return e===m.SPACE||e===m.LINE_FEED||e===m.TABULATION||e===m.FORM_FEED}function qu(e){return Gf(e)||e===m.SOLIDUS||e===m.GREATER_THAN_SIGN}function Y_(e){return e===m.NULL?G.nullCharacterReference:e>1114111?G.characterReferenceOutsideUnicodeRange:Ff(e)?G.surrogateCharacterReference:jf(e)?G.noncharacterCharacterReference:zf(e)||e===m.CARRIAGE_RETURN?G.controlCharacterReference:null}class Q_{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 R_(r),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new H_(L_,(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=Y_(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:ve.START_TAG,tagName:"",tagID:o.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:ve.END_TAG,tagName:"",tagID:o.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(t){this.currentToken={type:ve.COMMENT,data:"",location:this.getCurrentLocation(t)}}_createDoctypeToken(t){this.currentToken={type:ve.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(Vf(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=Ia(t.tagName),t.type===ve.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 ve.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case ve.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case ve.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:ve.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=Gf(t)?ve.WHITESPACE_CHARACTER:t===m.NULL?ve.NULL_CHARACTER:ve.CHARACTER;this._appendCharToCurrentCharacterToken(r,String.fromCodePoint(t))}_emitChars(t){this._appendCharToCurrentCharacterToken(ve.CHARACTER,t)}_startCharacterReference(){this.returnState=this.state,this.state=T.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?$t.Attribute:$t.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 m.LESS_THAN_SIGN:{this.state=T.TAG_OPEN;break}case m.AMPERSAND:{this._startCharacterReference();break}case m.NULL:{this._err(G.unexpectedNullCharacter),this._emitCodePoint(t);break}case m.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRcdata(t){switch(t){case m.AMPERSAND:{this._startCharacterReference();break}case m.LESS_THAN_SIGN:{this.state=T.RCDATA_LESS_THAN_SIGN;break}case m.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(ze);break}case m.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRawtext(t){switch(t){case m.LESS_THAN_SIGN:{this.state=T.RAWTEXT_LESS_THAN_SIGN;break}case m.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(ze);break}case m.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptData(t){switch(t){case m.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_LESS_THAN_SIGN;break}case m.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(ze);break}case m.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case m.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(ze);break}case m.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateTagOpen(t){if(er(t))this._createStartTagToken(),this.state=T.TAG_NAME,this._stateTagName(t);else switch(t){case m.EXCLAMATION_MARK:{this.state=T.MARKUP_DECLARATION_OPEN;break}case m.SOLIDUS:{this.state=T.END_TAG_OPEN;break}case m.QUESTION_MARK:{this._err(G.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=T.BOGUS_COMMENT,this._stateBogusComment(t);break}case m.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(er(t))this._createEndTagToken(),this.state=T.TAG_NAME,this._stateTagName(t);else switch(t){case m.GREATER_THAN_SIGN:{this._err(G.missingEndTagName),this.state=T.DATA;break}case m.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:{this.state=T.BEFORE_ATTRIBUTE_NAME;break}case m.SOLIDUS:{this.state=T.SELF_CLOSING_START_TAG;break}case m.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentTagToken();break}case m.NULL:{this._err(G.unexpectedNullCharacter),r.tagName+=ze;break}case m.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:r.tagName+=String.fromCodePoint(Pn(t)?Ci(t):t)}}_stateRcdataLessThanSign(t){t===m.SOLIDUS?this.state=T.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=T.RCDATA,this._stateRcdata(t))}_stateRcdataEndTagOpen(t){er(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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=T.BEFORE_ATTRIBUTE_NAME,!1;case m.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=T.SELF_CLOSING_START_TAG,!1;case m.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===m.SOLIDUS?this.state=T.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=T.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagOpen(t){er(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 m.SOLIDUS:{this.state=T.SCRIPT_DATA_END_TAG_OPEN;break}case m.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){er(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===m.HYPHEN_MINUS?(this.state=T.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=T.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStartDash(t){t===m.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 m.HYPHEN_MINUS:{this.state=T.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case m.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case m.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(ze);break}case m.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataEscapedDash(t){switch(t){case m.HYPHEN_MINUS:{this.state=T.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case m.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case m.NULL:{this._err(G.unexpectedNullCharacter),this.state=T.SCRIPT_DATA_ESCAPED,this._emitChars(ze);break}case m.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=T.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedDashDash(t){switch(t){case m.HYPHEN_MINUS:{this._emitChars("-");break}case m.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case m.GREATER_THAN_SIGN:{this.state=T.SCRIPT_DATA,this._emitChars(">");break}case m.NULL:{this._err(G.unexpectedNullCharacter),this.state=T.SCRIPT_DATA_ESCAPED,this._emitChars(ze);break}case m.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=T.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedLessThanSign(t){t===m.SOLIDUS?this.state=T.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:er(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){er(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(dt.SCRIPT,!1)&&qu(this.preprocessor.peek(dt.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r<dt.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 m.HYPHEN_MINUS:{this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case m.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case m.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(ze);break}case m.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDash(t){switch(t){case m.HYPHEN_MINUS:{this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case m.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case m.NULL:{this._err(G.unexpectedNullCharacter),this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(ze);break}case m.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case m.HYPHEN_MINUS:{this._emitChars("-");break}case m.LESS_THAN_SIGN:{this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case m.GREATER_THAN_SIGN:{this.state=T.SCRIPT_DATA,this._emitChars(">");break}case m.NULL:{this._err(G.unexpectedNullCharacter),this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(ze);break}case m.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=T.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedLessThanSign(t){t===m.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(dt.SCRIPT,!1)&&qu(this.preprocessor.peek(dt.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r<dt.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:break;case m.SOLIDUS:case m.GREATER_THAN_SIGN:case m.EOF:{this.state=T.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case m.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:case m.SOLIDUS:case m.GREATER_THAN_SIGN:case m.EOF:{this._leaveAttrName(),this.state=T.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case m.EQUALS_SIGN:{this._leaveAttrName(),this.state=T.BEFORE_ATTRIBUTE_VALUE;break}case m.QUOTATION_MARK:case m.APOSTROPHE:case m.LESS_THAN_SIGN:{this._err(G.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case m.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.name+=ze;break}default:this.currentAttr.name+=String.fromCodePoint(Pn(t)?Ci(t):t)}}_stateAfterAttributeName(t){switch(t){case m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:break;case m.SOLIDUS:{this.state=T.SELF_CLOSING_START_TAG;break}case m.EQUALS_SIGN:{this.state=T.BEFORE_ATTRIBUTE_VALUE;break}case m.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentTagToken();break}case m.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=T.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateBeforeAttributeValue(t){switch(t){case m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:break;case m.QUOTATION_MARK:{this.state=T.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case m.APOSTROPHE:{this.state=T.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case m.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 m.QUOTATION_MARK:{this.state=T.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case m.AMPERSAND:{this._startCharacterReference();break}case m.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=ze;break}case m.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueSingleQuoted(t){switch(t){case m.APOSTROPHE:{this.state=T.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case m.AMPERSAND:{this._startCharacterReference();break}case m.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=ze;break}case m.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueUnquoted(t){switch(t){case m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:{this._leaveAttrValue(),this.state=T.BEFORE_ATTRIBUTE_NAME;break}case m.AMPERSAND:{this._startCharacterReference();break}case m.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=T.DATA,this.emitCurrentTagToken();break}case m.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=ze;break}case m.QUOTATION_MARK:case m.APOSTROPHE:case m.LESS_THAN_SIGN:case m.EQUALS_SIGN:case m.GRAVE_ACCENT:{this._err(G.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case m.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAfterAttributeValueQuoted(t){switch(t){case m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:{this._leaveAttrValue(),this.state=T.BEFORE_ATTRIBUTE_NAME;break}case m.SOLIDUS:{this._leaveAttrValue(),this.state=T.SELF_CLOSING_START_TAG;break}case m.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=T.DATA,this.emitCurrentTagToken();break}case m.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 m.GREATER_THAN_SIGN:{const r=this.currentToken;r.selfClosing=!0,this.state=T.DATA,this.emitCurrentTagToken();break}case m.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 m.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentComment(r);break}case m.EOF:{this.emitCurrentComment(r),this._emitEOFToken();break}case m.NULL:{this._err(G.unexpectedNullCharacter),r.data+=ze;break}default:r.data+=String.fromCodePoint(t)}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(dt.DASH_DASH,!0)?(this._createCommentToken(dt.DASH_DASH.length+1),this.state=T.COMMENT_START):this._consumeSequenceIfMatch(dt.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(dt.DOCTYPE.length+1),this.state=T.DOCTYPE):this._consumeSequenceIfMatch(dt.CDATA_START,!0)?this.inForeignNode?this.state=T.CDATA_SECTION:(this._err(G.cdataInHtmlContent),this._createCommentToken(dt.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 m.HYPHEN_MINUS:{this.state=T.COMMENT_START_DASH;break}case m.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 m.HYPHEN_MINUS:{this.state=T.COMMENT_END;break}case m.GREATER_THAN_SIGN:{this._err(G.abruptClosingOfEmptyComment),this.state=T.DATA,this.emitCurrentComment(r);break}case m.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 m.HYPHEN_MINUS:{this.state=T.COMMENT_END_DASH;break}case m.LESS_THAN_SIGN:{r.data+="<",this.state=T.COMMENT_LESS_THAN_SIGN;break}case m.NULL:{this._err(G.unexpectedNullCharacter),r.data+=ze;break}case m.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 m.EXCLAMATION_MARK:{r.data+="!",this.state=T.COMMENT_LESS_THAN_SIGN_BANG;break}case m.LESS_THAN_SIGN:{r.data+="<";break}default:this.state=T.COMMENT,this._stateComment(t)}}_stateCommentLessThanSignBang(t){t===m.HYPHEN_MINUS?this.state=T.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=T.COMMENT,this._stateComment(t))}_stateCommentLessThanSignBangDash(t){t===m.HYPHEN_MINUS?this.state=T.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=T.COMMENT_END_DASH,this._stateCommentEndDash(t))}_stateCommentLessThanSignBangDashDash(t){t!==m.GREATER_THAN_SIGN&&t!==m.EOF&&this._err(G.nestedComment),this.state=T.COMMENT_END,this._stateCommentEnd(t)}_stateCommentEndDash(t){const r=this.currentToken;switch(t){case m.HYPHEN_MINUS:{this.state=T.COMMENT_END;break}case m.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 m.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentComment(r);break}case m.EXCLAMATION_MARK:{this.state=T.COMMENT_END_BANG;break}case m.HYPHEN_MINUS:{r.data+="-";break}case m.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 m.HYPHEN_MINUS:{r.data+="--!",this.state=T.COMMENT_END_DASH;break}case m.GREATER_THAN_SIGN:{this._err(G.incorrectlyClosedComment),this.state=T.DATA,this.emitCurrentComment(r);break}case m.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:{this.state=T.BEFORE_DOCTYPE_NAME;break}case m.GREATER_THAN_SIGN:{this.state=T.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case m.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(Pn(t))this._createDoctypeToken(String.fromCharCode(Ci(t))),this.state=T.DOCTYPE_NAME;else switch(t){case m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:break;case m.NULL:{this._err(G.unexpectedNullCharacter),this._createDoctypeToken(ze),this.state=T.DOCTYPE_NAME;break}case m.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 m.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:{this.state=T.AFTER_DOCTYPE_NAME;break}case m.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentDoctype(r);break}case m.NULL:{this._err(G.unexpectedNullCharacter),r.name+=ze;break}case m.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.name+=String.fromCodePoint(Pn(t)?Ci(t):t)}}_stateAfterDoctypeName(t){const r=this.currentToken;switch(t){case m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:break;case m.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentDoctype(r);break}case m.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(dt.PUBLIC,!1)?this.state=T.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(dt.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:{this.state=T.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case m.QUOTATION_MARK:{this._err(G.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=T.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case m.APOSTROPHE:{this._err(G.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=T.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case m.GREATER_THAN_SIGN:{this._err(G.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=T.DATA,this.emitCurrentDoctype(r);break}case m.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:break;case m.QUOTATION_MARK:{r.publicId="",this.state=T.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case m.APOSTROPHE:{r.publicId="",this.state=T.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case m.GREATER_THAN_SIGN:{this._err(G.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=T.DATA,this.emitCurrentDoctype(r);break}case m.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 m.QUOTATION_MARK:{this.state=T.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case m.NULL:{this._err(G.unexpectedNullCharacter),r.publicId+=ze;break}case m.GREATER_THAN_SIGN:{this._err(G.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=T.DATA;break}case m.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 m.APOSTROPHE:{this.state=T.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case m.NULL:{this._err(G.unexpectedNullCharacter),r.publicId+=ze;break}case m.GREATER_THAN_SIGN:{this._err(G.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=T.DATA;break}case m.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:{this.state=T.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case m.GREATER_THAN_SIGN:{this.state=T.DATA,this.emitCurrentDoctype(r);break}case m.QUOTATION_MARK:{this._err(G.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case m.APOSTROPHE:{this._err(G.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case m.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:break;case m.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=T.DATA;break}case m.QUOTATION_MARK:{r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case m.APOSTROPHE:{r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case m.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:{this.state=T.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case m.QUOTATION_MARK:{this._err(G.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case m.APOSTROPHE:{this._err(G.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case m.GREATER_THAN_SIGN:{this._err(G.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=T.DATA,this.emitCurrentDoctype(r);break}case m.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:break;case m.QUOTATION_MARK:{r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case m.APOSTROPHE:{r.systemId="",this.state=T.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case m.GREATER_THAN_SIGN:{this._err(G.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=T.DATA,this.emitCurrentDoctype(r);break}case m.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 m.QUOTATION_MARK:{this.state=T.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case m.NULL:{this._err(G.unexpectedNullCharacter),r.systemId+=ze;break}case m.GREATER_THAN_SIGN:{this._err(G.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=T.DATA;break}case m.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 m.APOSTROPHE:{this.state=T.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case m.NULL:{this._err(G.unexpectedNullCharacter),r.systemId+=ze;break}case m.GREATER_THAN_SIGN:{this._err(G.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=T.DATA;break}case m.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 m.SPACE:case m.LINE_FEED:case m.TABULATION:case m.FORM_FEED:break;case m.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=T.DATA;break}case m.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 m.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=T.DATA;break}case m.NULL:{this._err(G.unexpectedNullCharacter);break}case m.EOF:{this.emitCurrentDoctype(r),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case m.RIGHT_SQUARE_BRACKET:{this.state=T.CDATA_SECTION_BRACKET;break}case m.EOF:{this._err(G.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateCdataSectionBracket(t){t===m.RIGHT_SQUARE_BRACKET?this.state=T.CDATA_SECTION_END:(this._emitChars("]"),this.state=T.CDATA_SECTION,this._stateCdataSection(t))}_stateCdataSectionEnd(t){switch(t){case m.GREATER_THAN_SIGN:{this.state=T.DATA;break}case m.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(m.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&Qu(this.preprocessor.peek(1))?T.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(t){Qu(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===m.SEMICOLON&&this._err(G.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t))}}const Yf=new Set([o.DD,o.DT,o.LI,o.OPTGROUP,o.OPTION,o.P,o.RB,o.RP,o.RT,o.RTC]),Wu=new Set([...Yf,o.CAPTION,o.COLGROUP,o.TBODY,o.TD,o.TFOOT,o.TH,o.THEAD,o.TR]),Qs=new Set([o.APPLET,o.CAPTION,o.HTML,o.MARQUEE,o.OBJECT,o.TABLE,o.TD,o.TEMPLATE,o.TH]),q_=new Set([...Qs,o.OL,o.UL]),W_=new Set([...Qs,o.BUTTON]),$u=new Set([o.ANNOTATION_XML,o.MI,o.MN,o.MO,o.MS,o.MTEXT]),Ku=new Set([o.DESC,o.FOREIGN_OBJECT,o.TITLE]),$_=new Set([o.TR,o.TEMPLATE,o.HTML]),K_=new Set([o.TBODY,o.TFOOT,o.THEAD,o.TEMPLATE,o.HTML]),Z_=new Set([o.TABLE,o.TEMPLATE,o.HTML]),X_=new Set([o.TD,o.TH]);class J_{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=o.UNKNOWN,this.current=t}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===o.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===te.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])!==te.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(wo,te.HTML)}popUntilTableCellPopped(){this.popUntilPopped(X_,te.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(Z_,te.HTML)}clearBackToTableBodyContext(){this.clearBackTo(K_,te.HTML)}clearBackToTableRowContext(){this.clearBackTo($_,te.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]===o.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]===o.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 te.HTML:{if(i===t)return!0;if(r.has(i))return!1;break}case te.SVG:{if(Ku.has(i))return!1;break}case te.MATHML:{if($u.has(i))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,Qs)}hasInListItemScope(t){return this.hasInDynamicScope(t,q_)}hasInButtonScope(t){return this.hasInDynamicScope(t,W_)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){const r=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case te.HTML:{if(wo.has(r))return!0;if(Qs.has(r))return!1;break}case te.SVG:{if(Ku.has(r))return!1;break}case te.MATHML:{if($u.has(r))return!1;break}}}return!0}hasInTableScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===te.HTML)switch(this.tagIDs[r]){case t:return!0;case o.TABLE:case o.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===te.HTML)switch(this.tagIDs[t]){case o.TBODY:case o.THEAD:case o.TFOOT:return!0;case o.TABLE:case o.HTML:return!1}return!0}hasInSelectScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===te.HTML)switch(this.tagIDs[r]){case t:return!0;case o.OPTION:case o.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&Yf.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&Wu.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&Wu.has(this.currentTagId);)this.pop()}}const Ga=3;var Ft;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"})(Ft||(Ft={}));const Zu={type:Ft.Marker};class eA{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(t,r){const n=[],i=r.length,s=this.treeAdapter.getTagName(t),a=this.treeAdapter.getNamespaceURI(t);for(let c=0;c<this.entries.length;c++){const u=this.entries[c];if(u.type===Ft.Marker)break;const{element:d}=u;if(this.treeAdapter.getTagName(d)===s&&this.treeAdapter.getNamespaceURI(d)===a){const l=this.treeAdapter.getAttrList(d);l.length===i&&n.push({idx:c,attrs:l})}}return n}_ensureNoahArkCondition(t){if(this.entries.length<Ga)return;const r=this.treeAdapter.getAttrList(t),n=this._getNoahArkConditionCandidates(t,r);if(n.length<Ga)return;const i=new Map(r.map(a=>[a.name,a.value]));let s=0;for(let a=0;a<n.length;a++){const c=n[a];c.attrs.every(u=>i.get(u.name)===u.value)&&(s+=1,s>=Ga&&this.entries.splice(c.idx,1))}}insertMarker(){this.entries.unshift(Zu)}pushElement(t,r){this._ensureNoahArkCondition(t),this.entries.unshift({type:Ft.Element,element:t,token:r})}insertElementAfterBookmark(t,r){const n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:Ft.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(Zu);t===-1?this.entries.length=0:this.entries.splice(0,t+1)}getElementEntryInScopeWithTagName(t){const r=this.entries.find(n=>n.type===Ft.Marker||this.treeAdapter.getTagName(n.element)===t);return r&&r.type===Ft.Element?r:null}getElementEntry(t){return this.entries.find(r=>r.type===Ft.Element&&r.element===t)}}const tr={createDocument(){return{nodeName:"#document",mode:It.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};tr.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(tr.isTextNode(r)){r.value+=t;return}}tr.appendChild(e,tr.createTextNode(t))},insertTextBefore(e,t,r){const n=e.childNodes[e.childNodes.indexOf(r)-1];n&&tr.isTextNode(n)?n.value+=t:tr.insertBefore(e,tr.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}}},Qf="html",tA="about:legacy-compat",rA="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",qf=["+//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//"],nA=[...qf,"-//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"]),Wf=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],sA=[...Wf,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function Xu(e,t){return t.some(r=>e.startsWith(r))}function aA(e){return e.name===Qf&&e.publicId===null&&(e.systemId===null||e.systemId===tA)}function oA(e){if(e.name!==Qf)return It.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===rA)return It.QUIRKS;let{publicId:r}=e;if(r!==null){if(r=r.toLowerCase(),iA.has(r))return It.QUIRKS;let n=t===null?nA:qf;if(Xu(r,n))return It.QUIRKS;if(n=t===null?Wf:sA,Xu(r,n))return It.LIMITED_QUIRKS}return It.NO_QUIRKS}const Ju={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},cA="definitionurl",uA="definitionURL",dA=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])),lA=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:te.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:te.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:te.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:te.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:te.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:te.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:te.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:te.XML}],["xml:space",{prefix:"xml",name:"space",namespace:te.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:te.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:te.XMLNS}]]),fA=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])),hA=new Set([o.B,o.BIG,o.BLOCKQUOTE,o.BODY,o.BR,o.CENTER,o.CODE,o.DD,o.DIV,o.DL,o.DT,o.EM,o.EMBED,o.H1,o.H2,o.H3,o.H4,o.H5,o.H6,o.HEAD,o.HR,o.I,o.IMG,o.LI,o.LISTING,o.MENU,o.META,o.NOBR,o.OL,o.P,o.PRE,o.RUBY,o.S,o.SMALL,o.SPAN,o.STRONG,o.STRIKE,o.SUB,o.SUP,o.TABLE,o.TT,o.U,o.UL,o.VAR]);function mA(e){const t=e.tagID;return t===o.FONT&&e.attrs.some(({name:n})=>n===Sr.COLOR||n===Sr.SIZE||n===Sr.FACE)||hA.has(t)}function $f(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===cA){e.attrs[t].name=uA;break}}function Kf(e){for(let t=0;t<e.attrs.length;t++){const r=dA.get(e.attrs[t].name);r!=null&&(e.attrs[t].name=r)}}function Mc(e){for(let t=0;t<e.attrs.length;t++){const r=lA.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 EA(e){const t=fA.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=Ia(e.tagName))}function gA(e,t){return t===te.MATHML&&(e===o.MI||e===o.MO||e===o.MN||e===o.MS||e===o.MTEXT)}function pA(e,t,r){if(t===te.MATHML&&e===o.ANNOTATION_XML){for(let n=0;n<r.length;n++)if(r[n].name===Sr.ENCODING){const i=r[n].value.toLowerCase();return i===Ju.TEXT_HTML||i===Ju.APPLICATION_XML}}return t===te.SVG&&(e===o.FOREIGN_OBJECT||e===o.DESC||e===o.TITLE)}function TA(e,t,r,n){return(!n||n===te.HTML)&&pA(e,t,r)||(!n||n===te.MATHML)&&gA(e,t)}const _A="hidden",AA=8,IA=3;var A;(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"})(A||(A={}));const bA={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Zf=new Set([o.TABLE,o.TBODY,o.TFOOT,o.THEAD,o.TR]),ed={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:tr,onParseError:null};class yA{constructor(t,r,n=null,i=null){this.fragmentContext=n,this.scriptHandler=i,this.currentToken=null,this.stopped=!1,this.insertionMode=A.INITIAL,this.originalInsertionMode=A.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 Q_(this.options,this),this.activeFormattingElements=new eA(this.treeAdapter),this.fragmentContextID=n?Ia(this.treeAdapter.getTagName(n)):o.UNKNOWN,this._setContextModes(n??this.document,this.fragmentContextID),this.openElements=new J_(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(v.TEMPLATE,te.HTML,[]));const i=n.treeAdapter.createElement("documentmock",te.HTML,[]),s=new this(n,i,t);return s.fragmentContextID===o.TEMPLATE&&s.tmplInsertionModeStack.unshift(A.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:bA,a={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(a)}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,a;this.openElements.stackTop===0&&this.fragmentContext?(s=this.fragmentContext,a=this.fragmentContextID):{current:s,currentTagId:a}=this.openElements,this._setContextModes(s,a)}}_setContextModes(t,r){const n=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===te.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&t!==void 0&&r!==void 0&&!this._isIntegrationPoint(r,t)}_switchToTextParsing(t,r){this._insertElement(t,te.HTML),this.tokenizer.state=r,this.originalInsertionMode=this.insertionMode,this.insertionMode=A.TEXT}switchToPlaintextParsing(){this.insertionMode=A.TEXT,this.originalInsertionMode=A.IN_BODY,this.tokenizer.state=ft.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)===v.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==te.HTML))switch(this.fragmentContextID){case o.TITLE:case o.TEXTAREA:{this.tokenizer.state=ft.RCDATA;break}case o.STYLE:case o.XMP:case o.IFRAME:case o.NOEMBED:case o.NOFRAMES:case o.NOSCRIPT:{this.tokenizer.state=ft.RAWTEXT;break}case o.SCRIPT:{this.tokenizer.state=ft.SCRIPT_DATA;break}case o.PLAINTEXT:{this.tokenizer.state=ft.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 a=this.treeAdapter.getChildNodes(this.document).find(c=>this.treeAdapter.isDocumentTypeNode(c));a&&this.treeAdapter.setNodeSourceCodeLocation(a,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,te.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,r)}_insertTemplate(t){const r=this.treeAdapter.createElement(t.tagName,te.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(v.HTML,te.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,o.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,a=i[s-1];if(this.treeAdapter.getNodeSourceCodeLocation(a)){const{endLine:u,endCol:d,endOffset:l}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(a,{endLine:u,endCol:d,endOffset:l})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,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===ve.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===o.SVG&&this.treeAdapter.getTagName(r)===v.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(r)===te.MATHML?!1:this.tokenizer.inForeignNode||(t.tagID===o.MGLYPH||t.tagID===o.MALIGNMARK)&&n!==void 0&&!this._isIntegrationPoint(n,r,te.HTML)}_processToken(t){switch(t.type){case ve.CHARACTER:{this.onCharacter(t);break}case ve.NULL_CHARACTER:{this.onNullCharacter(t);break}case ve.COMMENT:{this.onComment(t);break}case ve.DOCTYPE:{this.onDoctype(t);break}case ve.START_TAG:{this._processStartTag(t);break}case ve.END_TAG:{this.onEndTag(t);break}case ve.EOF:{this.onEof(t);break}case ve.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,r,n){const i=this.treeAdapter.getNamespaceURI(r),s=this.treeAdapter.getAttrList(r);return TA(t,i,s,n)}_reconstructActiveFormattingElements(){const t=this.activeFormattingElements.entries.length;if(t){const r=this.activeFormattingElements.entries.findIndex(i=>i.type===Ft.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=A.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(o.P),this.openElements.popUntilTagNamePopped(o.P)}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case o.TR:{this.insertionMode=A.IN_ROW;return}case o.TBODY:case o.THEAD:case o.TFOOT:{this.insertionMode=A.IN_TABLE_BODY;return}case o.CAPTION:{this.insertionMode=A.IN_CAPTION;return}case o.COLGROUP:{this.insertionMode=A.IN_COLUMN_GROUP;return}case o.TABLE:{this.insertionMode=A.IN_TABLE;return}case o.BODY:{this.insertionMode=A.IN_BODY;return}case o.FRAMESET:{this.insertionMode=A.IN_FRAMESET;return}case o.SELECT:{this._resetInsertionModeForSelect(t);return}case o.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case o.HTML:{this.insertionMode=this.headElement?A.AFTER_HEAD:A.BEFORE_HEAD;return}case o.TD:case o.TH:{if(t>0){this.insertionMode=A.IN_CELL;return}break}case o.HEAD:{if(t>0){this.insertionMode=A.IN_HEAD;return}break}}this.insertionMode=A.IN_BODY}_resetInsertionModeForSelect(t){if(t>0)for(let r=t-1;r>0;r--){const n=this.openElements.tagIDs[r];if(n===o.TEMPLATE)break;if(n===o.TABLE){this.insertionMode=A.IN_SELECT_IN_TABLE;return}}this.insertionMode=A.IN_SELECT}_isElementCausesFosterParenting(t){return Zf.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 o.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(r)===te.HTML)return{parent:this.treeAdapter.getTemplateContent(r),beforeElement:null};break}case o.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 j_[n].has(r)}onCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){JI(this,t);return}switch(this.insertionMode){case A.INITIAL:{yn(this,t);break}case A.BEFORE_HTML:{Un(this,t);break}case A.BEFORE_HEAD:{Bn(this,t);break}case A.IN_HEAD:{Hn(this,t);break}case A.IN_HEAD_NO_SCRIPT:{Fn(this,t);break}case A.AFTER_HEAD:{zn(this,t);break}case A.IN_BODY:case A.IN_CAPTION:case A.IN_CELL:case A.IN_TEMPLATE:{Jf(this,t);break}case A.TEXT:case A.IN_SELECT:case A.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case A.IN_TABLE:case A.IN_TABLE_BODY:case A.IN_ROW:{Ya(this,t);break}case A.IN_TABLE_TEXT:{sh(this,t);break}case A.IN_COLUMN_GROUP:{qs(this,t);break}case A.AFTER_BODY:{Ws(this,t);break}case A.AFTER_AFTER_BODY:{Qi(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){XI(this,t);return}switch(this.insertionMode){case A.INITIAL:{yn(this,t);break}case A.BEFORE_HTML:{Un(this,t);break}case A.BEFORE_HEAD:{Bn(this,t);break}case A.IN_HEAD:{Hn(this,t);break}case A.IN_HEAD_NO_SCRIPT:{Fn(this,t);break}case A.AFTER_HEAD:{zn(this,t);break}case A.TEXT:{this._insertCharacters(t);break}case A.IN_TABLE:case A.IN_TABLE_BODY:case A.IN_ROW:{Ya(this,t);break}case A.IN_COLUMN_GROUP:{qs(this,t);break}case A.AFTER_BODY:{Ws(this,t);break}case A.AFTER_AFTER_BODY:{Qi(this,t);break}}}onComment(t){if(this.skipNextNewLine=!1,this.currentNotInHTML){Do(this,t);return}switch(this.insertionMode){case A.INITIAL:case A.BEFORE_HTML:case A.BEFORE_HEAD:case A.IN_HEAD:case A.IN_HEAD_NO_SCRIPT:case A.AFTER_HEAD:case A.IN_BODY:case A.IN_TABLE:case A.IN_CAPTION:case A.IN_COLUMN_GROUP:case A.IN_TABLE_BODY:case A.IN_ROW:case A.IN_CELL:case A.IN_SELECT:case A.IN_SELECT_IN_TABLE:case A.IN_TEMPLATE:case A.IN_FRAMESET:case A.AFTER_FRAMESET:{Do(this,t);break}case A.IN_TABLE_TEXT:{Nn(this,t);break}case A.AFTER_BODY:{CA(this,t);break}case A.AFTER_AFTER_BODY:case A.AFTER_AFTER_FRAMESET:{RA(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case A.INITIAL:{LA(this,t);break}case A.BEFORE_HEAD:case A.IN_HEAD:case A.IN_HEAD_NO_SCRIPT:case A.AFTER_HEAD:{this._err(t,G.misplacedDoctype);break}case A.IN_TABLE_TEXT:{Nn(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)?eb(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case A.INITIAL:{yn(this,t);break}case A.BEFORE_HTML:{PA(this,t);break}case A.BEFORE_HEAD:{kA(this,t);break}case A.IN_HEAD:{Pt(this,t);break}case A.IN_HEAD_NO_SCRIPT:{BA(this,t);break}case A.AFTER_HEAD:{FA(this,t);break}case A.IN_BODY:{nt(this,t);break}case A.IN_TABLE:{an(this,t);break}case A.IN_TABLE_TEXT:{Nn(this,t);break}case A.IN_CAPTION:{xI(this,t);break}case A.IN_COLUMN_GROUP:{Lc(this,t);break}case A.IN_TABLE_BODY:{Na(this,t);break}case A.IN_ROW:{wa(this,t);break}case A.IN_CELL:{HI(this,t);break}case A.IN_SELECT:{ch(this,t);break}case A.IN_SELECT_IN_TABLE:{zI(this,t);break}case A.IN_TEMPLATE:{VI(this,t);break}case A.AFTER_BODY:{YI(this,t);break}case A.IN_FRAMESET:{QI(this,t);break}case A.AFTER_FRAMESET:{WI(this,t);break}case A.AFTER_AFTER_BODY:{KI(this,t);break}case A.AFTER_AFTER_FRAMESET:{ZI(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 A.INITIAL:{yn(this,t);break}case A.BEFORE_HTML:{vA(this,t);break}case A.BEFORE_HEAD:{xA(this,t);break}case A.IN_HEAD:{UA(this,t);break}case A.IN_HEAD_NO_SCRIPT:{HA(this,t);break}case A.AFTER_HEAD:{zA(this,t);break}case A.IN_BODY:{ya(this,t);break}case A.TEXT:{DI(this,t);break}case A.IN_TABLE:{ci(this,t);break}case A.IN_TABLE_TEXT:{Nn(this,t);break}case A.IN_CAPTION:{UI(this,t);break}case A.IN_COLUMN_GROUP:{BI(this,t);break}case A.IN_TABLE_BODY:{So(this,t);break}case A.IN_ROW:{oh(this,t);break}case A.IN_CELL:{FI(this,t);break}case A.IN_SELECT:{uh(this,t);break}case A.IN_SELECT_IN_TABLE:{jI(this,t);break}case A.IN_TEMPLATE:{GI(this,t);break}case A.AFTER_BODY:{lh(this,t);break}case A.IN_FRAMESET:{qI(this,t);break}case A.AFTER_FRAMESET:{$I(this,t);break}case A.AFTER_AFTER_BODY:{Qi(this,t);break}}}onEof(t){switch(this.insertionMode){case A.INITIAL:{yn(this,t);break}case A.BEFORE_HTML:{Un(this,t);break}case A.BEFORE_HEAD:{Bn(this,t);break}case A.IN_HEAD:{Hn(this,t);break}case A.IN_HEAD_NO_SCRIPT:{Fn(this,t);break}case A.AFTER_HEAD:{zn(this,t);break}case A.IN_BODY:case A.IN_TABLE:case A.IN_CAPTION:case A.IN_COLUMN_GROUP:case A.IN_TABLE_BODY:case A.IN_ROW:case A.IN_CELL:case A.IN_SELECT:case A.IN_SELECT_IN_TABLE:{nh(this,t);break}case A.TEXT:{SI(this,t);break}case A.IN_TABLE_TEXT:{Nn(this,t);break}case A.IN_TEMPLATE:{dh(this,t);break}case A.AFTER_BODY:case A.IN_FRAMESET:case A.AFTER_FRAMESET:case A.AFTER_AFTER_BODY:case A.AFTER_AFTER_FRAMESET:{Rc(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,t.chars.charCodeAt(0)===m.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 A.IN_HEAD:case A.IN_HEAD_NO_SCRIPT:case A.AFTER_HEAD:case A.TEXT:case A.IN_COLUMN_GROUP:case A.IN_SELECT:case A.IN_SELECT_IN_TABLE:case A.IN_FRAMESET:case A.AFTER_FRAMESET:{this._insertCharacters(t);break}case A.IN_BODY:case A.IN_CAPTION:case A.IN_CELL:case A.IN_TEMPLATE:case A.AFTER_BODY:case A.AFTER_AFTER_BODY:case A.AFTER_AFTER_FRAMESET:{Xf(this,t);break}case A.IN_TABLE:case A.IN_TABLE_BODY:case A.IN_ROW:{Ya(this,t);break}case A.IN_TABLE_TEXT:{ih(this,t);break}}}}function NA(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):rh(e,t),r}function wA(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 DA(e,t,r){let n=t,i=e.openElements.getCommonAncestor(t);for(let s=0,a=i;a!==r;s++,a=i){i=e.openElements.getCommonAncestor(a);const c=e.activeFormattingElements.getElementEntry(a),u=c&&s>=IA;!c||u?(u&&e.activeFormattingElements.removeEntry(c),e.openElements.remove(a)):(a=SA(e,c),n===t&&(e.activeFormattingElements.bookmark=c),e.treeAdapter.detachNode(n),e.treeAdapter.appendChild(a,n),n=a)}return n}function SA(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 OA(e,t,r){const n=e.treeAdapter.getTagName(t),i=Ia(n);if(e._isElementCausesFosterParenting(i))e._fosterParentElement(r);else{const s=e.treeAdapter.getNamespaceURI(t);i===o.TEMPLATE&&s===te.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,r)}}function MA(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 Cc(e,t){for(let r=0;r<AA;r++){const n=NA(e,t);if(!n)break;const i=wA(e,n);if(!i)break;e.activeFormattingElements.bookmark=n;const s=DA(e,i,n.element),a=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(s),a&&OA(e,a,s),MA(e,i,n)}}function Do(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function CA(e,t){e._appendCommentNode(t,e.openElements.items[0])}function RA(e,t){e._appendCommentNode(t,e.document)}function Rc(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],a=e.treeAdapter.getNodeSourceCodeLocation(s);a&&!a.endTag&&e._setEndLocation(s,t)}}}}function LA(e,t){e._setDocumentType(t);const r=t.forceQuirks?It.QUIRKS:oA(t);aA(t)||e._err(t,G.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,r),e.insertionMode=A.BEFORE_HTML}function yn(e,t){e._err(t,G.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,It.QUIRKS),e.insertionMode=A.BEFORE_HTML,e._processToken(t)}function PA(e,t){t.tagID===o.HTML?(e._insertElement(t,te.HTML),e.insertionMode=A.BEFORE_HEAD):Un(e,t)}function vA(e,t){const r=t.tagID;(r===o.HTML||r===o.HEAD||r===o.BODY||r===o.BR)&&Un(e,t)}function Un(e,t){e._insertFakeRootElement(),e.insertionMode=A.BEFORE_HEAD,e._processToken(t)}function kA(e,t){switch(t.tagID){case o.HTML:{nt(e,t);break}case o.HEAD:{e._insertElement(t,te.HTML),e.headElement=e.openElements.current,e.insertionMode=A.IN_HEAD;break}default:Bn(e,t)}}function xA(e,t){const r=t.tagID;r===o.HEAD||r===o.BODY||r===o.HTML||r===o.BR?Bn(e,t):e._err(t,G.endTagWithoutMatchingOpenElement)}function Bn(e,t){e._insertFakeElement(v.HEAD,o.HEAD),e.headElement=e.openElements.current,e.insertionMode=A.IN_HEAD,e._processToken(t)}function Pt(e,t){switch(t.tagID){case o.HTML:{nt(e,t);break}case o.BASE:case o.BASEFONT:case o.BGSOUND:case o.LINK:case o.META:{e._appendElement(t,te.HTML),t.ackSelfClosing=!0;break}case o.TITLE:{e._switchToTextParsing(t,ft.RCDATA);break}case o.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,ft.RAWTEXT):(e._insertElement(t,te.HTML),e.insertionMode=A.IN_HEAD_NO_SCRIPT);break}case o.NOFRAMES:case o.STYLE:{e._switchToTextParsing(t,ft.RAWTEXT);break}case o.SCRIPT:{e._switchToTextParsing(t,ft.SCRIPT_DATA);break}case o.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=A.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(A.IN_TEMPLATE);break}case o.HEAD:{e._err(t,G.misplacedStartTagForHeadElement);break}default:Hn(e,t)}}function UA(e,t){switch(t.tagID){case o.HEAD:{e.openElements.pop(),e.insertionMode=A.AFTER_HEAD;break}case o.BODY:case o.BR:case o.HTML:{Hn(e,t);break}case o.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!==o.TEMPLATE&&e._err(t,G.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(o.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,G.endTagWithoutMatchingOpenElement)}function Hn(e,t){e.openElements.pop(),e.insertionMode=A.AFTER_HEAD,e._processToken(t)}function BA(e,t){switch(t.tagID){case o.HTML:{nt(e,t);break}case o.BASEFONT:case o.BGSOUND:case o.HEAD:case o.LINK:case o.META:case o.NOFRAMES:case o.STYLE:{Pt(e,t);break}case o.NOSCRIPT:{e._err(t,G.nestedNoscriptInHead);break}default:Fn(e,t)}}function HA(e,t){switch(t.tagID){case o.NOSCRIPT:{e.openElements.pop(),e.insertionMode=A.IN_HEAD;break}case o.BR:{Fn(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function Fn(e,t){const r=t.type===ve.EOF?G.openElementsLeftAfterEof:G.disallowedContentInNoscriptInHead;e._err(t,r),e.openElements.pop(),e.insertionMode=A.IN_HEAD,e._processToken(t)}function FA(e,t){switch(t.tagID){case o.HTML:{nt(e,t);break}case o.BODY:{e._insertElement(t,te.HTML),e.framesetOk=!1,e.insertionMode=A.IN_BODY;break}case o.FRAMESET:{e._insertElement(t,te.HTML),e.insertionMode=A.IN_FRAMESET;break}case o.BASE:case o.BASEFONT:case o.BGSOUND:case o.LINK:case o.META:case o.NOFRAMES:case o.SCRIPT:case o.STYLE:case o.TEMPLATE:case o.TITLE:{e._err(t,G.abandonedHeadElementChild),e.openElements.push(e.headElement,o.HEAD),Pt(e,t),e.openElements.remove(e.headElement);break}case o.HEAD:{e._err(t,G.misplacedStartTagForHeadElement);break}default:zn(e,t)}}function zA(e,t){switch(t.tagID){case o.BODY:case o.HTML:case o.BR:{zn(e,t);break}case o.TEMPLATE:{vr(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function zn(e,t){e._insertFakeElement(v.BODY,o.BODY),e.insertionMode=A.IN_BODY,ba(e,t)}function ba(e,t){switch(t.type){case ve.CHARACTER:{Jf(e,t);break}case ve.WHITESPACE_CHARACTER:{Xf(e,t);break}case ve.COMMENT:{Do(e,t);break}case ve.START_TAG:{nt(e,t);break}case ve.END_TAG:{ya(e,t);break}case ve.EOF:{nh(e,t);break}}}function Xf(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function Jf(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function jA(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function VA(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(r,t.attrs))}function GA(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&r&&(e.treeAdapter.detachNode(r),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,te.HTML),e.insertionMode=A.IN_FRAMESET)}function YA(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,te.HTML)}function QA(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&wo.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,te.HTML)}function qA(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,te.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function WA(e,t){const r=e.openElements.tmplCount>0;(!e.formElement||r)&&(e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,te.HTML),r||(e.formElement=e.openElements.current))}function $A(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===o.LI&&i===o.LI||(r===o.DD||r===o.DT)&&(i===o.DD||i===o.DT)){e.openElements.generateImpliedEndTagsWithExclusion(i),e.openElements.popUntilTagNamePopped(i);break}if(i!==o.ADDRESS&&i!==o.DIV&&i!==o.P&&e._isSpecialElement(e.openElements.items[n],i))break}e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,te.HTML)}function KA(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,te.HTML),e.tokenizer.state=ft.PLAINTEXT}function ZA(e,t){e.openElements.hasInScope(o.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,te.HTML),e.framesetOk=!1}function XA(e,t){const r=e.activeFormattingElements.getElementEntryInScopeWithTagName(v.A);r&&(Cc(e,t),e.openElements.remove(r.element),e.activeFormattingElements.removeEntry(r)),e._reconstructActiveFormattingElements(),e._insertElement(t,te.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function JA(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,te.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function eI(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(o.NOBR)&&(Cc(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,te.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function tI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,te.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function rI(e,t){e.treeAdapter.getDocumentMode(e.document)!==It.QUIRKS&&e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,te.HTML),e.framesetOk=!1,e.insertionMode=A.IN_TABLE}function eh(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,te.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function th(e){const t=Vf(e,Sr.TYPE);return t!=null&&t.toLowerCase()===_A}function nI(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,te.HTML),th(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function iI(e,t){e._appendElement(t,te.HTML),t.ackSelfClosing=!0}function sI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._appendElement(t,te.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function aI(e,t){t.tagName=v.IMG,t.tagID=o.IMG,eh(e,t)}function oI(e,t){e._insertElement(t,te.HTML),e.skipNextNewLine=!0,e.tokenizer.state=ft.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=A.TEXT}function cI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,ft.RAWTEXT)}function uI(e,t){e.framesetOk=!1,e._switchToTextParsing(t,ft.RAWTEXT)}function td(e,t){e._switchToTextParsing(t,ft.RAWTEXT)}function dI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,te.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===A.IN_TABLE||e.insertionMode===A.IN_CAPTION||e.insertionMode===A.IN_TABLE_BODY||e.insertionMode===A.IN_ROW||e.insertionMode===A.IN_CELL?A.IN_SELECT_IN_TABLE:A.IN_SELECT}function lI(e,t){e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,te.HTML)}function fI(e,t){e.openElements.hasInScope(o.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,te.HTML)}function hI(e,t){e.openElements.hasInScope(o.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(o.RTC),e._insertElement(t,te.HTML)}function mI(e,t){e._reconstructActiveFormattingElements(),$f(t),Mc(t),t.selfClosing?e._appendElement(t,te.MATHML):e._insertElement(t,te.MATHML),t.ackSelfClosing=!0}function EI(e,t){e._reconstructActiveFormattingElements(),Kf(t),Mc(t),t.selfClosing?e._appendElement(t,te.SVG):e._insertElement(t,te.SVG),t.ackSelfClosing=!0}function rd(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,te.HTML)}function nt(e,t){switch(t.tagID){case o.I:case o.S:case o.B:case o.U:case o.EM:case o.TT:case o.BIG:case o.CODE:case o.FONT:case o.SMALL:case o.STRIKE:case o.STRONG:{JA(e,t);break}case o.A:{XA(e,t);break}case o.H1:case o.H2:case o.H3:case o.H4:case o.H5:case o.H6:{QA(e,t);break}case o.P:case o.DL:case o.OL:case o.UL:case o.DIV:case o.DIR:case o.NAV:case o.MAIN:case o.MENU:case o.ASIDE:case o.CENTER:case o.FIGURE:case o.FOOTER:case o.HEADER:case o.HGROUP:case o.DIALOG:case o.DETAILS:case o.ADDRESS:case o.ARTICLE:case o.SEARCH:case o.SECTION:case o.SUMMARY:case o.FIELDSET:case o.BLOCKQUOTE:case o.FIGCAPTION:{YA(e,t);break}case o.LI:case o.DD:case o.DT:{$A(e,t);break}case o.BR:case o.IMG:case o.WBR:case o.AREA:case o.EMBED:case o.KEYGEN:{eh(e,t);break}case o.HR:{sI(e,t);break}case o.RB:case o.RTC:{fI(e,t);break}case o.RT:case o.RP:{hI(e,t);break}case o.PRE:case o.LISTING:{qA(e,t);break}case o.XMP:{cI(e,t);break}case o.SVG:{EI(e,t);break}case o.HTML:{jA(e,t);break}case o.BASE:case o.LINK:case o.META:case o.STYLE:case o.TITLE:case o.SCRIPT:case o.BGSOUND:case o.BASEFONT:case o.TEMPLATE:{Pt(e,t);break}case o.BODY:{VA(e,t);break}case o.FORM:{WA(e,t);break}case o.NOBR:{eI(e,t);break}case o.MATH:{mI(e,t);break}case o.TABLE:{rI(e,t);break}case o.INPUT:{nI(e,t);break}case o.PARAM:case o.TRACK:case o.SOURCE:{iI(e,t);break}case o.IMAGE:{aI(e,t);break}case o.BUTTON:{ZA(e,t);break}case o.APPLET:case o.OBJECT:case o.MARQUEE:{tI(e,t);break}case o.IFRAME:{uI(e,t);break}case o.SELECT:{dI(e,t);break}case o.OPTION:case o.OPTGROUP:{lI(e,t);break}case o.NOEMBED:case o.NOFRAMES:{td(e,t);break}case o.FRAMESET:{GA(e,t);break}case o.TEXTAREA:{oI(e,t);break}case o.NOSCRIPT:{e.options.scriptingEnabled?td(e,t):rd(e,t);break}case o.PLAINTEXT:{KA(e,t);break}case o.COL:case o.TH:case o.TD:case o.TR:case o.HEAD:case o.FRAME:case o.TBODY:case o.TFOOT:case o.THEAD:case o.CAPTION:case o.COLGROUP:break;default:rd(e,t)}}function gI(e,t){if(e.openElements.hasInScope(o.BODY)&&(e.insertionMode=A.AFTER_BODY,e.options.sourceCodeLocationInfo)){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e._setEndLocation(r,t)}}function pI(e,t){e.openElements.hasInScope(o.BODY)&&(e.insertionMode=A.AFTER_BODY,lh(e,t))}function TI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r))}function _I(e){const t=e.openElements.tmplCount>0,{formElement:r}=e;t||(e.formElement=null),(r||t)&&e.openElements.hasInScope(o.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(o.FORM):r&&e.openElements.remove(r))}function AI(e){e.openElements.hasInButtonScope(o.P)||e._insertFakeElement(v.P,o.P),e._closePElement()}function II(e){e.openElements.hasInListItemScope(o.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(o.LI),e.openElements.popUntilTagNamePopped(o.LI))}function bI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r))}function yI(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function NI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker())}function wI(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(v.BR,o.BR),e.openElements.pop(),e.framesetOk=!1}function rh(e,t){const r=t.tagName,n=t.tagID;for(let i=e.openElements.stackTop;i>0;i--){const s=e.openElements.items[i],a=e.openElements.tagIDs[i];if(n===a&&(n!==o.UNKNOWN||e.treeAdapter.getTagName(s)===r)){e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.stackTop>=i&&e.openElements.shortenToLength(i);break}if(e._isSpecialElement(s,a))break}}function ya(e,t){switch(t.tagID){case o.A:case o.B:case o.I:case o.S:case o.U:case o.EM:case o.TT:case o.BIG:case o.CODE:case o.FONT:case o.NOBR:case o.SMALL:case o.STRIKE:case o.STRONG:{Cc(e,t);break}case o.P:{AI(e);break}case o.DL:case o.UL:case o.OL:case o.DIR:case o.DIV:case o.NAV:case o.PRE:case o.MAIN:case o.MENU:case o.ASIDE:case o.BUTTON:case o.CENTER:case o.FIGURE:case o.FOOTER:case o.HEADER:case o.HGROUP:case o.DIALOG:case o.ADDRESS:case o.ARTICLE:case o.DETAILS:case o.SEARCH:case o.SECTION:case o.SUMMARY:case o.LISTING:case o.FIELDSET:case o.BLOCKQUOTE:case o.FIGCAPTION:{TI(e,t);break}case o.LI:{II(e);break}case o.DD:case o.DT:{bI(e,t);break}case o.H1:case o.H2:case o.H3:case o.H4:case o.H5:case o.H6:{yI(e);break}case o.BR:{wI(e);break}case o.BODY:{gI(e,t);break}case o.HTML:{pI(e,t);break}case o.FORM:{_I(e);break}case o.APPLET:case o.OBJECT:case o.MARQUEE:{NI(e,t);break}case o.TEMPLATE:{vr(e,t);break}default:rh(e,t)}}function nh(e,t){e.tmplInsertionModeStack.length>0?dh(e,t):Rc(e,t)}function DI(e,t){var r;t.tagID===o.SCRIPT&&((r=e.scriptHandler)===null||r===void 0||r.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function SI(e,t){e._err(t,G.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function Ya(e,t){if(e.openElements.currentTagId!==void 0&&Zf.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=A.IN_TABLE_TEXT,t.type){case ve.CHARACTER:{sh(e,t);break}case ve.WHITESPACE_CHARACTER:{ih(e,t);break}}else Ai(e,t)}function OI(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,te.HTML),e.insertionMode=A.IN_CAPTION}function MI(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,te.HTML),e.insertionMode=A.IN_COLUMN_GROUP}function CI(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(v.COLGROUP,o.COLGROUP),e.insertionMode=A.IN_COLUMN_GROUP,Lc(e,t)}function RI(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,te.HTML),e.insertionMode=A.IN_TABLE_BODY}function LI(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(v.TBODY,o.TBODY),e.insertionMode=A.IN_TABLE_BODY,Na(e,t)}function PI(e,t){e.openElements.hasInTableScope(o.TABLE)&&(e.openElements.popUntilTagNamePopped(o.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function vI(e,t){th(t)?e._appendElement(t,te.HTML):Ai(e,t),t.ackSelfClosing=!0}function kI(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,te.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function an(e,t){switch(t.tagID){case o.TD:case o.TH:case o.TR:{LI(e,t);break}case o.STYLE:case o.SCRIPT:case o.TEMPLATE:{Pt(e,t);break}case o.COL:{CI(e,t);break}case o.FORM:{kI(e,t);break}case o.TABLE:{PI(e,t);break}case o.TBODY:case o.TFOOT:case o.THEAD:{RI(e,t);break}case o.INPUT:{vI(e,t);break}case o.CAPTION:{OI(e,t);break}case o.COLGROUP:{MI(e,t);break}default:Ai(e,t)}}function ci(e,t){switch(t.tagID){case o.TABLE:{e.openElements.hasInTableScope(o.TABLE)&&(e.openElements.popUntilTagNamePopped(o.TABLE),e._resetInsertionMode());break}case o.TEMPLATE:{vr(e,t);break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:case o.TBODY:case o.TD:case o.TFOOT:case o.TH:case o.THEAD:case o.TR:break;default:Ai(e,t)}}function Ai(e,t){const r=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,ba(e,t),e.fosterParentingEnabled=r}function ih(e,t){e.pendingCharacterTokens.push(t)}function sh(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function Nn(e,t){let r=0;if(e.hasNonWhitespacePendingCharacterToken)for(;r<e.pendingCharacterTokens.length;r++)Ai(e,e.pendingCharacterTokens[r]);else for(;r<e.pendingCharacterTokens.length;r++)e._insertCharacters(e.pendingCharacterTokens[r]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}const ah=new Set([o.CAPTION,o.COL,o.COLGROUP,o.TBODY,o.TD,o.TFOOT,o.TH,o.THEAD,o.TR]);function xI(e,t){const r=t.tagID;ah.has(r)?e.openElements.hasInTableScope(o.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=A.IN_TABLE,an(e,t)):nt(e,t)}function UI(e,t){const r=t.tagID;switch(r){case o.CAPTION:case o.TABLE:{e.openElements.hasInTableScope(o.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=A.IN_TABLE,r===o.TABLE&&ci(e,t));break}case o.BODY:case o.COL:case o.COLGROUP:case o.HTML:case o.TBODY:case o.TD:case o.TFOOT:case o.TH:case o.THEAD:case o.TR:break;default:ya(e,t)}}function Lc(e,t){switch(t.tagID){case o.HTML:{nt(e,t);break}case o.COL:{e._appendElement(t,te.HTML),t.ackSelfClosing=!0;break}case o.TEMPLATE:{Pt(e,t);break}default:qs(e,t)}}function BI(e,t){switch(t.tagID){case o.COLGROUP:{e.openElements.currentTagId===o.COLGROUP&&(e.openElements.pop(),e.insertionMode=A.IN_TABLE);break}case o.TEMPLATE:{vr(e,t);break}case o.COL:break;default:qs(e,t)}}function qs(e,t){e.openElements.currentTagId===o.COLGROUP&&(e.openElements.pop(),e.insertionMode=A.IN_TABLE,e._processToken(t))}function Na(e,t){switch(t.tagID){case o.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,te.HTML),e.insertionMode=A.IN_ROW;break}case o.TH:case o.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(v.TR,o.TR),e.insertionMode=A.IN_ROW,wa(e,t);break}case o.CAPTION:case o.COL:case o.COLGROUP:case o.TBODY:case o.TFOOT:case o.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE,an(e,t));break}default:an(e,t)}}function So(e,t){const r=t.tagID;switch(t.tagID){case o.TBODY:case o.TFOOT:case o.THEAD:{e.openElements.hasInTableScope(r)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE);break}case o.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE,ci(e,t));break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:case o.TD:case o.TH:case o.TR:break;default:ci(e,t)}}function wa(e,t){switch(t.tagID){case o.TH:case o.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,te.HTML),e.insertionMode=A.IN_CELL,e.activeFormattingElements.insertMarker();break}case o.CAPTION:case o.COL:case o.COLGROUP:case o.TBODY:case o.TFOOT:case o.THEAD:case o.TR:{e.openElements.hasInTableScope(o.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE_BODY,Na(e,t));break}default:an(e,t)}}function oh(e,t){switch(t.tagID){case o.TR:{e.openElements.hasInTableScope(o.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE_BODY);break}case o.TABLE:{e.openElements.hasInTableScope(o.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE_BODY,So(e,t));break}case o.TBODY:case o.TFOOT:case o.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(o.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE_BODY,So(e,t));break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:case o.TD:case o.TH:break;default:ci(e,t)}}function HI(e,t){const r=t.tagID;ah.has(r)?(e.openElements.hasInTableScope(o.TD)||e.openElements.hasInTableScope(o.TH))&&(e._closeTableCell(),wa(e,t)):nt(e,t)}function FI(e,t){const r=t.tagID;switch(r){case o.TD:case o.TH:{e.openElements.hasInTableScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=A.IN_ROW);break}case o.TABLE:case o.TBODY:case o.TFOOT:case o.THEAD:case o.TR:{e.openElements.hasInTableScope(r)&&(e._closeTableCell(),oh(e,t));break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:break;default:ya(e,t)}}function ch(e,t){switch(t.tagID){case o.HTML:{nt(e,t);break}case o.OPTION:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e._insertElement(t,te.HTML);break}case o.OPTGROUP:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e.openElements.currentTagId===o.OPTGROUP&&e.openElements.pop(),e._insertElement(t,te.HTML);break}case o.HR:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e.openElements.currentTagId===o.OPTGROUP&&e.openElements.pop(),e._appendElement(t,te.HTML),t.ackSelfClosing=!0;break}case o.INPUT:case o.KEYGEN:case o.TEXTAREA:case o.SELECT:{e.openElements.hasInSelectScope(o.SELECT)&&(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode(),t.tagID!==o.SELECT&&e._processStartTag(t));break}case o.SCRIPT:case o.TEMPLATE:{Pt(e,t);break}}}function uh(e,t){switch(t.tagID){case o.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===o.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===o.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===o.OPTGROUP&&e.openElements.pop();break}case o.OPTION:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop();break}case o.SELECT:{e.openElements.hasInSelectScope(o.SELECT)&&(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode());break}case o.TEMPLATE:{vr(e,t);break}}}function zI(e,t){const r=t.tagID;r===o.CAPTION||r===o.TABLE||r===o.TBODY||r===o.TFOOT||r===o.THEAD||r===o.TR||r===o.TD||r===o.TH?(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode(),e._processStartTag(t)):ch(e,t)}function jI(e,t){const r=t.tagID;r===o.CAPTION||r===o.TABLE||r===o.TBODY||r===o.TFOOT||r===o.THEAD||r===o.TR||r===o.TD||r===o.TH?e.openElements.hasInTableScope(r)&&(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode(),e.onEndTag(t)):uh(e,t)}function VI(e,t){switch(t.tagID){case o.BASE:case o.BASEFONT:case o.BGSOUND:case o.LINK:case o.META:case o.NOFRAMES:case o.SCRIPT:case o.STYLE:case o.TEMPLATE:case o.TITLE:{Pt(e,t);break}case o.CAPTION:case o.COLGROUP:case o.TBODY:case o.TFOOT:case o.THEAD:{e.tmplInsertionModeStack[0]=A.IN_TABLE,e.insertionMode=A.IN_TABLE,an(e,t);break}case o.COL:{e.tmplInsertionModeStack[0]=A.IN_COLUMN_GROUP,e.insertionMode=A.IN_COLUMN_GROUP,Lc(e,t);break}case o.TR:{e.tmplInsertionModeStack[0]=A.IN_TABLE_BODY,e.insertionMode=A.IN_TABLE_BODY,Na(e,t);break}case o.TD:case o.TH:{e.tmplInsertionModeStack[0]=A.IN_ROW,e.insertionMode=A.IN_ROW,wa(e,t);break}default:e.tmplInsertionModeStack[0]=A.IN_BODY,e.insertionMode=A.IN_BODY,nt(e,t)}}function GI(e,t){t.tagID===o.TEMPLATE&&vr(e,t)}function dh(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(o.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):Rc(e,t)}function YI(e,t){t.tagID===o.HTML?nt(e,t):Ws(e,t)}function lh(e,t){var r;if(t.tagID===o.HTML){if(e.fragmentContext||(e.insertionMode=A.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===o.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 Ws(e,t)}function Ws(e,t){e.insertionMode=A.IN_BODY,ba(e,t)}function QI(e,t){switch(t.tagID){case o.HTML:{nt(e,t);break}case o.FRAMESET:{e._insertElement(t,te.HTML);break}case o.FRAME:{e._appendElement(t,te.HTML),t.ackSelfClosing=!0;break}case o.NOFRAMES:{Pt(e,t);break}}}function qI(e,t){t.tagID===o.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==o.FRAMESET&&(e.insertionMode=A.AFTER_FRAMESET))}function WI(e,t){switch(t.tagID){case o.HTML:{nt(e,t);break}case o.NOFRAMES:{Pt(e,t);break}}}function $I(e,t){t.tagID===o.HTML&&(e.insertionMode=A.AFTER_AFTER_FRAMESET)}function KI(e,t){t.tagID===o.HTML?nt(e,t):Qi(e,t)}function Qi(e,t){e.insertionMode=A.IN_BODY,ba(e,t)}function ZI(e,t){switch(t.tagID){case o.HTML:{nt(e,t);break}case o.NOFRAMES:{Pt(e,t);break}}}function XI(e,t){t.chars=ze,e._insertCharacters(t)}function JI(e,t){e._insertCharacters(t),e.framesetOk=!1}function fh(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==te.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function eb(e,t){if(mA(t))fh(e),e._startTagOutsideForeignContent(t);else{const r=e._getAdjustedCurrentElement(),n=e.treeAdapter.getNamespaceURI(r);n===te.MATHML?$f(t):n===te.SVG&&(EA(t),Kf(t)),Mc(t),t.selfClosing?e._appendElement(t,n):e._insertElement(t,n),t.ackSelfClosing=!0}}function tb(e,t){if(t.tagID===o.P||t.tagID===o.BR){fh(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)===te.HTML){e._endTagOutsideForeignContent(t);break}const i=e.treeAdapter.getTagName(n);if(i.toLowerCase()===t.tagName){t.tagName=i,e.openElements.shortenToLength(r);break}}}v.AREA,v.BASE,v.BASEFONT,v.BGSOUND,v.BR,v.COL,v.EMBED,v.FRAME,v.HR,v.IMG,v.INPUT,v.KEYGEN,v.LINK,v.META,v.PARAM,v.SOURCE,v.TRACK,v.WBR;function rb(e,t,r){typeof e=="string"&&(r=t,t=e,e=null);const n=yA.getFragmentParser(e,r);return n.tokenizer.write(t,!0),n.getFragment()}const ir=e=>{if(!Se(e))throw ye("帖子响应必须是对象");return e};function gt(e){if(typeof e!="string")throw ye("帖子响应字符串字段无效");return e}function Tr(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw ye("帖子响应数值字段无效");return e}function qi(e){if(typeof e!="boolean")throw ye("帖子响应状态无效");return e}function nb(e,t){if(!Array.isArray(e))throw ye("帖子响应列表无效");return e.map(t)}function ib(e){const t=ir(e),r=gt(t.revision);if(!/^(0|[1-9]\d*)$/.test(r))throw ye("绑定版本无效");return{postId:gt(t.postId),revision:r}}function sb(e){const t=ir(e);return{id:gt(t.id),name:gt(t.name),avatar:gt(t.avatar),isMe:qi(t.isMe)}}function ab(e){const t=ir(e);return{url:gt(t.url),width:Tr(t.width),height:Tr(t.height)}}function ob(e){const t=ir(e),r=ir(t.stats),n=ir(t.viewer);return{id:gt(ir(t.binding).postId),title:gt(t.title),text:gt(t.text),author:sb(t.author),content:nb(t.content,i=>{const s=ir(i);if(s.type==="text")return{type:"text",text:gt(s.text)};if(s.type==="image")return{type:"image",image:ab(s.image)};if(s.type==="link")return{type:"link",url:gt(s.url)};throw ye("帖子内容类型无效")}),createdAt:Tr(t.createdAt),updatedAt:Tr(t.updatedAt),url:gt(t.url),canComment:qi(t.canComment),stats:{likes:Tr(r.likes),comments:Tr(r.comments),favorites:Tr(r.favorites)},viewer:{liked:qi(n.liked),favorited:qi(n.favorited)}}}const cb=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 ub(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 a(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=cb.has(d);if(l&&t.length>0&&(r=!0),u=u||d==="pre"||d==="textarea","value"in c){const h=c.value;if(!u&&/^[ \t\r\n\f]*$/.test(h)){if(r||i())return;n=!0;return}s(),n&&!t[t.length-1].endsWith(" ")&&t.push(" "),n=!1,t.push(h)}"childNodes"in c&&c.childNodes.forEach(h=>a(h,u)),l&&t.length>0&&(r=!0)}return a(rb(gt(e))),t.join("")}function Vt(e){if(!Se(e))throw ye("社区评论响应无效");return e}function rr(e){const t=typeof e=="string"&&/^\d+$/.test(e)?Number(e):e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw ye("社区评论数值无效");return t}function jn(e){if(e==null||e===""||e===0||e==="0")return"";if(typeof e!="string"&&!Number.isSafeInteger(e))throw ye("社区评论 ID 无效");const t=String(e);if(!/^[1-9]\d{0,18}$/.test(t))throw ye("社区评论 ID 无效");return t}function Qa(e){if(typeof e!="string")throw ye("社区评论文本无效");return e}function Oo(e,t,r,n){const i=Vt(e),s=jn(i.commentid);if(!s)throw ye("社区评论缺少 ID");const a=i.user==null?{}:Vt(i.user),c=jn(i.userid??a.userid),u=i.is_support==null?void 0:rr(i.is_support);if(u!==void 0&&![0,1,2].includes(u))throw ye("社区评论点赞状态无效");const d=i.imgs==null?void 0:(()=>{if(!Array.isArray(i.imgs))throw ye("社区评论图片无效");return i.imgs.map(h=>{const f=Vt(h);return{url:Qa(f.url),width:rr(f.width??0),height:rr(f.height??0)}})})(),l=(d?.length??0)>0||rr(i.has_imgs??0)>0;return{id:s,rootCommentId:t||s,replyToCommentId:jn(i.replyid),author:{id:c,name:Qa(a.username??""),avatar:Qa(a.avatar??""),isMe:c===r},text:ub(i.text),hasImages:l,...d?.length||!l?{images:d??[]}:{},createdAt:rr(i.create_at),likes:rr(i.up??0),replies:rr(i.child_num??0),...u!==void 0?{liked:u===1}:{},canDelete:c===r||n===r}}function db(e,t,r,n,i,s){const a=Vt(t),c=a.comments??[];if(!Array.isArray(c))throw ye("社区评论列表无效");const u=c.map(h=>{if(r)return Oo(h,r,n,i);const f=Vt(h).comment;if(!Array.isArray(f)||!f.length)throw ye("社区评论楼层无效");return Oo(f[0],"",n,i)});if(r){if(typeof a.has_more!="boolean")throw ye("社区回复分页无效");const h=jn(a.lastval);if(a.has_more&&!h)throw ye("社区回复缺少游标");return{items:u,cursor:a.has_more?h:"",hasMore:a.has_more}}const d=a.total_page??Vt(e).total_page,l=d==null?u.length>0:s<rr(d);return{items:u,cursor:l?String(s+1):"",hasMore:l}}function lb(e,t,r,n,i,s){const a=Vt(t),c=a.current_comment??Vt(e).current_comment,u=[...c==null?[]:[c],...Array.isArray(a.comments)?a.comments:[]];for(const d of u){const l=Vt(d).comment;if(!Array.isArray(l))continue;const h=l.find(f=>jn(Vt(f).commentid)===r);if(h)return Oo(h,n,i,s)}throw{code:"COMMENT_UNAVAILABLE",message:"评论不存在或不可访问"}}const hh=3e4;function fb(e){let t=!1,r=!0,n=!1,i=!1,s;const a=()=>t&&r&&!n,c=()=>{clearTimeout(s),s=void 0},u=()=>{c(),a()&&(s=setTimeout(d,hh*(1+(e.random??Math.random)()*.1)))};async function d(){if(c(),!(!a()||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 hb(e){const t=new Set;let r=0,n=!1,i,s,a=!1,c=new AbortController,u,d=!1,l,h=0,f=0,E,g,b,N;const y=S=>{if(n||e.operationContext.signal.aborted)throw ie("RUNTIME_DESTROYED","小程序已关闭");if(r!==S)throw ie("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")};function w(){if(d)throw ie("BINDING_CHANGED","关联帖子已更换,请重新打开小程序")}function I(S){throw Se(S)&&S.code==="BINDING_CHANGED"&&(x(),w()),S}function x(){if(!d){d=!0,l=void 0,b?.abort(),c.abort(),U.setEnabled(!1);try{e.emit({changed:["binding"]})}catch{}}}function V(S){return w(),u&&(u.revision!==S.revision||u.postId!==S.postId)&&(x(),w()),u??=S,u}async function M(S,q){y(S),w();const W=await e.account.getCurrentUserId(q);if(y(S),w(),i!==void 0&&i!==W)throw H(),ie("AUTHORIZATION_CONTEXT_CHANGED","账号已变化,请重试");if(!W)throw ie("UNAUTHORIZED","请先登录小黑盒");if(a&&s!==W)throw ie("AUTHORIZATION_CONTEXT_CHANGED","账号已变化,请重试");i=W}async function R(S,q,W,Z=r){const se=ke(ke(e.operationContext,c.signal),W);await M(Z,se);const de=await q(se);await M(Z,se);const Ie=await Ti({network:e.network,operationContext:se,subject:"关联帖子",assertUsable:()=>{y(Z),w()},...e.requestGate?{gate:{capability:"post",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},S,de);return await M(Z,se),Ie}async function L(S,q,W){try{const Z=await R(D_,async de=>{if(!e.authorizationContext)throw ie("METHOD_FORBIDDEN","宿主不支持关联帖子授权上下文");const Ie=await e.authorizationContext.get(de);if(!Ie.token||Ie.expiresAt<=Date.now())throw ie("UNAUTHORIZED","小程序运行上下文已过期");return{runtime_auth_context_token:Ie.token,action:S,payload:JSON.stringify(q)}},W),se=rt(Z,S,"关联帖子");if(!Se(se)||!Se(se.data))throw ie("INVALID_RESPONSE","关联帖子响应缺少数据");return se.data}catch(Z){return I(Z)}}function Y(){if(g)return g;const S=r,q=f,W=L("get",{},e.operationContext.signal).then(Z=>{if(y(S),q!==f)return g=void 0,Y();V(ib(Z.binding));const se=ob(Z);if(Z.commentsRevision!==void 0&&(typeof Z.commentsRevision!="string"||!/^\d+$/.test(Z.commentsRevision)))throw ie("INVALID_RESPONSE","评论版本无效");const de=[];if(l){const{stats:Ie,viewer:Re,...Ue}=l,{stats:_,viewer:B,...K}=se;JSON.stringify(Ue)!==JSON.stringify(K)&&de.push("content"),JSON.stringify([Ie,Re])!==JSON.stringify([_,B])&&de.push("stats")}return Z.commentsRevision!==void 0&&E!==void 0&&E!==Z.commentsRevision&&de.push("comments"),l=se,h=Date.now(),Z.commentsRevision!==void 0&&(E=Z.commentsRevision),de.length&&U.invalidate({changed:de}),se}).catch(Z=>{if(r===S&&f===q&&Se(Z)&&["POST_UNAVAILABLE","POST_NOT_BOUND","POST_TYPE_UNSUPPORTED"].includes(String(Z.code))){const se=l!==void 0;l=void 0,se&&U.invalidate({changed:["content","stats"]})}throw Z}).finally(()=>{g===W&&(g=void 0)});return g=W,W}function j(S){y(S),w(),f++,h=0}async function ee(S,q){const W=r;try{await q()}catch(Z){if(n||e.operationContext.signal.aborted||r!==W||Z instanceof Error&&Z.name==="AbortError")return;try{e.onBackgroundError?.(S,Z)}catch{}}}function k(S,q){return j(S),U.invalidate({changed:["comments"]}),L("comments.changed",{bindingRevision:u.revision},q)}async function z(S){const q=r;await M(q,ke(e.operationContext,S));const W=l&&Date.now()-h<hh?l:await be(Y,S).catch(Z=>{throw w(),Z});return y(q),w(),W}async function F(S,q,W,Z,se){const Ie=await R(S==="post.setLiked"?w_:N_,()=>({targetId:W,enabled:q.liked===!0||q.favorited===!0}),Z,se);(!Se(Ie)||Ie.status!=="ok")&&rt(Ie,S,"帖子互动")}const U=fb({emit:e.emit,refresh:Y});function H(){r++,l&&U.invalidate({changed:["content","stats"]}),l=void 0,h=0,E=void 0,g=void 0,b?.abort(),c.abort(),c=new AbortController,i=void 0,U.reset()}const P=_i(e.account,S=>{s=S,a=!0,i!==void 0&&S!==i&&H()}),C=e.authorization.onEvent(H),Q={};for(const S of[...ra,...Wn])Q[S]=async(q,W)=>{if(y(r),S==="post.watch"){if(q!==void 0)throw ie("INVALID_ARGUMENT","变化订阅无需参数");if(t.size>=32)throw ie("RATE_LIMITED_BY_RUNTIME","帖子订阅过多");const _=r;if(w(),await z(W.signal),y(_),w(),W.signal.aborted)return;if(t.size>=32)throw ie("RATE_LIMITED_BY_RUNTIME","帖子订阅过多");return new Promise((B,K)=>{const J=()=>{W.signal.removeEventListener("abort",J),t.delete(J),U.setEnabled(t.size>0&&!d),B()};t.add(J),W.signal.addEventListener("abort",J,{once:!0}),U.setEnabled(!0);try{W.postProgress({watching:!0})}catch(Ee){W.signal.removeEventListener("abort",J),t.delete(J),U.setEnabled(t.size>0&&!d),K(Ee)}})}if(Wn.includes(S)&&!W.trustedUserGesture)throw ie("USER_GESTURE_REQUIRED","请通过用户操作发起帖子互动");const se=mb(S,q);w();const de=r;if(S==="post.get")return JSON.parse(JSON.stringify(await z(W.signal)));let Ie;S==="post.comments.openEditor"&&(b?.abort(),b=Ie=new AbortController,N=W.requestId,W={...W,...ke(W,Ie.signal)});const Re=await z(W.signal),Ue=i;if(y(de),w(),S==="post.comments.delete"||S==="post.comments.setLiked"){const _=await R(S==="post.comments.delete"?y_:b_,()=>({body:{comment_id:se.commentId,...S==="post.comments.setLiked"?{support_type:se.liked?1:2}:{}}}),W.signal,de);(!Se(_)||_.status!=="ok")&&rt(_,S,"帖子评论"),ee("post.comments.changed",()=>k(de,c.signal));return}if(S.startsWith("post.comments.")){const{cursor:_,limit:B}=se,K=W.signal;if(S==="post.comments.list"){const J=String(se.rootCommentId??""),Ee=J?1:Number(_||1),me=J?{root_comment_id:J,lastval:_||"",limit:B??20}:{link_id:Re.id,page:Ee,limit:B??20,owner_only:0,hide_cy:1,sort_filter:0,index:2},De=await R(J?I_:Yu,()=>me,K,de);return db(De,rt(De,S,"帖子评论"),J,Ue,Re.author.id,Ee)}if(S==="post.comments.openEditor"){const J=e.presentation?.openPostCommentEditor;if(!J||!Ie)throw ie("METHOD_FORBIDDEN","当前宿主不支持评论编辑器");let Ee;if(se.replyToCommentId){const we=String(se.replyToCommentId),Oe=String(se.rootCommentId??we),Pe=await R(Yu,()=>({link_id:Re.id,root_comment_id:Oe,comment_id:we,page:1,limit:20,owner_only:0,hide_cy:1,sort_filter:0,index:2}),K,de);Ee=lb(Pe,rt(Pe,S,"帖子评论"),we,Oe,Ue,Re.author.id)}const me=ke(ke(e.operationContext,c.signal),Ie.signal),De=ke(me,K);await M(de,De),await be(()=>J({postId:Re.id,...Ee?{reply:Ee}:{},lifetimeSignal:me.signal,onSubmitted(){b!==Ie||me.signal.aborted||r!==de||ee("post.comments.changed",async()=>{await M(de,me),!me.signal.aborted&&await k(de,me.signal)})}},De),De.signal),await M(de,De);return}}await F(S,se,Re.id,W.signal,de),j(de),ee("post.get",Y)};return{handlers:Q,setVisible:U.setVisible,dismissEditor(S){S===N&&(N=void 0,b?.abort())},dispose(){if(!n){n=!0;for(const S of[...t])S();r++,c.abort(),U.dispose(),P(),C()}}}}const Ri={"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 mb(e,t){if(Ri[e].length===0&&t===void 0)return{};if(!Se(t)||Object.keys(t).some(r=>!Ri[e].includes(r)))throw ie("INVALID_ARGUMENT","帖子操作参数无效");for(const r of["liked","favorited"])if(Ri[e].includes(r)&&typeof t[r]!="boolean")throw ie("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 ie("INVALID_ARGUMENT","评论 ID 无效");if(Ri[e].includes("commentId")&&t.commentId===void 0)throw ie("INVALID_ARGUMENT","缺少评论 ID");if(e==="post.comments.openEditor"&&t.rootCommentId!==void 0&&t.replyToCommentId===void 0)throw ie("INVALID_ARGUMENT","根评论 ID 需要同时指定回复目标");if(t.limit!==void 0&&(!Number.isInteger(t.limit)||Number(t.limit)<1||Number(t.limit)>50))throw ie("INVALID_ARGUMENT","分页数量须为 1–50");if(t.cursor!==void 0&&(typeof t.cursor!="string"||!/^(|[1-9]\d{0,18})$/.test(t.cursor)))throw ie("INVALID_ARGUMENT","评论游标无效");if(!t.rootCommentId&&t.cursor&&!Number.isSafeInteger(Number(t.cursor)))throw ie("INVALID_ARGUMENT","评论页码无效");return{...t}}const Eb=new Set(["stdio","attachments","notifications"]),mh=new Set(["windows-x64","macos-arm64"]),gb=new Set(["unsigned","valid","invalid","unknown"]),pb=/^[a-f0-9]{64}$/,Tb=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),_b=new Set(Bl),Ab=new Set([...Bl,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Eh=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 Ib(e){const t=async(n,i,s,a)=>{const c=bb(n);try{Ht(i.signal);const u=await s(c,{...e.operationContext,signal:i.signal});return Ht(i.signal),u}catch(u){throw Co(u,a)}},r=async(n,i,s)=>{if(!s.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw p("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const a={...e.operationContext,signal:s.signal},c=await e.companion.getInfo(i,a).then(d=>yb(d,i)).catch(d=>{throw Co(d)});Ht(s.signal);const u=await e.companionPresentation.confirmCompanionOperation({action:n,companion:c,miniProgram:e.miniProgramPresentation,signal:s.signal});if(Ht(s.signal),u.status!=="granted")throw p("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[na]:(n,i)=>t(n,i,async(s,a)=>Mo(await e.companion.getInfo(s,a),s)),[ia]:(n,i)=>t(n,i,async(s,a)=>nd(await e.companion.getPreparationStatus(s,a))),[sa]:(n,i)=>t(n,i,async(s,a)=>{const c=nd(await e.companion.getPreparationStatus(s,a));return Ht(i.signal),c.state!=="ready"&&c.state!=="preparing"&&await r("prepare",s,i),Ht(i.signal),Mo(await e.companion.prepare(s,{...a,onProgress:u=>i.postProgress(ph(u))}),s)},"COMPANION_PREPARATION_CANCELLED"),[aa]:(n,i)=>t(n,i,(s,a)=>e.companion.cancelPreparation(s,a)),[oa]:(n,i)=>t(n,i,async(s,a)=>id(await e.companion.getActiveSession(s,a),s)),[ca]:(n,i)=>t(n,i,async(s,a)=>{const c=id(await e.companion.getActiveSession(s,a),s);return Ht(i.signal),c||(await r("launch",s,i),Ht(i.signal),Th(await e.companion.launch(s,a),s))}),[ua]:(n,i)=>Vr(n,i,e,"write"),[da]:(n,i)=>Vr(n,i,e,"closeStdin"),[la]:(n,i)=>Vr(n,i,e,"terminate"),[fa]:(n,i)=>Vr(n,i,e,"ackOutput"),[ha]:async(n,i)=>{const s=await Vr(n,i,e,"openAttachment");return e.fileRegistry.registerFile(s,"companion-attachment","read")},[ma]:(n,i)=>Vr(n,i,e,"showNotification")}}function bb(e){if(!he(e)||typeof e.alias!="string"||!U0.test(e.alias))throw p("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Ht(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function Vr(e,t,r,n){if(!he(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw p("INVALID_PARAMS","Companion Session controller 不合法");try{Ht(t.signal);const i=await r.companion[n](Nb(e,n),{...r.operationContext,signal:t.signal});return Ht(t.signal),i}catch(i){throw Co(i)}}function Rt(){throw p("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function gh(e){return!Array.isArray(e)||e.some(t=>!Eb.has(t))?Rt():Object.freeze([...new Set(e)])}function Mo(e,t){return!he(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!mh.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!gb.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?Rt():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:gh(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function yb(e,t){const r=Mo(e,t);return!he(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!pb.test(e.sha256)?Rt():Object.freeze({...r,sha256:e.sha256})}function ph(e){return he(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}):Rt():Rt()}function nd(e){return he(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:ph(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&he(e.error)&&typeof e.error.code=="string"&&_b.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:Eh[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):Rt():Rt()}function Th(e,t){return!he(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!mh.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?Rt():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:gh(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function id(e,t){return e===void 0?void 0:Th(e,t)}function Nb(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Rl(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 wb(e){return!he(e)||!Tb.has(String(e.reason))?Rt():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):Rt():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?Rt():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Db(e){if(!he(e)||!he(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||!Rl(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:wb(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 Co(e,t){return he(e)&&typeof e.code=="string"&&Ab.has(e.code)?p(e.code,Eh[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&he(e)&&e.name==="AbortError"?p(t,"Companion 准备已取消"):p("COMPANION_HOST_FAILED","Companion Host 操作失败")}const sd=5e3,ad=1e4;function at(e){throw{code:"INVALID_PARAMS",message:e}}function Pc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _h(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&at(`${r} 不支持字段: ${n.join(", ")}`)}function Sb(e){if(e===void 0)return{intensity:"light",delay:0};if(!Pc(e))return at("device.vibrate 参数必须是对象");_h(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return at("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>sd?at(`device.vibrate delay 必须是 0-${sd} 的整数毫秒`):{intensity:r,delay:n}}function Ob(e){return Pc(e)?(_h(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?at("device.setClipboard text 必须是非空字符串"):e.text.length>ad?at(`device.setClipboard text 不能超过 ${ad} 字符`):{text:e.text}):at("device.setClipboard 参数必须是对象")}function Mb(e){return typeof e=="string"?e.trim()?e:at("device.executeProtocol 协议字符串不能为空"):Pc(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?at("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(Ro(e,new Set),e):at("device.executeProtocol 参数必须是协议字符串或协议对象")}function Ro(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||at("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":at("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":at(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&at("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)Ro(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&at("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))Ro(i,t);t.delete(r)}function Cb(e){return{[Ls]:async(t,r)=>{const n=ke(e.operationContext,r.signal,r.requestId);Ce(n.signal),await be(()=>e.presentation.vibrate(Sb(t),n),n.signal)},[Ps]:async(t,r)=>{const n=ke(e.operationContext,r.signal,r.requestId);Ce(n.signal),await be(()=>e.presentation.setClipboard(Ob(t),n),n.signal)},[vs]:async(t,r)=>{const n=ke(e.operationContext,r.signal,r.requestId);Ce(n.signal);const i=Mb(t);await be(()=>e.protocol.invoke(i,n),n.signal)}}}const od=1e3,Rb=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function Lb(e){const t=r=>ke(e.operationContext,r.signal);return{files:{[As]:async(r,n)=>{qa(n);const i=Wa(e.picker),s=Pb(r),a=await Et(()=>i.pickFiles(s,t(n)));return e.registry.registerFiles(a,"external",s.mode,s.multiple?void 0:1)},[Is]:async(r,n)=>{qa(n);const i=Wa(e.picker),s=vb(r),a=await Et(()=>i.pickDirectory(s,t(n)));return e.registry.registerDirectory(a,"external",s.mode)},[bs]:async(r,n)=>{qa(n);const i=Wa(e.picker),s=kb(r).suggestedName,a=t(n);if(!i.saveFile)throw Nt("files.saveFile");const c=await Et(()=>i.saveFile({suggestedName:s},a));return e.registry.registerFile(c,"external","readwrite")}},file:{[Xn]:async(r,n)=>{const i=_t(r,["recursive","exclusive"]),s=e.registry.resolveFile(i.target);Gr(s.mode),await Et(()=>s.create(cd(i),t(n)))},[Jn]:async(r,n)=>{const i=_t(r),s=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(s),Gr(s.handle.mode),!s.handle.remove)throw Nt(Jn);await Et(()=>s.handle.remove(t(n)))},[ys]:async(r,n)=>{const i=_t(r);return ud(async()=>{const s=await e.registry.resolveFile(i.target).stat(t(n));if(!he(s)||s.kind!=="file")throw ld()})},[ei]:async(r,n)=>{const i=_t(r),s=dd(await Et(()=>e.registry.resolveFile(i.target).read(t(n))));try{const a=new TextDecoder("utf-8",{fatal:!0}).decode(s);return a.charCodeAt(0)===65279?a.slice(1):a}catch{throw p("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Ns]:async(r,n)=>{const i=_t(r,["content"]);typeof i.content!="string"&&wt("content 必须是字符串");const s=e.registry.resolveFile(i.target);Gr(s.mode),await Et(()=>s.write(new TextEncoder().encode(i.content),t(n)))},[ti]:async(r,n)=>{const i=_t(r),s=await Et(()=>e.registry.resolveFile(i.target).read(t(n)));return dd(s)},[ws]:async(r,n)=>{const i=_t(r,["content"]),s=e.registry.resolveFile(i.target);Gr(s.mode),await Et(()=>s.write(Ub(i.content),t(n)))},[ri]:async(r,n)=>{const i=_t(r),s=await Et(()=>e.registry.resolveFile(i.target).stat(t(n)));return Bb(s)}},directory:{[Ds]:async(r,n)=>{const i=_t(r,["recursive","exclusive"]),s=e.registry.resolveDirectory(i.target);Gr(s.mode),await Et(()=>s.create(cd(i),t(n)))},[ni]:async(r,n)=>{const i=_t(r,["recursive"]);if(he(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 Nt(ni);await Et(()=>s.handle.remove({recursive:i.recursive===void 0?!1:$s(i.recursive,"recursive")},t(n)))},[Ss]:async(r,n)=>{const i=_t(r);return ud(async()=>{const s=await e.registry.resolveDirectory(i.target).stat(t(n));if(!he(s)||s.kind!=="directory")throw ld()})},[Os]:async(r,n)=>{const i=_t(r,["limit"]),s=xb(i.limit),a=e.registry.resolveDirectoryEntry(i.target),c=await Et(()=>a.handle.list({limit:s},t(n)));return e.registry.describeListedEntries(a,c,s)}}}}function Pb(e){if(e===void 0)return{mode:"read",multiple:!1};he(e)||wt("pickFiles 参数必须是对象"),Da(e,["mode","accept","multiple"]);const t=Ah(e.mode,"read"),r=e.multiple===void 0?!1:$s(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)))&&wt("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function vb(e){return e===void 0?{mode:"read"}:(he(e)||wt("pickDirectory 参数必须是对象"),Da(e,["mode"]),{mode:Ah(e.mode,"read")})}function kb(e){return he(e)||wt("saveFile 参数必须是对象"),Da(e,["suggestedName"]),{suggestedName:mi(e.suggestedName,"suggestedName")}}function _t(e,t=[]){return(!he(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&wt("文件操作参数必须包含 target"),Da(e,["target",...t]),e}function cd(e){return{recursive:e.recursive===void 0?!1:$s(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:$s(e.exclusive,"exclusive")}}function Ah(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&wt("mode 必须是 read 或 readwrite"),e)}function $s(e,t){return typeof e!="boolean"&&wt(`${t} 必须是布尔值`),e}function xb(e){if(e===void 0)return od;if((!Number.isSafeInteger(e)||e<=0)&&wt("limit 必须是正整数"),e>od)throw p("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Da(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&wt(`不支持字段: ${r.join(", ")}`)}function Gr(e){if(e!=="readwrite")throw p("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function qa(e){if(!e.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Wa(e){if(!e)throw Nt("files.external");return e}async function ud(e){try{return await e(),!0}catch(t){if(Rb.has(bc(t)??""))return!1;throw nn(t)}}async function Et(e){try{return await e()}catch(t){throw nn(t)}}function Ub(e){return e instanceof Uint8Array||wt("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&wt("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function dd(e){if(!(e instanceof Uint8Array))throw p("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function ld(){return p("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Bb(e){if(!he(e)||e.kind!=="file"||!Hb(e.size))throw p("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Fb(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 Hb(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Fb(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function wt(e){throw p("INVALID_PARAMS",e)}const fd=16*1024,hd=200;function zb(e){const t=af(e.runtimePermissions);function r(n,i){e.capabilities&&Xl(i,e.capabilities);const s=t({kind:"all",permissions:["filesystem"]},i);if(!s.allowed)throw p(s.code,s.message);const a=ke(e.operationContext,n);return Lo(a),a}return{async list(n,i={}){const s=r(i.signal,"directory.list"),a=e.registry.resolveDirectoryEntry({kind:"directory",root:{kind:"sandbox"},relativePath:n}),c=await md(()=>a.handle.list({limit:hd},s),s);return e.registry.describeListedEntries(a,c,hd).map(({name:u,kind:d})=>({name:u,kind:d}))},async read(n,i={}){const s=i.maxBytes??fd;if(!Number.isSafeInteger(s)||s<1||s>fd)throw p("INVALID_PARAMS","诊断读取最多允许 16384 bytes");const a=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},a),a);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 Lo(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 Lo(t),n}catch(n){throw t.signal.aborted&&Lo(t),nn(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const jb=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),$a={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function Vb(e){if(e instanceof qe)return p("REQUEST_UNSUPPORTED",$a.REQUEST_UNSUPPORTED);const t=Ih(e);return t!==void 0&&jb.has(t)?p(t,$a[t]??"媒体操作失败"):p("MEDIA_PREPARE_FAILED",$a.MEDIA_PREPARE_FAILED)}function Ih(e){try{if(!he(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Gb=["source","mediaType","maxCount"],Wi=Object.freeze({source:"album",mediaType:"all",maxCount:1});function Yb(e){if(e===void 0)return Wi;if(!g0(e))throw p("INVALID_PARAMS",qb(e));return Qb(e)}function Qb(e){return Object.freeze({source:e.source??Wi.source,mediaType:e.mediaType??Wi.mediaType,maxCount:e.maxCount??Wi.maxCount})}function qb(e){if(!he(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!Gb.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 Wb=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),$b={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class Kb{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=Zb(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const s=n.map((a,c)=>Jb(a,i[c]));if(!p0(s))throw jt("Host 返回的媒体结果未通过协议校验");for(const a of n)this.committed.add(a);return s}catch(s){throw this.registry.revokeFiles(i.map(ey).filter(a=>a!==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=Ih(n);throw i!==void 0&&Wb.has(i)?n:jt("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function Ed(e,t){if(e.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw p("REQUEST_CANCELLED","media.pick 已取消")}function Zb(e,t){if(!Array.isArray(e))throw jt("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw jt("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw jt("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw jt("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw jt("Host 返回了稀疏媒体结果");Xb(e[n],n)}return e}function Xb(e,t){if(!he(e))throw jt(`第 ${t+1} 项不是对象`);if(!Cl({...e,file:$b}))throw jt(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!he(e.file))throw jt(`第 ${t+1} 项缺少文件句柄`)}function Jb(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 ey(e){return"handleId"in e.ref?e.ref.handleId:void 0}function jt(e){return p("MEDIA_PREPARE_FAILED",e)}function ty(e){const t=e.media?new Kb(e.registry,e.media,e.operationContext):void 0;return{handlers:{[ii]:async(n,i)=>{const s=Yb(n);ny(i);const a=e.media,c=t;if(!a||typeof a.pick!="function"||!c)throw Nt(ii);const u=ke(e.operationContext,i.signal);Ed(e.operationContext,i.signal);const d=await ry(a,s,u,e.operationContext,i.signal);Ed(e.operationContext,i.signal);try{return c.commit(d,s)}catch(l){throw c.releaseBatch(d,u),l}}},dispose(){t?.dispose()}}}async function ry(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 已取消"):Vb(s)}}function ny(e){if(!e.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Li=4294967296;function iy(e){const t=new sy;return t.write(e),t.finish()}class sy{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<Li?(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=ay(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<Li)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/Li),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Li)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function ay(e){const t=new Uint8Array(oy(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 oy(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 bh(e){Po(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 Po(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)Po(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,a]of i){if(s==="__proto__")throw new Error("extra object key is not supported");Po(a,t+1,r)}r.delete(e)}const cy=["pc","console","mobile"],uy=["game","wiki"];function Ks(e){throw{code:"INVALID_PARAMS",message:e}}function dy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lr(e,t){return typeof e!="string"||!e.trim()?Ks(t):e.trim()}function gd(e,t,r){return typeof e!="string"||!t.includes(e)?Ks(r):e}function ly(e){const t={target:"game_detail",appId:lr(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:gd(e.gameType,cy,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=gd(e.page,uy,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=lr(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=lr(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function fy(e){return{target:"user_detail",userId:lr(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function hy(e){const t={target:"post_detail",linkId:lr(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=lr(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=lr(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function my(e){const t={target:"mini_program",miniProgramId:lr(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Ey(e){return dy(e)?e.target==="game_detail"?ly(e):e.target==="user_detail"?fy(e):e.target==="post_detail"?hy(e):e.target==="mini_program"?my(e):Ks("navigation.openAppPage target 不支持"):Ks("navigation.openAppPage options 必须是对象")}function gy(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 py(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Ty(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 _y(e){const t=e;return t.target==="game_detail"?gy(t):t.target==="user_detail"?py(t):Ty(t)}const Ay="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",Iy="data-hb-sdk-fullscreen-exit",by=3e3,yy=2e3,pd="var(--white-70a,rgba(255,255,255,.7))",Td="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function Ny(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(Iy,""),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 ${pd}`,`box-shadow:${Td}`,"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=Ay,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,a=!1,c=!1,u,d;function l(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function h(){s||(t.style.width=l())}function f(){d?.cancel(),d=void 0}function E(N=yy){clearTimeout(u),u=setTimeout(()=>{f(),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(){f(),s=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=pd,t.style.boxShadow=Td,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),E()}async function b(){if(!(a||c)){if(!s){g();return}c=!0,clearTimeout(u),f();try{await e()}catch{}finally{c=!1,a||g()}}}return t.addEventListener("click",b),window.addEventListener("resize",h),document.body.append(t),!r&&t.animate&&(d=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),E(by),{dispose(){a=!0,clearTimeout(u),f(),t.removeEventListener("click",b),window.removeEventListener("resize",h),t.remove()}}}const yh=1e4;function Nh(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()},yh);return{signal:r.signal,async run(a){try{return await be(a,r.signal)}catch(c){throw n??c}},dispose(){clearTimeout(s),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function _d(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 Ka(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function wn(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function wy(e){let t=0,r=0,n,i,s={mode:"portrait",hideCapsule:!1},a={mode:"portrait",hideCapsule:!1},c;function u(){c?.dispose(),c=void 0}function d(g){if(!g.hideCapsule){u();return}c??=Ny(()=>E.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",h),"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&&!Ka(a,g.options)){a={...g.options};try{e.onDisplayChange?.({orientation:a.mode,fullscreen:a.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 h(){n&&l(n,{error:wn()})}function f(g,b){return new Promise((N,y)=>{const w=()=>{g.subscribers.delete(I),I.dispose(),y(wn()),g.subscribers.size===0&&l(g,{error:wn()})},I={resolve:N,reject:y,dispose:()=>b?.removeEventListener("abort",w)};g.subscribers.add(I),b?.addEventListener("abort",w,{once:!0}),b?.aborted&&w()})}const E={async runDisplayRequest(g,b,N){const y=++t,w=Nh(b,e.operationContext.signal);try{return await w.run(async()=>{if(await N(w.signal),w.signal.aborted)throw wn();if(_d(g),y<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=y,E.apply(g,w.signal)})}finally{w.dispose()}},async apply(g,b,N="api"){if(Ce(e.operationContext.signal),b?.aborted)throw wn();const y=_d(g),w=n?.options??s,I={mode:y.orientation??w.mode,hideCapsule:y.fullscreen??w.hideCapsule};I.mode==="landscape"&&(I.hideCapsule=!0);const x=e.presentation.applyOrientation;if(!x)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&Ka(n.options,I))return f(n,b);if(n&&l(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&Ka(i.options,I))return i.result;i=void 0;const V={options:I,source:N,controller:new AbortController,subscribers:new Set};n=V;const M=f(V,b);return e.operationContext.signal.addEventListener("abort",h,{once:!0}),b||(V.timer=setTimeout(()=>{l(V,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},yh)),be(()=>x.call(e.presentation,I,{...e.operationContext,signal:V.controller.signal}),V.controller.signal).then(R=>l(V,{result:R??{supported:!0}}),R=>l(V,{error:R})),M},dispose(){e.operationContext.signal.removeEventListener("abort",u),u()}};return E}function wh(e){throw{code:"INVALID_PARAMS",message:e}}function Ad(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&wh(`${t} 不支持参数`)}function Dy(e){return{[ks]:async(t,r)=>{const n=ke(e.operationContext,r.signal,r.requestId);Ce(n.signal),Ad(t,"navigation.close"),await be(()=>e.presentation.close(n),n.signal)},[xs]:async(t,r)=>{const n=ke(e.operationContext,r.signal,r.requestId);Ce(n.signal),Ad(t,"navigation.reload"),await be(()=>e.presentation.reload(n),n.signal)},[Us]:async(t,r)=>{const n=ke(e.operationContext,r.signal,r.requestId);Ce(n.signal);const i=Ey(t);if(i.target==="mini_program"){let s;if(i.extra!==void 0)try{s=bh(i.extra)}catch{wh("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const a=e.resetDisplay;if(a){const c=Nh(n.signal);try{await c.run(()=>a(c.signal))}finally{c.dispose()}}Ce(n.signal),await be(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...s===void 0?{}:{extra:s}},n),n.signal);return}await be(()=>e.presentation.openAppPage(_y(i),n),n.signal)}}}const Id={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function Sy(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw Nt("network.upload");const s=ke(r.operationContext,t.signal),a=()=>{if(s.signal.aborted)throw p("UPLOAD_CANCELLED","上传已取消")};a();let c,u;try{c=i.resolveFileEntry(e.from).hostHandle,u=await c.stat(s)}catch(f){throw a(),nn(f)}if(a(),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 h=f=>{l||s.signal.aborted||!Number.isSafeInteger(f)||f<d||f>u.size||(d=f,t.postProgress({loaded:d,total:u.size,lengthComputable:!0}))};try{const{from:f,...E}=e,g=await n.upload(c,{...E,expectedBytes:u.size,...e.format==="multipart"?{fileName:e.fileName??c.name}:{}},{...s,onProgress:h});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(f){l=!0;const E=bc(f);throw E&&Id[E]?p(E,Id[E]):s.signal.aborted?p("UPLOAD_CANCELLED","上传已取消"):E?.startsWith("FILE_")||E?.startsWith("DIRECTORY_")?nn(f):p("UPLOAD_NETWORK_FAILED","上传网络失败")}}const vc="withCredentials",Oy=new Set(["url","method","params","data","headers","timeout",vc]),My=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",vc]),Cy=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),bd=3e4,vo=2*1024*1024,Ry=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Dh=/[\u0000-\u0008\u000A-\u001F\u007F]/,Ly=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Py="network.request 不支持 multipart/form-data,请使用专用上传能力";function vy(e){const t=ky(e.runtimePermissions);t.allowDevelopmentHttp=e.allowDevelopmentHttp===!0,t.firstParty=e.firstParty===!0,t.networkPolicy=t.firstParty?void 0:tf(e.networkPolicy);const r=$y(e.allowedHttpOrigins);return{[_s]:async(n,i)=>{const s=Uy(n,{permission:t,allowedHttpOrigins:r}),a=await Sy(s,i,e),{uploadedBytes:c,...u}=a;return Nd(u)},[Ts]:async(n,i)=>{const s=By(n,{permission:t,allowedHttpOrigins:r});return hf(s,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[ps]:async(n,i)=>{const s=ke(e.operationContext,i?.signal);Ce(s.signal);const a=xy(n,{permission:t,allowedHttpOrigins:r});let c;try{c=await be(()=>e.network.request(a,s),s.signal)}catch(u){throw Zy(u)?u:Xy(u,"REQUEST_UNSUPPORTED")?Ne("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):Ne("REQUEST_FAILED","网络请求失败")}return Nd(c)}}}function ky(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 xy(e,t){const r=on(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(u=>!Oy.has(u));if(n.length>0)throw Ne("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Sh(r,"network.request");const i=kc(r,t,"network.request"),s=Fy(r.method),a=r.data;a!==void 0&&Vy(a),Yy(i.headers,a);const c=Qy(i.headers,a,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},...a===void 0?{}:{data:a},...i.headers===void 0?{}:{headers:i.headers},...c===void 0?{}:{bodyEncoding:c},...i.timeout===void 0?{}:{timeout:i.timeout}}}function Uy(e,t){const r=on(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 Ne("INVALID_PARAMS","network.upload 包含不支持的字段");const i=kc(r,t,"network.upload");if(!t.permission.firstParty&&i.official)throw Ne("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw Ne("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!Dr(r.from))throw Ne("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Ne("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw Ne("INVALID_PARAMS","format 必须是 raw 或 multipart");const s=r.method??(r.format==="raw"?"PUT":"POST");if(s!=="POST"&&(r.format!=="raw"||s!=="PUT"))throw Ne("INVALID_PARAMS","上传 HTTP 方法不支持");const a={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 Ne("INVALID_PARAMS","raw 不接受 multipart 字段");return a}if(Object.keys(i.headers??{}).some(l=>l.toLowerCase()==="content-type"))throw Ne("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const c=yd(r.fieldName),u=r.fields===void 0?void 0:on(r.fields,"fields 必须是字符串字典");for(const[l,h]of Object.entries(u??{}))if(yd(l),typeof h!="string"||l===c)throw Ne("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw Ne("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||Dh.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw Ne("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>vo)throw Ne("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...a,fieldName:c,...u===void 0?{}:{fields:{...u}},...r.fileName===void 0?{}:{fileName:Nc(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function yd(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw Ne("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function By(e,t){const r=on(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(u=>!My.has(u));if(n.length>0)throw Ne("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Sh(r,"network.download");const i=kc(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw Ne("INVALID_PARAMS","network.download timeout 必须是有限正数");Sp(i.headers);const s=Dr(r.to),a=Ol(r.to);if(!s&&!a)throw Ne("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(s&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw Ne("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let c;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw Ne("INVALID_PARAMS","suggestedName 必须是字符串");c=Nc(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw Ne("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Ne("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 kc(e,t,r){const n=Hy(e.url,t.allowedHttpOrigins,r,t.permission.allowDevelopmentHttp===!0),i=_g(n);if(!t.permission.firstParty){const s=t.permission.networkPolicy,a=s?.enforcement==="approved_domains"&&n.protocol==="http:"&&(t.permission.allowDevelopmentHttp===!0||t.allowedHttpOrigins.has(n.origin));if(s&&!a&&(n.protocol!=="https:"||n.port!==""||!s.entries.some(c=>c.domain===n.hostname.toLowerCase())))throw Ne("PERMISSION_DENIED",`${r} 目标不在平台批准的域名清单中`);if(i&&!t.permission.useOfficialDomain)throw Ne("PERMISSION_DENIED","当前小程序暂不支持访问官方域名")}if(Tg(n.pathname,i))throw Ne("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...on(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:zy(e.headers,r),timeout:jy(e.timeout,r)}}function Hy(e,t,r="network.request",n=!1){if(typeof e!="string"||!e.trim())throw Ne("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let i;try{i=new URL(e)}catch{throw Ne("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw Ne("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(i.username||i.password)throw Ne("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(i.protocol==="http:"&&!n&&!t.has(i.origin))throw Ne("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return i}function Fy(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw Ne("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!Cy.has(t))throw Ne("INVALID_PARAMS","network.request method 不合法");return t}function zy(e,t="network.request"){const r=on(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,s]of Object.entries(r)){const a=i.trim();if(!a||a!==i||!Ry.test(a)||typeof s!="string"||Dh.test(s))throw Ne("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Ag(a))throw Ne("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[a]=s}return n}function Sh(e,t){const r=e[vc];if(r!==void 0&&typeof r!="boolean")throw Ne("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function jy(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw Ne("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>bd)throw Ne("INVALID_PARAMS",`${t} timeout 不能超过 ${bd}ms`);return e}}function Vy(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw Ne("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Gy(e)>vo)throw Ne("INVALID_PARAMS",`network.request data 不能超过 ${vo} 字节`)}function Gy(e){if(typeof e=="string")return Za(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return Za(e.toString());try{const t=JSON.stringify(e);return t?Za(t):0}catch{throw Ne("INVALID_PARAMS","network.request data 必须可序列化")}}function Yy(e,t){const r=Oh(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 Ne("INVALID_PARAMS",Py)}function Qy(e,t,r){if(t===void 0)return;const n=Oh(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)||Wy(t))?"form":qy(t)?"json":void 0}function Oh(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function qy(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function Wy(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function $y(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&&Ky(n.hostname)&&t.add(n.origin)}catch{}return t}function Ky(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 Nd(e){return Object.keys(e.headers).some(wd)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!wd(t)))}:e}function wd(e){const t=e.trim().toLowerCase();return Ly.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Zy(e){return e instanceof Error&&e.name==="AbortError"}function Xy(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function on(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Ne("INVALID_PARAMS",t);return e}function Za(e){return new TextEncoder().encode(e).length}function Ne(e,t){return{code:e,message:t}}function Jy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eN(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=eN(i);s?r.has(s)||(r.add(s),n.push(s)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function rN(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 Mh(e,t){if(e==null)return{};if(!Jy(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=tN(e.topicIds),n=rN(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 a=s.length||n.values.length?{...s.length?{topicIds:s}:{},...n.values.length?{topics:n.values}:{}}:void 0;return a||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:a}}function nN(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function iN(e){try{if(nN(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function Ze(e){throw{code:"INVALID_PARAMS",message:e}}function Ii(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ko(e,t){return typeof e!="string"||!e.trim()?Ze(t):e}function sN(e,t){const r=ko(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?Ze(t):r}catch{return Ze(t)}}function aN(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Ch(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return Ze(`${t} 缺少有效的小程序分享地址`);try{const s=new URL(e.environment.getCurrentHref()),a=new URL("/tools/common_share",s);a.searchParams.set("user_miniprogram_id",i);const c=n?.version?.trim();c&&a.searchParams.set("miniprogram_version",c);const u=s.searchParams.get("h_src");return u?.trim()&&a.searchParams.set("h_src",u),r!==void 0&&a.searchParams.set("extra",r),a.href}catch{return Ze(`${t} 缺少有效的小程序分享地址`)}}function oN(e,t){if(!Ii(e))return Ze("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return Ze("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!aN(r))return Ze("share.showShareMenu channel 不合法");const n=Rh(e.extra,"share.showShareMenu");return{title:ko(e.title,"share.showShareMenu title 必须是非空字符串"),description:ko(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Ch(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:sN(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Rh(e,t){if(e!==void 0)try{return bh(e)}catch{return Ze(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function Lh(e,t){return e.invalidMessage&&await be(()=>iN(t.environment),t.operationContext.signal)?Ze(e.invalidMessage):e.post}function Dd(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function cN(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Dd(t.windowWidth,0),height:Dd(t.windowHeight,0)}}function xo(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?Ze(t):r}function Sd(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?Ze(t):r}function uN(e){return Ii(e)?{left:xo(e.left,"share.screenshot rect.left 必须是非负数字"),top:xo(e.top,"share.screenshot rect.top 必须是非负数字"),width:Sd(e.width,"share.screenshot rect.width 必须是正数"),height:Sd(e.height,"share.screenshot rect.height 必须是正数")}:Ze("share.screenshot rect 必须是对象")}function Od(e,t){if(e!=null&&!Ii(e))return Ze("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?Ze("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?Ze("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?cN(t):uN(r.rect),...r.delay===void 0?{}:{delay:xo(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function dN(e,t){Ce(t.operationContext.signal);const r=oN(e,t);let n=Mh(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await Lh(n,t);return be(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function lN(e,t){if(Ce(t.operationContext.signal),e!==void 0&&!Ii(e))return Ze("share.copyLink 参数必须是对象");const r=Rh(e?.extra,"share.copyLink"),n=Ch(t,"share.copyLink",r);return await be(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Md(e,t,r,n=!1){Ce(t.operationContext.signal);const i=Mh(Ii(e)?e.post:void 0,{method:"share.screenshot"}),s=await Lh(i,t),a=t.identity.get()?.miniProgramId.trim()||void 0,c=fN(),{watermarkTheme:u,...d}=r;let l=!1,h,f,E;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);h=N.restore,d.rect=N.rect}f=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,u),E={status:"fulfilled",value:await be(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:s,...a?{sourceMiniProgramId:a}:{}},t.operationContext),t.operationContext.signal)}}catch(b){E={status:"rejected",error:b}}finally{try{f?.()}finally{h?.()}}const g=l?await hN(t.presentation,c,t.operationContext.signal):void 0;if(E.status==="rejected")throw E.error;if(g)throw g;return E.value}function fN(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function hN(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 mN(e){let t=Promise.resolve();const r=async(n,i)=>{const s=ke(e.operationContext,i.signal,i.requestId),a=Od(n,e.presentation);(a.rect.top+a.rect.height>1e4||a.rect.left+a.rect.width>2048||a.rect.width*a.rect.height>4e6)&&Ze("长图尺寸超出限制");const c=t.then(()=>Md(n,{...e,operationContext:s},a,!0));return t=c.then(()=>{},()=>{}),c};return{[ms]:r,[ls]:(n,i)=>lN(n,{...e,operationContext:ke(e.operationContext,i.signal,i.requestId)}),[fs]:(n,i)=>dN(n,{...e,operationContext:ke(e.operationContext,i.signal,i.requestId)}),[hs]:async(n,i)=>{const s=ke(e.operationContext,i.signal,i.requestId);Ce(s.signal);const a=Od(n,e.presentation),c=t.then(()=>Md(n,{...e,operationContext:s},a));return t=c.then(()=>{},()=>{}),be(()=>c,s.signal)}}}const Cd=new WeakMap,Pi=new Map;function Ph(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return FE(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Zl(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function vh(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 h=Cd.get(t);h||(h=new Map,Cd.set(t,h));const f=h.get(l)??Promise.resolve(),E=async()=>(Ce(u.signal,{preserveReason:!0}),d(l)),g=f.catch(()=>{}).then(()=>e.lock?e.lock(l,E):E());h.set(l,g);try{return await g}finally{h.get(l)===g&&h.delete(l)}},s=async(u,d,l=!1)=>{const h=Br(u,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(g=>g.key.startsWith(h)&&g.value!=="").map(g=>g.key.slice(h.length)))];const f=await e.storage.getRaw(wi(u),d);if((f===void 0||f==="")&&!l)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let E;try{E=f?JSON.parse(f):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(E)||E.length>uu||E.some(g=>typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)))throw new Error("本地数据索引异常");return[...new Set(E)]},a=async(u,d)=>{if(e.diagnostics){const f=Br(u,"");return(await e.diagnostics.listRaw(d)).filter(E=>E.key.startsWith(f)&&E.value!=="").map(E=>({...E,key:E.key.slice(f.length)}))}const l=[],h=await s(u,d);for(let f=0;f<h.length;f+=16){Ce(d.signal,{preserveReason:!0});const E=await Promise.all(h.slice(f,f+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 E)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 h=>{const f=await s(h,l,!0);if(!f.includes(u)&&f.length>=uu)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const E=[...new Set([...f,u])];await e.storage.setRaw(wi(h),JSON.stringify(E),l)}Ce(l.signal,{preserveReason:!0}),await e.storage.setRaw(Br(h,u),d,l),Ce(l.signal,{preserveReason:!0})})},list(u){return i(u,d=>a(d,u))},clear(u){return i(u,async d=>{const l=await s(d,u);e.diagnostics||await e.storage.setRaw(wi(d),JSON.stringify(l),u);for(let h=0;h<l.length;h+=16){Ce(u.signal,{preserveReason:!0});const E=(await Promise.allSettled(l.slice(h,h+16).map(g=>e.storage.setRaw(Br(d,g),"",u)))).find(g=>g.status==="rejected");if(E)throw E.reason}Ce(u.signal,{preserveReason:!0}),await e.storage.setRaw(wi(d),"[]",u)})}}}function kh(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=(Pi.get(e)??Promise.resolve()).catch(()=>{}).then(t);return Pi.set(e,r),r.finally(()=>{Pi.get(e)===r&&Pi.delete(e)})}const EN=128,gN=/^[A-Za-z0-9_-]+$/;function pN(e){const t=e.scopedStorage??vh({storage:e.storage,resolveScope:()=>Ph({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[Kn]:async n=>{Ce(e.operationContext.signal);const i=Rd(n,Kn,e.storageLimits?.maxKeyLength),s=await be(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:Ld(s)}},[Zn]:async n=>{Ce(e.operationContext.signal);const i=xh(n,"storage.setStorage 参数必须是对象"),s=Rd(i,Zn,e.storageLimits?.maxKeyLength),a=TN(i.data,e.storageLimits?.maxValueBytes);await be(()=>t.set(s,a,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(Ce(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"?Or("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const s=i.value;return{area:i.area,key:i.key,value:Ld(s),serializedValue:s,bytes:Uh(s)}}).sort((i,s)=>i.key.localeCompare(s.key)))}}}function Rd(e,t,r=EN){const i=xh(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Or("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!gN.test(i))throw Or("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function TN(e,t){let r;try{r=JSON.stringify(e)}catch{throw Or("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw Or("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Uh(r)>t)throw Or("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Ld(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function xh(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Or("INVALID_PARAMS",t);return e}function Uh(e){return new TextEncoder().encode(e).length}function Or(e,t){return{code:e,message:t}}const Pd=120;function or(e){throw{code:"INVALID_PARAMS",message:e}}function xc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bh(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&or(`${r} 不支持字段: ${n.join(", ")}`)}function _N(e){if(!xc(e))return or("ui.showToast 参数必须是对象");if(Bh(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return or("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Pd)return or(`ui.showToast message 不能超过 ${Pd} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return or("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function AN(e){return e===void 0?{dismissible:!1}:xc(e)?(Bh(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?or("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):or("ui.showLoading 参数必须是对象")}function IN(e){e!==void 0&&(!xc(e)||Object.keys(e).length)&&or("ui.hideLoading 不支持参数")}function bN(e){return{[Ms]:async(t,r)=>{const n=ke(e.operationContext,r.signal,r.requestId);Ce(n.signal),await be(()=>e.presentation.showToast(_N(t),n),n.signal)},[Cs]:async(t,r)=>{const n=ke(e.operationContext,r.signal,r.requestId);Ce(n.signal),await be(()=>e.presentation.showLoading(AN(t),n),n.signal)},[Rs]:async(t,r)=>{const n=ke(e.operationContext,r.signal,r.requestId);Ce(n.signal),IN(t),await be(()=>e.presentation.hideLoading(n),n.signal)}}}const yN={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return He(e,"当前用户首页资料接口响应异常")}},NN=3e4;function wN(e,t,r={}){const n=r.ttlMs??NN,i=r.requestPolicyEnabled!==!1,s=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let a=0,c,u;async function d(){let h;try{h=await _a(e,yN,void 0,{...t,credentials:"heybox-session",...s?{gate:s}:{}})}catch(f){throw t.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):f instanceof qe?p("REQUEST_UNSUPPORTED",f.message):f instanceof pi?p("INVALID_RESPONSE","user home_v2 响应不合法"):f instanceof sn?p("REQUEST_FAILED","user home_v2 请求失败"):f instanceof gi?i&&(f.status===403||f.status===429)?p("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:f.status,...f.retryAfterMs===void 0?{}:{retryAfterMs:f.retryAfterMs}}):p("REQUEST_FAILED",f.message):SN(f)?f:p("REQUEST_FAILED","user home_v2 请求失败")}return DN(h,"user home_v2")}function l(h){const f=Date.now();if(c?.userId===h&&c.expiresAt>f)return Promise.resolve(c.value);if(u?.userId===h&&u.generation===a)return u.promise;const E=a,g=d().then(b=>(a===E&&(c={userId:h,value:b,expiresAt:Date.now()+n}),b)).finally(()=>{u?.promise===g&&(u=void 0)});return u={userId:h,generation:E,promise:g},g}return{get:l,clear(){a+=1,c=void 0,u=void 0}}}function DN(e,t){if(!he(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(!he(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function SN(e){return he(e)&&typeof e.code=="string"&&typeof e.message=="string"}const ON={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 He(e,"关注用户接口响应异常")}},MN={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 He(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowStatus 接口响应异常")}},CN={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 He(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowGuidanceBegin 接口响应异常")}},RN={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 He(e,"Steam 游戏库接口响应异常")}};function LN(e,t=_o){const r=Pp({version:"2",validate:vN}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):_o,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 vd(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 PN(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 vN(e){if(!he(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 $r();for(const t of e.gameList){if(!he(t)||!Uo(t.appid)||!Uo(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw $r();for(const r of["image","portraitImage","icon"])kN(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 $r()}return e}function Uo(e){return typeof e=="number"&&Number.isFinite(e)}function kd(e,t){if(e[t]!==void 0&&!Uo(e[t]))throw $r()}function kN(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw $r()}function $r(){return p("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Hh=20,xN=100,UN=128,Fh=0,zh="weeks",BN=100,HN=new Set(["weeks","all","achieved"]);function FN(){return{nickname:"",avatar:""}}function zN(e){const t=wN(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??gf(),i=LN(n,r?e.steamGameListTtlMs:0);let s;const a=new Map;let c=Promise.resolve();function u(F,U){const H=JSON.stringify([F,U]);return(!s||s.key!==H)&&(s={key:H,scope:n.createScope(U,n.createScope(F))}),s.scope}function d(){const F=s;s=void 0,F&&n.invalidateScope(F.scope).catch(()=>{}),a.clear()}const l=Mf({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??wf))}),h=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let f,E,g=0,b=!1;const N=e.account.onChange(()=>{g+=1,t.clear(),l.invalidate(),d()}),y=e.authorization.onEvent((F,U)=>{F==="user_info_authorization_change"&&Object.values(U).some(H=>H==="denied")&&(g+=1,t.clear(),l.invalidate(),d(),c=c.then(async()=>{if(b)return;const H=await e.account.getCurrentUserId(e.operationContext);typeof H=="string"&&H.trim()&&await n.invalidateScope(u(I(),H.trim()))}).catch(()=>{}))});function w(){if(b||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function I(){const F=e.identity.get()?.miniProgramId?.trim();if(!F)throw p("INVALID_STATE","用户能力缺少 canonical 小程序身份");return F}async function x(){w(),await c,w();let F;try{F=await e.account.getCurrentUserId(e.operationContext)}catch(U){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Dn(U)?U:p("REQUEST_FAILED","读取小黑盒账号失败")}return typeof F=="string"&&F.trim()?F.trim():void 0}async function V(F,U){const H=await x();if(g!==U||H!==F)throw p("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function M(F,U,H=e.operationContext.signal){try{return await _a(e.network,F,U,{...e.operationContext,signal:H,credentials:"heybox-session",...h?{gate:h}:{}})}catch(P){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):P instanceof qe?p("REQUEST_UNSUPPORTED",P.message):P instanceof pi?p("INVALID_RESPONSE","用户接口响应不合法"):P instanceof sn?p("REQUEST_FAILED","用户请求失败"):P instanceof gi?r&&(P.status===403||P.status===429)?p("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:P.status,...P.retryAfterMs===void 0?{}:{retryAfterMs:P.retryAfterMs}}):p("REQUEST_FAILED",P.message):Dn(P)?P:p("REQUEST_FAILED","用户请求失败")}}async function R(F,U){if(!e.authorizationContext)return{mini_program_id:F};let H;try{H=await be(()=>e.authorizationContext.get({...e.operationContext,signal:U}),U)}catch(P){if(Dn(P))throw P;const C=p("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(C,"cause",{configurable:!0,value:P}),C}if(!H.token?.trim())throw p("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:F,runtime_auth_context_token:H.token}}async function L(){w();const F=I(),U=g,H=await x();if(!H){if(g!==U)throw p("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const P=await R(F,e.operationContext.signal);await V(H,U);const C=await M(MN,P);if(await V(H,U),I()!==F)throw p("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Bd(Ud(C))}function Y(F,U){if(!F)return Promise.reject(p("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(U?.aborted)return Promise.reject(p("REQUEST_CANCELLED","关注操作已取消"));if(f)return Promise.reject(p("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(p("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const H=j(U).finally(()=>{f===H&&(f=void 0)});return f=H,H}async function j(F){w();const U=I(),H=new AbortController;E=H;const P=()=>H.abort();e.operationContext.signal.addEventListener("abort",P,{once:!0}),F?.addEventListener("abort",P,{once:!0});let C=()=>{},Q=!1;try{try{await be(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:H.signal}),H.signal)}catch(B){throw Dn(B)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(B.code)?p("FOLLOW_CANCELLED","已取消小黑盒登录"):B}w();const S=g;C=e.account.onChange(()=>{Q=!0,P()});const q=await be(x,H.signal);if(!q)throw p("FOLLOW_CANCELLED","未完成小黑盒登录");const W=async()=>{if(await be(()=>V(q,S),H.signal),w(),I()!==U)throw p("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await W();const Z=await R(U,H.signal);await W();const se=KN(),de=await be(()=>M(CN,{...Z,request_id:se},H.signal),H.signal);await W();const Ie=Ud(de);if(Ie.status!=="notFollowing")return Bd(Ie);if(Ie.rateLimited)throw p("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const Re=await be(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:U,signal:H.signal}),H.signal);if(await W(),Re!=="confirmed")throw p("FOLLOW_CANCELLED","已取消关注作者");const Ue=Ie.authorId,_=await be(()=>M(ON,{body:{following_id:Ue}},H.signal),H.signal);if(await W(),_.status!=="ok"){const B=["login","relogin","lack_token"].includes(_.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw p(B,typeof _.msg=="string"&&_.msg.trim()?_.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(S){throw w(),Q?p("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):F?.aborted?p("REQUEST_CANCELLED","关注操作已取消"):Dn(S)?S:p("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{C(),e.operationContext.signal.removeEventListener("abort",P),F?.removeEventListener("abort",P),E===H&&(E=void 0)}}async function ee(){I();const F=g,U=await x();if(!U)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[H,P]=await Promise.all([e.authorization.getOrCreateLocalIdentity(U),k(U).catch(()=>FN())]);return await V(U,F),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:H.appUserId,profile:P,...H.steamId?{steam_id:H.steamId}:{}}}}function k(F){return l.read(F,()=>M(Of,void 0).then(U=>{const H=Bo(U,"账号基础信息");if(H.display_username!==void 0&&typeof H.display_username!="string")throw p("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(H.display_avatar!==void 0&&typeof H.display_avatar!="string")throw p("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:H.display_username??"",avatar:H.display_avatar??""}}))}async function z(F){const U=jN(F),H=I(),P=g,C=await x();if(!C)return d(),{isLogin:!1,isBound:!1,data:null};const Q=await t.get(C);await V(C,P);const S=jh(Q.steam_id_info);if(Object.keys(S).length===0)return await n.invalidateScope(u(H,C)).catch(()=>{}),await V(C,P),a.delete(JSON.stringify([H,C])),{isLogin:!0,isBound:!1,data:null};const q=JSON.stringify([H,C]),W=u(H,C),Z=vd({...U,steamId:void 0},S),se=Vh(S.personal_infomation_open??S.personal_information_open),de=JSON.stringify([Z??null,se??null]),Ie=a.get(q);Ie&&Ie.identity!==de&&(await n.invalidateScope(W).catch(()=>{}),await V(C,P));const Re={identity:de,scope:n.createScope(de,W)};a.set(q,Re);const Ue=vd(U,S),_=Ue?i.persistent:i.unresolved,B=n.createScope(Ue??"unresolved",Re.scope),K=async()=>{if(await V(C,P),I()!==H||a.get(q)?.identity!==de)throw p("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},J=await _.read({scope:B,key:PN({miniProgramId:H,userId:C,effectiveSteamId:Ue,personalInformationOpen:se,query:U}),signal:e.operationContext.signal,load:async Ee=>{const me=await M(RN,{userId:C,...U,personalInformationOpen:se},Ee);return await K(),qN(Bo(me,"Steam 游戏库"),U)}}).catch(async Ee=>{throw await K(),Ee});return await K(),{isLogin:!0,isBound:!0,data:J}}return{getFollowStatus:L,requestFollowAuthor:Y,getInfo:ee,getSteamGameList:z,async invalidateSteamGameListCache(){const F=I(),U=g,H=await x();if(!H)return;const P=u(F,H);await Promise.all([i.persistent.invalidateScope(P),i.unresolved.invalidateScope(P)]),t.clear(),a.delete(JSON.stringify([F,H])),await V(H,U)},dispose(){b||(b=!0,E?.abort(),g+=1,N(),y(),t.clear(),l.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function jN(e){if(e==null)return{limit:Hh,offset:Fh,sort:zh,includeHidden:!1};if(!he(e))throw cr("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw cr(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:VN(e.limit),offset:GN(e.offset),sort:YN(e.sort),includeHidden:QN(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>UN)throw cr("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw cr("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,BN))}return r}function VN(e){if(e===void 0)return Hh;if(!Number.isInteger(e)||Number(e)<1)throw cr("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),xN)}function GN(e){if(e===void 0)return Fh;if(!Number.isInteger(e)||Number(e)<0)throw cr("user.getSteamGameList offset 必须是非负整数");return Number(e)}function YN(e){if(e===void 0)return zh;if(typeof e!="string"||!HN.has(e))throw cr("user.getSteamGameList sort 不支持");return e}function QN(e){if(e===void 0)return!1;if(typeof e!="boolean")throw cr("user.getSteamGameList includeHidden 必须是 boolean");return e}function qN(e,t){if(!Array.isArray(e.game_list))throw p("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(WN).filter(c=>c!==void 0),n=Zs(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 a=Vh(e.is_me);return a!==void 0&&(s.isMe=a),s}function WN(e){const t=jh(e),r=Zs(t.appid),n=Zs(t.steam_appid)??r,i=Uc(t.name);if(r===void 0||n===void 0||!i)return;const s={appid:r,steamAppid:n,name:i};Xa(s,"image",t.image),typeof t.vertical_head_image=="string"&&Xa(s,"portraitImage",t.vertical_head_image),Xa(s,"icon",t.appicon??t.icon),xd(s,"playtimeForever",t.playtime_forever),xd(s,"playtime2Weeks",t.playtime_2weeks);const a=$N(t.external_tags??t.tags);return a.length&&(s.tags=a),s}function Bo(e,t){if(!he(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(!he(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function jh(e){return he(e)?e:{}}function Uc(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function $N(e){return Array.isArray(e)?e.map(Uc).filter(Boolean):[]}function Zs(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function Vh(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function Xa(e,t,r){const n=Uc(r);n&&Object.assign(e,{[t]:n})}function xd(e,t,r){const n=Zs(r);n!==void 0&&Object.assign(e,{[t]:n})}function cr(e){return p("INVALID_PARAMS",e)}function Dn(e){return he(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Ud(e){const t=Bo(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 Bd(e){return e.status}function KN(){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 ZN(e){return{[as]:async t=>(vi(t,"user.getFollowStatus"),e.user.getFollowStatus()),[os]:async(t,r)=>(vi(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[cs]:async t=>(vi(t,"user.getInfo"),e.user.getInfo()),[us]:async(t,r)=>{vi(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[ds]:async t=>e.user.getSteamGameList(t)}}function vi(e,t){if(e!==void 0)throw p("INVALID_PARAMS",`${t} 不接收入参`)}function XN(){return p("USER_DATA_PERMISSION_STATE_INVALID","本地用户数据许可状态异常,已停止访问")}function Hd(e){return p("USER_DATA_PERMISSION_SAVE_FAILED","本次运行已停止访问,设置未保存,请重试",e===void 0?void 0:{reason:e instanceof Error?e.message:String(e)})}function JN(e){const t=e.managedResources??Ir,r=typeof e.storage.withLock=="function"||typeof navigator<"u"&&!!navigator.locks,n=e.hash??Tc,i=new Map,s=new Set;let a=!1;function c(){if(a)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function u(I,x){if(e.storage.withLock)return e.storage.withLock(l(I),x);if(typeof navigator<"u"&&navigator.locks)return kh(l(I),x);throw p("REQUEST_UNSUPPORTED","当前宿主不支持跨实例保存资料许可")}function d(I){return WE({miniProgramId:e.resolveMiniProgramId(),userId:I,environment:e.resolveEnvironment()})}function l(I){return jE(qE(d(I)))}function h(I,x){return e.purposeOf?n(kl(I,e.revisionOf(I),x,e.purposeOf(I))):n(`${I}\0${e.revisionOf(I)}\0${x}`)}function f(I,x){return`${I}\0${x}`}async function E(I,x){let V;try{V=await e.storage.getRaw(l(I),x)}catch(R){throw c(),x.signal.aborted?p("REQUEST_CANCELLED","许可操作已取消"):p("USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","无法读取本地用户数据许可",{reason:R instanceof Error?R.message:String(R)})}if(c(),x.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");const M=V===void 0||V===""?void 0:QE(V);if(V!==void 0&&V!==""&&M===void 0)throw XN();return M??{schema_version:1,records:{}}}async function g(I,x,V){if(c(),V.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");await e.storage.setRaw(l(I),JSON.stringify(x),V)}function b(I){return I?.revision??0}function N(I,x,V){const M=new Set(V.declared??[]),R=new Set(t);for(const j of Object.keys(x.records))nr(j)&&R.add(j);for(const j of i.keys())j.startsWith(`${I}\0`)&&R.add(j.slice(I.length+1));const Y=[...R].sort((j,ee)=>{const k=Ir.indexOf(j),z=Ir.indexOf(ee);return(k<0?Number.MAX_SAFE_INTEGER:k)-(z<0?Number.MAX_SAFE_INTEGER:z)}).map(j=>{const ee=x.records[j],k=b(ee),z=V.egressTier===void 0?void 0:h(j,V.egressTier),F=i.get(f(I,j)),U=F!==void 0&&F.revision===k&&(z===void 0||F.consentFingerprint===z);return{resource:j,name:Ec(j)?.name??j,purposeText:e.purposeOf?.(j)??"",scopeFingerprint:z??"",declared:M.has(j),available:M.has(j),decision:ee?.decision??"ask",revision:k,...ee?.decision==="allow"&&ee.consentFingerprint?{consentFingerprint:ee.consentFingerprint}:{},sessionAllowed:U,allowed:!s.has(f(I,j))&&M.has(j)&&ee?.decision!=="deny"&&(U||r&&ee?.decision==="allow"&&z!==void 0&&ee.consentFingerprint===z)}});return Object.freeze({schema_version:1,canPersist:r,resources:Object.freeze(Y),...V.egressTier===void 0?{}:{egressTier:V.egressTier}})}function y(I,x,V,M){const R=x.records[V],L=f(I,V);if(s.has(L))return{status:"denied",reason:"tightening"};if(R?.decision==="deny")return{status:"denied",reason:"deny"};const Y=h(V,M);if(r&&R?.decision==="allow"&&R.consentFingerprint===Y)return{status:"allowed",source:"persistent"};const j=i.get(L);return j&&j.revision===b(R)&&j.consentFingerprint===Y?{status:"allowed",source:"session"}:{status:"ask"}}function w(I){if(typeof I!="string"||!Ir.includes(I))throw p("INVALID_PARAMS","用户数据资源标识不合法")}return{canPersist:r,async read(I,x,V={}){c();const M=await E(I,x);return N(I,M,V)},async evaluate(I,x,V){c(),w(x.resource);const M=await E(I,V);return y(I,M,x.resource,x.egressTier)},async decide(I,x){c(),w(I.resource);const V=async()=>{c();const M=await E(I.userId,x);if(c(),x.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");const R=M.records[I.resource],L=b(R);if(I.expectedRevision!==void 0&&L!==I.expectedRevision)throw p("AUTHORIZATION_CONTEXT_CHANGED","资料许可已变化,请重新确认");const Y=f(I.userId,I.resource),j=h(I.resource,I.egressTier);if(I.expectedFingerprint!==void 0&&I.expectedFingerprint!==j)throw p("AUTHORIZATION_CONTEXT_CHANGED","资料披露范围已变化,请重新确认");if(I.scope==="session"){if(I.decision!=="allow")throw p("INVALID_PARAMS","本次许可只支持允许");return i.set(Y,Object.freeze({revision:L,consentFingerprint:j})),N(I.userId,M,{egressTier:I.egressTier})}const ee=L+1,k=I.decision==="allow"?{decision:"allow",revision:ee,consentFingerprint:j}:{decision:I.decision,revision:ee},z={schema_version:1,records:{...M.records,[I.resource]:k}};I.decision!=="allow"&&(s.add(Y),i.delete(Y));try{await g(I.userId,z,x)}catch(F){throw Hd(F)}return s.delete(Y),i.delete(Y),N(I.userId,z,{egressTier:I.egressTier})};return I.scope==="session"?V():u(I.userId,V)},async revokeSession(I,x){c(),I.resource!==void 0&&w(I.resource);for(const M of[...i.keys()])M.startsWith(`${I.userId}\0`)&&(I.resource===void 0||M===f(I.userId,I.resource))&&i.delete(M);const V=await E(I.userId,x);return N(I.userId,V,{})},async reset(I,x){return c(),u(I.userId,async()=>{c();const V=await E(I.userId,x);if(c(),x.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");const M=new Set(t);for(const Y of Object.keys(V.records))M.add(Y);for(const Y of i.keys())Y.startsWith(`${I.userId}\0`)&&M.add(Y.slice(I.userId.length+1));for(const Y of M)s.add(f(I.userId,Y));for(const Y of[...i.keys()])Y.startsWith(`${I.userId}\0`)&&i.delete(Y);const R={...V.records};for(const Y of M)R[Y]={decision:"ask",revision:(R[Y]?.revision??0)+1};const L={schema_version:1,records:R};try{await g(I.userId,L,x)}catch(Y){throw Hd(Y)}for(const Y of M)s.delete(f(I.userId,Y));return N(I.userId,L,{})})},dispose(){a||(a=!0,i.clear(),s.clear())}}}const Sa={auth:"none",channel:"api",method:"POST",bodyEncoding:"form",failurePresentation:"none",parse(e){return He(e,"游戏资料接口响应异常")}};function Oa(e){return{runtime_auth_context_token:e.runtime_auth_context_token,resource:e.resource,disclosure_revision:e.disclosure_revision}}const ew={...Sa,id:"heybox.user_miniprogram.runtime.user_game_data.query.post",path:"/user_miniprogram/runtime/user_game_data/query",body(e){return{...Oa(e),operation:e.operation,schema_version:e.schema_version,...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit}}}},tw={...Sa,id:"heybox.user_miniprogram.runtime.user_game_data.sync.post",path:"/user_miniprogram/runtime/user_game_data/sync",body:Oa},Fd={...Sa,id:"heybox.user_miniprogram.runtime.user_game_data.sync_status.post",path:"/user_miniprogram/runtime/user_game_data/sync_status",body(e){return{...Oa(e),task_id:e.task_id}}},rw={...Sa,id:"heybox.user_miniprogram.runtime.user_game_data.file.post",path:"/user_miniprogram/runtime/user_game_data/file",body(e){return{...Oa(e),save_id:e.save_id,file_id:e.file_id}}};function nw(e){const t=xf(e.storage),r=e.fileDownloads??(e.files&&e.transfer?Dc({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 ie("REQUEST_CANCELLED","资料请求已取消")};async function s(d,l){if(i(l),!e.authorizationContext)throw ie("REQUEST_UNSUPPORTED","宿主缺少受信运行上下文");const h=await e.authorizationContext.get(l);if(!h.token||!Number.isFinite(h.expiresAt)||h.expiresAt<=Date.now())throw ie("UNAUTHORIZED","受信运行上下文已过期");return{runtime_auth_context_token:h.token,resource:d.key,disclosure_revision:d.disclosureRevision}}async function a(d,l,h){i(h);const f=await Ti({network:e.network,operationContext:h,subject:"游戏资料",assertUsable:()=>i(h),requestPolicyEnabled:e.requestPolicyEnabled,...e.requestGate?{gate:{capability:"userGameData",gate:e.requestGate}}:{}},d,l),E=rt(f,"user.data","游戏资料");if(!Se(E))throw ie("INVALID_RESPONSE","游戏资料响应无效");return i(h),E}const c=d=>{const l=Ec(d);if(!l)throw ie("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 h=c(d.resource),f=h.queries[d.operation];if(!f)throw ie("REQUEST_UNSUPPORTED","未开放资料操作");const E=await a(ew,{...await s(h,l),operation:d.operation,schema_version:f.version,...d.cursor===void 0?{}:{cursor:d.cursor},...d.limit===void 0?{}:{limit:d.limit}},l);if(E.resource!==d.resource||E.operation!==d.operation||E.schema_version!==f.version||E.disclosure_revision!==h.disclosureRevision)throw ie("INVALID_RESPONSE","游戏资料合同不匹配");if(E.status==="ready"){if(!BE(f.schema,E.data))throw ie("INVALID_RESPONSE","游戏资料正文不匹配公开 schema");return{status:"ready",data:E.data,meta:{},schemaVersion:f.version}}if(E.status==="empty"&&(E.reason==="no_data"||E.reason==="not_ready")&&typeof E.message=="string")return{status:"empty",reason:E.reason,message:E.message,meta:{},schemaVersion:f.version};throw ie("INVALID_RESPONSE","游戏资料状态无效")},async sync(d,l,h){const f=c(d.resource);if(f.game===null||!f.operations.includes("sync"))throw ie("REQUEST_UNSUPPORTED","资源不支持同步");const E=await s(f,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),w={...l,signal:g.signal},I={...h,gameId:f.game,resource:d.resource};let x;try{const V=await t.run(I,w,async()=>{const R=await t.get(I,w);if(R)return x=R,{id:R,status:await a(Fd,{...await s(f,w),task_id:R},w)};const L=await a(tw,E,w);if(typeof L.task_id!="string"||!L.task_id||L.task_id.length>128)throw ie("INVALID_RESPONSE","同步任务缺失");return await t.set(I,L.task_id,w),{id:L.task_id,status:L}});let M=V.status;for(x=V.id;;){if(i(w),M.state==="succeeded")return await t.remove(I,x,w),{status:"succeeded"};if(M.state==="failed")throw await t.remove(I,x,w),ie(typeof M.error_code=="string"?M.error_code:"SYNC_FAILED","存档同步失败");if(M.state!=="syncing"&&M.state!=="uploading")throw ie("INVALID_RESPONSE","同步状态无效");if(await iw(w.signal),M=await a(Fd,{...await s(f,w),task_id:x},w),M.task_id!==x)throw ie("INVALID_RESPONSE","同步任务不匹配")}}catch(V){throw x&&Se(V)&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED"].includes(String(V.code))&&await t.remove(I,x,w),N?ie("REQUEST_TIMEOUT","等待同步超时,后台任务可能仍在执行"):V}finally{clearTimeout(y),l.signal.removeEventListener("abort",b)}},async file(d,l,h){const f=c(d.resource);if(!f.operations.includes("file")||!r)throw ie("REQUEST_UNSUPPORTED","宿主不支持资料文件下载");const E=async b=>{await h(b);const N=await a(rw,{...await s(f,b),save_id:d.saveId,file_id:d.fileId},b);if(!Se(N.file)||N.file.file_id!==d.fileId)throw ie("INVALID_RESPONSE","文件标识不匹配");return await h(b),N},g=await r.download(await E(l),async b=>{await E(b)},l);try{return i(l),await h(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(ie("REQUEST_CANCELLED","已停止等待同步"))},i=setTimeout(()=>{e.removeEventListener("abort",n),t()},2e3);e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})}const Sn=["event_id","miniProgramId","environment","host_platform","host_version","sdk_version","runtime_version","egress_tier","resource","call_id","flow_id"],sw=Object.freeze({user_game_data_permission_show:new Set([...Sn,"entry","reason"]),user_game_data_permission_result:new Set([...Sn,"choice","apply_result"]),user_game_data_permission_manage:new Set([...Sn,"operation","apply_result","succeeded_count","failed_count"]),user_game_data_action:new Set([...Sn,"stage","action_type","outcome","duration_ms"]),user_game_data_access_result:new Set([...Sn,"api","trigger","status","error_code","failure_stage","duration_ms","cache_hit","sample_rate","overview_status_counts"])}),zd=10*6e4,aw=256;function ow(e){const t=e.now??Date.now,r=e.random??Math.random,n=e.createId??lw,i=uw(e.sampleRate),s=new Map,a=new Map,c=new Map;let u=!1,d=0,l=0,h=0,f=0;const E={get emitted(){return d},get failed(){return l},get skipped(){return h},get deduplicated(){return f}};function g(M){return`${M}${n()}`}function b(){const M=t();for(const[R,L]of s)M-L.createdAt<=zd||(s.delete(R),a.get(L.key)===R&&a.delete(L.key));for(const[R,L]of c){if(M-L<=zd&&c.size<=aw)break;c.delete(R)}}function N(M){const R=s.get(M);R!==void 0&&(s.delete(M),a.get(R.key)===M&&a.delete(R.key))}function y(M){N(M),c.delete(M),c.set(M,t())}function w(M,R){const L=sw[M],Y={};for(const[j,ee]of Object.entries(R))ee===void 0||!L.has(j)||(Y[j]=ee);return Object.freeze(Y)}function I(M){const R={event_id:g("evt_"),miniProgramId:Yr(()=>e.resolveMiniProgramId())??"unknown",environment:cw(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:dw(e)};return M.resource!==void 0&&(R.resource=M.resource),M.callId!==void 0&&(R.call_id=M.callId),M.flowId!==void 0&&(R.flow_id=M.flowId),R}function x(M,R){if(u){h+=1;return}try{if(e.sink===void 0){h+=1;return}e.sink.postEvent(M,w(M,R)),d+=1}catch{l+=1}}function V(M,R){if(M===void 0)return!1;const L=s.get(M);return L===void 0?!1:R==="start"&&L.started||R==="shown"&&L.shown||R==="decided"&&L.decided?!0:(R==="start"&&(L.started=!0),R==="shown"&&(L.shown=!0),R==="decided"&&(L.decided=!0),!1)}return{diagnostics:E,createCallId(){return g("call_")},beginFlow(M){b();const R=`${M.resource??""}\0${M.actionType}`,L=a.get(R);if(L!==void 0&&s.has(L))return L;const Y=g("flow_");return s.set(Y,{key:R,createdAt:t(),started:!1,shown:!1,decided:!1}),a.set(R,Y),Y},permissionShow(M){if(V(M.flowId,"shown")){f+=1;return}x("user_game_data_permission_show",{...I(M),entry:M.entry,reason:M.reason})},permissionResult(M){if(V(M.flowId,"decided")){f+=1;return}x("user_game_data_permission_result",{...I(M),choice:M.choice,apply_result:M.applyResult})},permissionManage(M){x("user_game_data_permission_manage",{...I(M),operation:M.operation,apply_result:M.applyResult,...M.succeededCount===void 0?{}:{succeeded_count:M.succeededCount},...M.failedCount===void 0?{}:{failed_count:M.failedCount}})},action(M){if(M.stage==="start"&&V(M.flowId,"start")){f+=1;return}if(M.stage==="finish"){if(M.flowId!==void 0&&c.has(M.flowId)){f+=1;return}M.flowId!==void 0&&y(M.flowId)}x("user_game_data_action",{...I(M),stage:M.stage,action_type:M.actionType,...M.outcome===void 0?{}:{outcome:M.outcome},...M.durationMs===void 0?{}:{duration_ms:Math.max(0,Math.round(M.durationMs))}})},access(M){if(i<=0){h+=1;return}if(i<1&&r()>=i){h+=1;return}x("user_game_data_access_result",{...I(M),api:M.api,trigger:M.trigger,status:M.status,duration_ms:Math.max(0,Math.round(M.durationMs)),sample_rate:i,...M.errorCode===void 0?{}:{error_code:M.errorCode},...M.failureStage===void 0?{}:{failure_stage:M.failureStage},...M.cacheHit===void 0?{}:{cache_hit:M.cacheHit},...M.overviewStatusCounts===void 0?{}:{overview_status_counts:M.overviewStatusCounts}})},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear())}}}function cw(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 uw(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 dw(e){try{return e.resolveEgressTier()==="upload"?"upload":"no_network"}catch{return"no_network"}}function lw(){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 Ut(e){const t=ot(e);return t.valid?t.permissions.network?.status==="enabled"||t.permissions.companion?.status==="enabled"?"upload":"no_network":"upload"}function fw(e){let t=!1;const r=e.verifiedSdkVersion!==void 0&&(Ta(e.verifiedSdkVersion,"0.10.0-alpha.1")??-1)>=0,n=new Set;let i,s=0,a,c=!1;const u=new Map,d=new Map,l=new Set,h=new Map,f=e.now??Date.now,E=_=>x()[_]?.purpose??"",g=_=>{const B=Ec(_);if(!B)throw p("REQUEST_UNSUPPORTED","未开放的资料资源");return B},b=_=>kl(_,g(_).disclosureRevision,Ut(e.runtimePermissions),E(_)),N=()=>JN({storage:e.storage,resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,revisionOf:_=>g(_).disclosureRevision,purposeOf:E,...e.hash?{hash:e.hash}:{}});let y=N();const w=ow({resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,resolveEgressTier:()=>Ut(e.runtimePermissions),...e.telemetry??{}}),I=nw({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 x(){const _=ot(e.runtimePermissions),B=_.valid?_.permissions.user_game_data:void 0;return B?.status==="enabled"?si(B.config.resources):{}}function V(_){if(t||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序已关闭");if(_?.signal.aborted)throw p("REQUEST_CANCELLED","资料请求已取消")}function M(_){for(const[B,K]of u)K!==void 0&&(_===void 0||K===_)&&B.abort()}function R(_){for(const[B,K]of d)(_===void 0||B===_)&&(K.abort(),d.delete(B))}function L(){s++,R();for(const _ of u.keys())_.abort();for(const _ of l)e.fileRegistry.revokeFiles([_]);l.clear(),h.clear(),I.invalidate()}const Y=_i(e.account,_=>{if(c&&a===_)return;const B=a;c=!0,a=_,B!==void 0&&(L(),y.dispose(),y=N())}),j=()=>L();e.operationContext.signal.addEventListener("abort",j,{once:!0});async function ee(_,B){V(_);const K=new AbortController,J=()=>K.abort();u.set(K,void 0),_.signal.addEventListener("abort",J,{once:!0}),_.signal.aborted&&J();const Ee={...e.operationContext,..._,signal:K.signal};try{const me=await B(Ee);return V(Ee),me}catch(me){throw he(me)&&me.name==="AbortError"?p("REQUEST_CANCELLED","资料操作已取消"):me}finally{_.signal.removeEventListener("abort",J),u.delete(K)}}function k(_){const B=g(_);if(!E(B.key))throw p("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明这项游戏资料",{resource:B.key});return B}async function z(_){V(_);const B=await e.account.getCurrentUserId(_);if(V(_),!c)c=!0,a=B;else if(a!==B){const K=a;a=B,K!==void 0&&(L(),y.dispose(),y=N(),V(_))}return B}function F(_,B){const K={login_required:"请先登录小黑盒",permission_required:"尚未允许读取这项资料",permission_denied:"已拒绝读取这项资料",source_not_linked:"请先在小黑盒关联对应游戏账号",source_login_required:"请先在小黑盒更新游戏来源登录"},J=B==="login_required"?{type:"user_login",label:"登录并授权"}:B==="permission_required"?{type:"permission",label:"允许读取"}:B==="permission_denied"&&e.presentation?.openDataPermissions?{type:"manage",label:"管理数据权限"}:void 0;return{status:"blocked",resource:_,reason:B,message:K[B],...J?{interaction:J}:{}}}async function U(_,B){k(_);const K=await z(B);if(!K)return F(_,"login_required");const J=await y.evaluate(K,{resource:_,egressTier:Ut(e.runtimePermissions)},B);return V(B),J.status==="allowed"?{userId:K}:F(_,J.status==="denied"?"permission_denied":"permission_required")}async function H(_,B,K,J,Ee){if(V(Ee),s!==K||await z(Ee)!==B||b(_)!==J)throw p("AUTHORIZATION_CONTEXT_CHANGED","账号或资料范围已变化");return U(_,Ee)}function P(_,B){if(!he(_)||typeof _.resource!="string")throw p("INVALID_PARAMS","资料请求无效");if(!nr(_.resource))throw p("REQUEST_UNSUPPORTED","当前宿主尚未开放该资料资源");const K=B==="query"?["resource","operation","schemaVersion","cursor","limit"]:["resource","saveId","fileId"];if(Object.keys(_).some(Ee=>!K.includes(Ee)))throw p("INVALID_PARAMS","资料请求包含未知参数");const J=k(_.resource);if(B==="query"){if(_.operation!=="get"&&_.operation!=="list")throw p("INVALID_PARAMS","资料查询操作无效");const Ee=J.queries[_.operation];if(!Ee)throw p("REQUEST_UNSUPPORTED","资源不支持该查询");if(_.schemaVersion!==Ee.version)throw p("REQUEST_UNSUPPORTED","SDK 与宿主正文合同版本不匹配");if(_.operation!=="list"&&(_.cursor!==void 0||_.limit!==void 0))throw p("INVALID_PARAMS","单份查询不能分页");if(_.cursor!==void 0&&(typeof _.cursor!="string"||!_.cursor||_.cursor.length>32768))throw p("INVALID_PARAMS","分页游标无效");if(!Ee.page&&(_.cursor!==void 0||_.limit!==void 0))throw p("INVALID_PARAMS","该列表不支持分页");if(_.limit!==void 0&&(typeof _.limit!="number"||!Number.isInteger(_.limit)||_.limit<1||_.limit>(Ee.page?.maxSize??100)))throw p("INVALID_PARAMS","分页数量无效")}else if(!J.operations.includes(B))throw p("REQUEST_UNSUPPORTED","资源不支持该操作");if(B==="file"&&(typeof _.saveId!="string"||!_.saveId||typeof _.fileId!="string"||!_.fileId))throw p("INVALID_PARAMS","资料文件标识无效");return B==="query"?{resource:_.resource,operation:_.operation,schemaVersion:_.schemaVersion,..._.cursor===void 0?{}:{cursor:_.cursor},..._.limit===void 0?{}:{limit:_.limit}}:{resource:_.resource,saveId:_.saveId,fileId:_.fileId}}async function C(_,B,K,J){const Ee=f(),me=s,De=b(B.resource);for(const we of u.keys())we.signal===K.signal&&u.set(we,B.resource);try{const we=await U(B.resource,K);if("status"in we)return w.access({resource:B.resource,api:_,trigger:"initial",status:"blocked",durationMs:f()-Ee}),we;let Oe;try{Oe=await J()}catch(Me){const Xe=he(Me)?Me.code:void 0;if(Xe==="USER_DATA_SOURCE_NOT_LINKED"||Xe==="USER_DATA_SOURCE_LOGIN_REQUIRED")return w.access({resource:B.resource,api:_,trigger:"initial",status:"blocked",durationMs:f()-Ee}),F(B.resource,Xe==="USER_DATA_SOURCE_NOT_LINKED"?"source_not_linked":"source_login_required");throw Me}const Pe=await H(B.resource,we.userId,me,De,K);return"status"in Pe?(w.access({resource:B.resource,api:_,trigger:"initial",status:"blocked",durationMs:f()-Ee}),Pe):(w.access({resource:B.resource,api:_,trigger:"initial",status:he(Oe)&&Oe.status==="empty"?"empty":_===kn?"succeeded":"ready",durationMs:f()-Ee}),Oe)}catch(we){throw w.access({resource:B.resource,api:_,trigger:"initial",status:"error",durationMs:f()-Ee,errorCode:he(we)?String(we.code):"REQUEST_FAILED"}),we}}async function Q(_){const B=await z(_);if(!B)throw p("UNAUTHORIZED","请先登录小黑盒");const K=await y.read(B,_,{declared:Object.keys(x()),egressTier:Ut(e.runtimePermissions)});return E(Jt)?K:{...K,resources:K.resources.filter(({resource:J})=>J!==Jt)}}async function S(_){const B=await _;return r?B:{...B,resources:B.resources.filter(({resource:K})=>K!==Jt)}}async function q(_,B,K){const J=k(_),Ee=K!==void 0;if(Ee&&a!==K)return{status:"cancelled"};let me=K??await z(B);if(!me&&!Ee&&(await e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:B.signal}),me=await z(B)),!me)return{status:"cancelled"};let De=await y.evaluate(me,{resource:_,egressTier:Ut(e.runtimePermissions)},B);if(De.status==="allowed")return{status:"allowed"};if(De.status==="denied"){if(Ee)return{status:"denied"};if(e.presentation?.openDataPermissions){const Pe=s,Me=b(_),Xe=await e.presentation.openDataPermissions({resource:_,miniProgramName:e.miniProgramPresentation?.name,signal:B.signal});if(!("status"in await H(_,me,Pe,Me,B)))return{status:"allowed"};if(!Xe)return{status:"cancelled"}}return De=await y.evaluate(me,{resource:_,egressTier:Ut(e.runtimePermissions)},B),{status:De.status==="allowed"?"allowed":"denied"}}if(!e.presentation?.confirmDataPermission)throw p("REQUEST_UNSUPPORTED","当前宿主不支持资料许可弹窗");if(_!==Jt)return Z(J,me,B);const we=i;if(we?.userId===me)return be(()=>we.result,B.signal);const Oe={userId:me,result:Z(J,me,B)};i=Oe;try{return await Oe.result}finally{i===Oe&&(i=void 0)}}async function W(){if(!(!e.presentation?.confirmDataPermission||!E(Jt)))try{const _=await z(e.operationContext);if(!_||n.has(_))return;await ee(e.operationContext,B=>q(Jt,B,_))}catch{}}async function Z(_,B,K){const J=_.key;R(J);const Ee=new AbortController;d.set(J,Ee);const me=()=>Ee.abort();K.signal.addEventListener("abort",me,{once:!0}),K.signal.aborted&&me();const De={...K,signal:Ee.signal},we=s,Oe=b(J),Pe=y,Me=w.beginFlow({resource:J,actionType:"permission"});let Xe="error";try{const Je=(await Pe.read(B,De,{egressTier:Ut(e.runtimePermissions)})).resources.find(La=>La.resource===J);w.action({resource:J,flowId:Me,stage:"start",actionType:"permission"}),w.permissionShow({resource:J,flowId:Me,entry:"other",reason:Je?.decision==="allow"?"scope_changed":"first"});const mt=await be(()=>e.presentation.confirmDataPermission({miniProgramName:e.miniProgramPresentation?.name,resource:J,scopeText:`此黑盒账号关联的${_.name}${_.operations.includes("sync")?`。${O0}`:""}`,purposeText:E(J),egress:Ut(e.runtimePermissions),canPersist:Pe.canPersist,...J===Jt&&{onShown:()=>{!Ee.signal.aborted&&s===we&&n.add(B)}},signal:Ee.signal}),Ee.signal);if(V(De),s!==we||await z(De)!==B||b(J)!==Oe)throw p("AUTHORIZATION_CONTEXT_CHANGED","资料许可范围已变化");return mt.decision==="cancelled"?(Xe="cancelled",w.permissionResult({resource:J,flowId:Me,choice:"cancel",applyResult:"cancelled"}),{status:"cancelled"}):(await Pe.decide({userId:B,resource:J,decision:mt.decision==="deny"?"deny":"allow",scope:mt.decision==="session"?"session":"persistent",egressTier:Ut(e.runtimePermissions),expectedRevision:Je?.revision??0,expectedFingerprint:Je?.scopeFingerprint},De),mt.decision==="deny"&&M(J),Xe=mt.decision==="deny"?"unresolved":"resolved",w.permissionResult({resource:J,flowId:Me,choice:mt.decision,applyResult:"applied"}),{status:mt.decision==="deny"?"denied":"allowed"})}catch(ut){throw Xe=De.signal.aborted?"cancelled":"error",w.permissionResult({resource:J,flowId:Me,choice:"cancel",applyResult:De.signal.aborted?"cancelled":"error"}),ut}finally{w.action({resource:J,flowId:Me,stage:"finish",actionType:"permission",outcome:Xe}),K.signal.removeEventListener("abort",me),d.get(J)===Ee&&d.delete(J)}}async function se(_,B,K,J,Ee,me){B==="allow"?k(_):g(_);const De=await z(J);if(!De)throw p("UNAUTHORIZED","请先登录小黑盒");try{await y.decide({userId:De,resource:_,decision:B,scope:K,expectedRevision:Ee,expectedFingerprint:me,egressTier:Ut(e.runtimePermissions)},J)}catch(we){throw he(we)&&we.code==="USER_DATA_PERMISSION_SAVE_FAILED"&&M(_),we}return R(_),B!=="allow"&&M(_),Q(J)}async function de(_,B,K){try{const J=await K();return w.permissionManage({operation:_,resource:B,applyResult:"applied"}),J}catch(J){throw w.permissionManage({operation:_,resource:B,applyResult:he(J)&&J.code==="USER_DATA_PERMISSION_SAVE_FAILED"?"save_failed":"error"}),J}}async function Ie(_,B){R(_),M(_);const K=await z(B);if(!K)throw p("UNAUTHORIZED","请先登录小黑盒");return de("revoke",_,async()=>(await y.revokeSession({userId:K,resource:_},B),Q(B)))}function Re(){let _;const B=K=>ee(e.operationContext,async J=>{const Ee=await z(J);if(!Ee)throw p("UNAUTHORIZED","请先登录小黑盒");if(_&&(_.userId!==Ee||_.generation!==s))throw p("AUTHORIZATION_CONTEXT_CHANGED","管理页面所属账号已变化,请重新打开");return _??={userId:Ee,generation:s},K(J)});return{getSnapshot:()=>B(Q),setDecision:K=>B(J=>de("modify",K.resource,()=>se(K.resource,K.decision,K.scope,J,K.expectedRevision,K.expectedFingerprint))),revokeSession:K=>B(J=>Ie(K?.resource,J)),resetAll:()=>B(async K=>{R(),M();const J=await z(K);return de("reset",void 0,async()=>(await y.reset({userId:J},K),Q(K)))})}}return{handlers:{[cc]:async(_,B)=>ee(B,async K=>{if(_!==void 0&&(!he(_)||Object.keys(_).some(me=>me!=="game")||_.game!==void 0&&typeof _.game!="string"))throw p("INVALID_PARAMS","概览参数无效");if(he(_)&&typeof _.game=="string"&&!eu(_.game))throw p("REQUEST_UNSUPPORTED","当前宿主尚未开放该游戏");const J=Object.keys(x()),Ee=he(_)?_.game:void 0;return Pl.filter(me=>Ee===void 0||me===Ee).map(me=>({game:me,name:Ll[me],resources:Fi.filter(De=>De.game===me&&J.includes(De.key)).map(De=>({resource:De.key,name:De.name,status:"not_checked",statusText:"尚未检查"}))})).filter(me=>me.resources.length>0)}),[ts]:async(_,B)=>ee(B,K=>{const J=P(_,"query");return C(ts,J,K,()=>I.query(J,K))}),[kn]:async(_,B)=>ee(B,async K=>{if(!he(_)||Object.keys(_).length!==1||typeof _.game!="string"||!eu(_.game))throw p("INVALID_PARAMS","同步需要指定已开放的游戏");const J={game:_.game};if(!Fi.some(Oe=>Oe.game===J.game&&Oe.sync))throw p("REQUEST_UNSUPPORTED","该游戏不支持存档同步");const Ee=Fi.filter(Oe=>Oe.game===J.game&&Oe.sync&&E(Oe.key));if(Ee.length===0)throw p("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明可同步的资料");let me,De;for(const Oe of Ee){const Pe=await U(Oe.key,K);if(!("status"in Pe)){me=Oe.key;break}(!De||De.reason==="permission_denied")&&(De=Pe)}if(!me)return De;const we={resource:me};return C(kn,we,K,async()=>{const Oe=await z(K),Pe=`${Oe}\0${we.resource}`;let Me=h.get(Pe);if(!Me){const Xe=new AbortController;u.set(Xe,we.resource);const ut={controller:Xe,waiters:0,settled:!1,promise:Promise.resolve(void 0)};ut.promise=I.sync(we,{...e.operationContext,signal:Xe.signal},{userId:Oe,miniProgramId:e.identity.get()?.miniProgramId??""}).finally(()=>{ut.settled=!0,u.delete(Xe),h.get(Pe)===ut&&h.delete(Pe)}),ut.promise.catch(()=>{}),h.set(Pe,ut),Me=ut}Me.waiters++;try{return await be(()=>Me.promise,K.signal)}finally{Me.waiters--,Me.waiters===0&&!Me.settled&&Me.controller.abort()}})}),[rs]:async(_,B)=>ee(B,async K=>{const J=P(_,"file"),Ee=await z(K),me=s,De=b(J.resource),we=async Pe=>{try{const Me=await H(J.resource,Ee,me,De,Pe);if("status"in Me)throw p("FILE_ACCESS_REVOKED","文件授权已撤销",{reason:Me.reason})}catch(Me){throw he(Me)&&["AUTHORIZATION_CONTEXT_CHANGED","USER_DATA_RESOURCE_NOT_DECLARED"].includes(String(Me.code))?p("FILE_ACCESS_REVOKED","文件授权已失效",{causeCode:Me.code}):Me}};let Oe;try{const Pe=await C(rs,J,K,async()=>(Oe=await I.file(J,K,we),{handle:Oe}));if(he(Pe)&&Pe.status==="blocked"){const Je=String(Pe.reason);throw p(Je==="source_not_linked"?"USER_DATA_SOURCE_NOT_LINKED":Je==="source_login_required"?"USER_DATA_SOURCE_LOGIN_REQUIRED":Je==="login_required"?"UNAUTHORIZED":"PERMISSION_DENIED",String(Pe.message),{reason:Je})}const Me=Pe.handle,Xe={...Me,read:async Je=>{await we(Je);const mt=await Me.read(Je);try{return await we(Je),mt}catch(La){throw mt.fill(0),La}},stat:async Je=>{await we(Je);const mt=await Me.stat(Je);return await we(Je),mt}},ut=e.fileRegistry.registerFile(Xe,"download","read");return"handleId"in ut.ref&&l.add(ut.ref.handleId),ut}catch(Pe){throw Oe&&await I.releaseFile(Oe),Pe}}),[uc]:async(_,B)=>{if(!B.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","许可操作需要点击");return ee(B,K=>{if(!he(_)||Object.keys(_).length!==1||typeof _.resource!="string"||!nr(_.resource))throw p("INVALID_PARAMS","许可资源无效");return q(_.resource,K)})},[dc]:async(_,B)=>ee(B,K=>S(Q(K))),[lc]:async(_,B)=>{if(!B.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","修改许可需要点击");if(!he(_)||typeof _.resource!="string"||!nr(_.resource)||_.decision!=="deny"||_.scope!=="persistent"||Object.keys(_).some(K=>!["resource","decision","scope"].includes(K)))throw p("INVALID_PARAMS","允许许可只能由可信弹窗确认");return ee(B,K=>S(se(_.resource,_.decision,"persistent",K)))},[fc]:async(_,B)=>{if(!B.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","管理资料许可需要点击");if(!e.presentation?.openDataPermissions)throw p("REQUEST_UNSUPPORTED","宿主未提供资料管理界面");if(_!==void 0&&(!he(_)||Object.keys(_).some(K=>K!=="resource")||_.resource!==void 0&&(typeof _.resource!="string"||!nr(_.resource))))throw p("INVALID_PARAMS","管理资源无效");return ee(B,async K=>(await e.presentation.openDataPermissions({resource:he(_)?_.resource:void 0,miniProgramName:e.miniProgramPresentation?.name,signal:K.signal}),S(Q(K))))},[hc]:async(_,B)=>{if(!B.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","撤销许可需要点击");if(_!==void 0&&(!he(_)||Object.keys(_).some(K=>K!=="resource")||_.resource!==void 0&&(typeof _.resource!="string"||!nr(_.resource))))throw p("INVALID_PARAMS","撤销资源无效");return ee(B,K=>S(Ie(he(_)?_.resource:void 0,K)))}},promptPcHardwareOnEntry:W,get permissionBridge(){return Re()},diagnostics:{telemetry:w.diagnostics},dispose(){t||(t=!0,L(),Y(),e.operationContext.signal.removeEventListener("abort",j),y.dispose(),w.dispose())}}}function jd(e){throw{code:"INVALID_PARAMS",message:e}}function On(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Gh(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function ki(e,t,r){return Math.min(Gh(e,t),r)}async function hw(e){try{return Gh(await e.getNavigationBarHeight(),0)}catch{return 0}}function mw(e,t,r,n){const i=ki(e.safeArea?.left,0,t),s=Math.max(i,ki(e.safeArea?.right,t,t)),a=ki(e.safeArea?.top,n,r),c=Math.max(a,ki(e.safeArea?.bottom,r,r));return{left:i,right:s,top:a,bottom:c,width:s-i,height:c-a}}async function Vd(e){const t=e.getViewportMetrics(),r=On(t.windowWidth,0),n=On(t.windowHeight,0),i=await hw(e);return{pixelRatio:On(t.pixelRatio,1),screenWidth:On(t.screenWidth,r),screenHeight:On(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:mw(t,r,n,i),screenTop:i}}function Ew(e){const t=new AbortController,r={...e,operationContext:{...e.operationContext,signal:t.signal}};let n=!1,i=0,s,a;const c=()=>{if(n||r.operationContext.signal.aborted||!r.onViewportChange)return;const h=++i;Vd(r.presentation).then(f=>{if(n||r.operationContext.signal.aborted||h!==i)return;const E=JSON.stringify(f);E!==s&&(s=E,r.onViewportChange?.(f))}).catch(()=>{})},u=wy({...r,onApplied:c}),d=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),u.dispose(),a?.())};return e.operationContext.signal.aborted?d():(a=r.presentation.onViewportChange?.(c),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[Mr]:async(h,f)=>u.apply(h,f?.signal),[Es]:async()=>(Ce(r.operationContext.signal),Vd(r.presentation)),[gs]:async h=>{if(Ce(r.operationContext.signal),typeof h!="object"||h===null||Array.isArray(h))return jd("viewport.setNavigationBarStyle 参数必须是对象");const f=h.foregroundStyle;if(f!=="light"&&f!=="dark")return jd("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await be(()=>r.presentation.setNavigationBarStyle(f,e.operationContext),r.operationContext.signal)}},runDisplayRequest:u.runDisplayRequest,applyOrientation:(h,f)=>u.apply({orientation:h.mode,fullscreen:h.hideCapsule},f),notifyChange:()=>{s=void 0,c()},dispose:d}}function gw(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw Le("INVALID_PARAMS","工作区卡片刷新参数必须是对象");const t=e;if(Object.keys(t).some(i=>i!=="gameAppId"&&i!=="cardIds"))throw Le("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 Le("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 Le("INVALID_PARAMS","工作区卡片编号无效");return{...r===void 0?{}:{gameAppId:r},...n===void 0?{}:{cardIds:[...n]}}}function pw(e,t){return{[ns]:async(r,n)=>{const i=ke(t,n.signal,n.requestId);if(Ce(i.signal),!e)throw Le("CAPABILITY_UNAVAILABLE","当前 Host 不支持工作区卡片");const s=gw(r),a=await be(()=>e.requestRefresh(s,i),i.signal);if(!a||typeof a!="object"||Array.isArray(a)||Object.keys(a).some(c=>c!=="scheduled")||!Number.isSafeInteger(a.scheduled)||a.scheduled<0)throw Le("HOST_INVALID_RESPONSE","工作区卡片刷新回执无效");return{scheduled:a.scheduled}}}}const Tw=new Map(dr.map(e=>[e.method,e]));function Ja(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function _w(e){const t=af(e);return r=>t(r.requirement,r.method)}function Aw(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,a)=>{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(()=>a(l)))})}function Iw(e){const t=_w(e.runtimePermissions),r=ot(e.runtimePermissions);let n=0;return{async dispatch(i,s,a){const c=e.now??bw,u=e.onTrace?c():0,d=e.onTrace?Date.now():0,l=e.onTrace?a.requestId??`runtime_${++n}`:"";e.onTrace&&eo(e.onTrace,{callId:l,method:i,startedAt:d,outcome:"started"},()=>u,u);try{if(e.terminalSignal.aborted)throw Ja("RUNTIME_DESTROYED","小程序 Runtime 已终止");Xl(i,e.effectiveCapabilities);const h=Tw.get(i);if(!h)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const f=t(h),E=!f.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,s)===!0,g=!f.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,s)===!0,b=!f.allowed&&r.valid&&r.permissions.user_game_data?.status==="enabled"&&e.allowsUserGameDataFileAccess?.(i,s)===!0;if(!f.allowed&&!E&&!g&&!b)throw Ja(f.code,f.message,f.data);const N=e.handlers[i];if(!N)throw new Error(`Capability method ${i} 缺少 handler`);const y=async x=>{for(const V of e.policies??[]){const M=await V.evaluate({method:i,payload:s,capability:h});if(e.terminalSignal.aborted||x.aborted)throw Yd();if(!M.allowed)throw Ja(M.code,M.message,M.data)}if(e.terminalSignal.aborted||x.aborted)throw Yd()},I=await Aw(async()=>{if(i===Mr){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(s,a.signal,y)}return await y(e.terminalSignal),N(s,a)},void 0,a,e.terminalSignal);return e.onTrace&&eo(e.onTrace,Gd(l,i,s,d,I),c,u),I}catch(h){throw e.onTrace&&eo(e.onTrace,Gd(l,i,s,d,{status:"error",error:h}),c,u),h}}}}function bw(){return typeof performance>"u"?Date.now():performance.now()}function eo(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 Gd(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:yw(i.error)}:{},...Nw(t,r,i)}}function yw(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function Nw(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 a=r.status==="handled"&&Ho(r.value)&&typeof r.value.status=="number"?r.value.status:void 0;return{network:{method:s,origin:n.origin,pathname:n.pathname,...a===void 0?{}:{responseStatus:a}}}}catch{return{}}}function Ho(e){return typeof e=="object"&&e!==null}function Yd(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function ww(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=$p(e.requestPolicy);let n;if(e.files)try{n=Hp(e.files,t)}catch{}const i=gf({store:n}),s=e.onRequestPolicyReport??(r.debugReport?Dw:void 0),a=r.enabled?Yp({...r.gateOptions,...s?{onReport:s}:{}}):void 0,c=new yc(e.files,e.miniProgramDetail),u=Lb({registry:c,picker:e.picker,operationContext:t}),d=AT({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:a,requestPolicyEnabled:r.enabled});let l,h,f,E,g,b,N,y=()=>{},w=()=>{};try{l=Ew({operationContext:t,presentation:e.hostPresentation,onDisplayChange:F=>e.eventSink.postEvent("display_change",F),onViewportChange:F=>e.eventSink.postEvent("viewport_change",F)}),f=zN({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:a,requestPolicyEnabled:r.enabled}),y=d.onEvent((F,U)=>e.eventSink.postEvent(F,U)),w=e.hostCompanion?.onSessionEvent?.(F=>{const U=Db(F);!e.terminalSignal.aborted&&U&&e.eventSink.postEvent(U.type,U.payload)})??(()=>{}),E=t_({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:a,requestPolicyEnabled:r.enabled});const I=e.files&&e.transfer?Dc({files:e.files,transfer:e.transfer,registry:c,signal:t.signal}):void 0,x=fw({...e.verifiedSdkVersion===void 0?{}:{verifiedSdkVersion:e.verifiedSdkVersion},identity:e.identity,account:e.account,storage:e.storage,network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,fileDownloads:I,requestGate:a,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(F,U){e.onUserDataTelemetry?.({name:F,payload:U})}}}}});N=x,g=h_({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:I,requestGate:a,requestPolicyEnabled:r.enabled}),b=hb({presentation:e.hostPresentation,account:e.account,network:e.network,authorization:d,authorizationContext:e.authorizationContext,operationContext:t,requestGate:a,requestPolicyEnabled:r.enabled,onBackgroundError:e.onBackgroundError,emit:F=>e.eventSink.postEvent("post_change",F)});const V=pN({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});h=ty({registry:c,media:e.media,operationContext:t});const M=[{name:"post",handlers:b.handlers},{name:"gameSaves",handlers:Object.fromEntries(Object.entries(g.handlers).map(([F,U])=>[F,async(H,P)=>{const C=e.verifiedSdkVersion,Q=C?Ta(C,"0.10.0-0"):void 0;if(Q===void 0||Q>=0)throw p("REQUEST_UNSUPPORTED","当前 SDK 不支持旧游戏存档入口,请使用 user.games.get(...).saves");return U(H,P)}]))},{name:"auth",handlers:OT({authorization:d})},{name:"user",handlers:{...ZN({user:f,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...Lp({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:mN({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:V.handlers},{name:"network",handlers:vy({network:e.network,transfer:e.transfer,fileRegistry:c,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins,allowDevelopmentHttp:e.allowDevelopmentHttp,networkPolicy:e.networkPolicy,firstParty:e.firstParty})},{name:"workspaceCards",handlers:pw(e.workspaceCards,t)},{name:"files",handlers:u.files},{name:"file",handlers:u.file},{name:"directory",handlers:u.directory},{name:"media",handlers:h.handlers},{name:"ui",handlers:bN({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Cb({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:Dy({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:F=>l.applyOrientation({mode:"portrait",hideCapsule:!1},F)}:{}})},{name:"cloud",handlers:E.handlers},{name:"userGameData",handlers:N.handlers},{name:"companion",handlers:Ib({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:c})}],R=Sw(M);let L=!1;const Y=()=>{L||(L=!0,e.terminalSignal.removeEventListener("abort",Y),l?.dispose(),h?.dispose(),E?.dispose(),g?.dispose(),b?.dispose(),N?.dispose(),y(),w(),f?.dispose(),i.dispose(),d.dispose(),a?.dispose(),c.dispose())};e.terminalSignal.aborted?Y():e.terminalSignal.addEventListener("abort",Y,{once:!0});const j=new Set(["file.readText","file.readBytes","file.stat"]),ee=(F,U)=>j.has(F)&&Ho(U)&&c.isCompanionAttachmentRef(U.target),k=new Set(["file.readText","file.readBytes","file.stat","file.exists"]),z=(F,U)=>k.has(F)&&Ho(U)&&c.isUserDataDownloadRef(U.target);return{get permissionBridge(){return x.permissionBridge},modules:M,setPostVisible:b.setVisible,dismissPostEditor:b.dismissEditor,handlers:R,runDisplayRequest:l.runDisplayRequest,allowsCompanionAttachmentAccess:ee,allowsGameSaveAccess:g.allowsRead,allowsUserGameDataFileAccess:z,gameSaveDiagnostics:g.diagnostics,applyOrientation:l.applyOrientation,notifyViewportChange:l.notifyChange,promptPcHardwareOnEntry:x.promptPcHardwareOnEntry,...V.diagnostics?{storageDiagnostics:V.diagnostics}:{},...e.files?{sandboxDiagnostics:zb({registry:c,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},dispose:Y}}catch(I){throw l?.dispose(),h?.dispose(),E?.dispose(),g?.dispose(),b?.dispose(),N?.dispose(),y(),w(),f?.dispose(),i.dispose(),d.dispose(),a?.dispose(),c.dispose(),I}}function Dw(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Sw(e){const t=new Map(dr.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[s,a]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 a!="function")throw new Error(`Capability method ${c} 缺少 handler`);r.set(c,a)}const n=dr.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==dr.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Ow="heybox-mini-dev:";function Qd(e){try{return Mw(new URL(e))}catch{return!1}}function Mw(e){return e.protocol===Ow}function Cw(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Rw(e)}function Rw(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 Lw=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Pw(e,t){const r=[],n=vw(e.environmentInfo,r),i=$i(n?.appVersion,"host.appVersion",r),s=xw(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:kw(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:$i(t.miniProgramId),version:$i(t.miniProgramVersion)}),operatingSystem:Object.freeze(s)}),invalidFields:Object.freeze(r)}}function vw(e,t){if(e!=null){if(Yh(e))return e;t.push("environmentInfo")}}function kw(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function xw(e,t){if(e==null)return{name:"unknown",version:null};if(!Yh(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=Lw.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:$i(e.version,"operatingSystem.version",t)}}function $i(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Yh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Uw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",Bw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",Hw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",Fw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function zw(e,t,r,n,i="dark"){Ce(n);const s=e.defaultView;if(!s||!e.body)throw new Error("截图水印缺少可用的展示窗口");const a=e.createElement("div"),c=i==="light",u=c?"black":"white";a.dataset.miniProgramScreenshotWatermark="",a.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);a.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:max-content;max-width:${r.width/d-24}px;transform:scale(${d});transform-origin:top left;font-family:"PingFang SC",sans-serif;`;const h=e.createElement("div");h.style.cssText="display:flex;align-items:center;max-width:100%;height:22px;flex-shrink:0;";const f=e.createElement("img");f.src=c?Hw:Uw,f.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const E=e.createElement("div");E.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?Fw:Bw,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;`,E.append(g,b),h.append(f,E),l.append(h,N),a.append(l),e.body.append(a);const y=()=>{a.remove(),n.removeEventListener("abort",y)};n.addEventListener("abort",y,{once:!0});try{await be(()=>Promise.all([f.decode(),g.decode()]),n);const w=l.getBoundingClientRect();return a.style.left=`${r.left+s.scrollX+(r.width-w.width)/2}px`,a.style.width=`${w.width}px`,a.style.height=`${w.height}px`,l.style.width=`${w.width/d}px`,l.style.height=`${w.height/d}px`,l.style.maxWidth="none",await be(()=>new Promise(I=>{let x=s.requestAnimationFrame(()=>{x=s.requestAnimationFrame(()=>{n.removeEventListener("abort",V),I()})});const V=()=>s.cancelAnimationFrame(x);n.addEventListener("abort",V,{once:!0})}),n),y}catch(w){throw y(),w}}const jw=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"]),Vw=new Set(["url","inline","eval","unknown"]),Gw=/^\/(?:\:segment(?:\/\:segment)*)?$/,Yw=/^[a-f0-9]{64}$/,Qw=255,qw=160,Ww=256;function $w(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!jw.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>Ww||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Vw.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=Kw(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>qw||!Gw.test(i)))return;const s=r.sanitizedPathnameHash;if(!(s!==void 0&&(typeof s!="string"||!Yw.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 Kw(e){if(e!==void 0&&!(typeof e!="string"||e.length>Qw))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Ma=["android","ios","ohos","windows","macos","linux"],Zw="0.9.0",Xw=Object.freeze(["android","ios","ohos","windows","macos"]),Qh="该小程序暂不支持当前平台",Jw="PLATFORM_UNSUPPORTED";function eD(e){return typeof e=="string"&&Ma.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 rD(e){const t=e.manifest;if(!oD(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Wd(e.sdkVersion)??Wd(t.sdkVersion);return sD(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:iD()}const r=qh(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function nD(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:Ma,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const a=rD({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return a.status==="invalid"?qr("platform_declaration_invalid",{invalidReason:a.reason,platform:t}):qd(t,a)}if(r.effectivePlatforms===void 0)return qr("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=qh(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=aD(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return qd(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:s})}function qd(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:Qh,...t}}function iD(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:Xw,platformsDeclared:!1,policy:"legacy_mobile_default"}}function qh(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(!eD(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Ma.filter(r=>t.has(r)))}}function sD(e){if(typeof e!="string"||!e.trim())return!1;const t=Ta(e.trim(),Zw);return t!==void 0&&t>=0}function Wd(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function aD(e){return e==="explicit"||e==="legacy_mobile_default"}function oD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cD(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:uD(i.pathname),sanitizedPathnameHash:Tc(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function uD(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}const dD=1e4,lD=3e4,fD=1e4,to=2e3,hD=2,mD="open-with-native-credential-policy",Wh="安全提示",$h="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class ED{nonce=gu();runtimeId=gu();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;awaitingDevelopmentDocumentLoad=!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;allowDevelopmentHttp=!1;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=ef(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??dD,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.awaitingDevelopmentDocumentLoad&&(this.awaitingDevelopmentDocumentLoad=!1,this.stateValue==="starting"&&this.armHandshakeTimeout()),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??Le("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??Le("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(SD(),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??Le("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.capabilityGraph?.promptPcHardwareOnEntry(),!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=jg(t.runtimePermissions),this.firstParty=t.firstParty===!0,this.networkPolicy=this.firstParty?void 0:tf(t.networkPolicy),this.networkPolicy?.enforcement==="restricted"){const a=t.canonicalIdentity?.miniProgramId?.trim();if(!a||!this.options.networkPolicyEnforcement)throw{code:"NETWORK_POLICY_UNSUPPORTED",message:"当前 Host 尚未具备严格网络策略执行能力,请更新 Host 后重新打开"};const c=await Ng(this.options.networkPolicyEnforcement,{policy:this.networkPolicy,miniProgramId:a,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=Cp(t.sdkVersionPolicy),this.allowDevelopmentHttp=t.sdkVersionPolicy?.releaseChannel==="development";const n=Pw(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=nD({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw CD(this.platformGateDecision);if(this.miniProgramDetail=RD(t),this.effectiveCapabilities=Jl(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(ND(i)),this.launchUrl=i,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const a=rf(new URL(i),this.locationBasePath);this.devDocumentDisposer=zg({iframe:this.iframe,launchUrl:i,nonce:this.nonce,locationBasePath:a,onLeaving:()=>{this.prepareForHistoryTraversal()},onResume:()=>{!this.isInactive()&&this.documentRevalidationPending&&this.beginDocumentRevalidation()},onReload:c=>{this.isInactive()||Ot(u=>this.options.onDevDocumentReload?.(u,a),c)}})}if(this.miniProgramSrc=Pg(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(a){if(this.isInactive())return;const c=Hs(a);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:Mr,errorCode:c.code,message:`默认展示设置失败,沿用宿主当前布局:${c.message}`})}if(this.isInactive())return}this.awaitingDevelopmentDocumentLoad=t.sdkVersionPolicy?.releaseChannel==="development",this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ot(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout(this.awaitingDevelopmentDocumentLoad)}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&(n!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(n!=="display_change"||this.effectiveCapabilities[Mr])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=ww({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)=>yg(this.iframe,n,i),prepareScreenshot:(n,i,s)=>{const a=this.sdkVersionDecision?.sdkVersion;return!a||(Ta(a,"0.9.1")??-1)<0?Promise.resolve(()=>{}):zw(this.iframe.ownerDocument,this.miniProgramPresentation?.name,n,i,s)},miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins,allowDevelopmentHttp:this.allowDevelopmentHttp,requestPolicy:this.options.requestPolicy,onBackgroundError:(n,i)=>{const s=Hs(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=Iw({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:a,durationMs:c,outcome:u,errorCode:d,network:l})=>{const h={type:"capability",phase:"host",runtimeId:this.runtimeId,callId:n,method:i,startedAt:s,timestamp:a,durationMs:c,outcome:u,...d?{errorCode:d}:{},...this.identity,...l?{network:l}:{}};Ot(this.options.onCapabilityTrace,h)}}:{}});this.bridgeServer=new qg({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,...this.options.onDevUploadSession?{onDevUploadSession:n=>{this.isInactive()||Ot(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(Le("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 ID(t)?t:Kh(Le("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 Lg(t,r,{allowPrivateNetwork:Qd(r)||$d(r)||await this.isDevRuntime()})}catch(r){throw Le("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??DD)({message:$h,title:Wh,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Tu(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!Qd(r)&&!$d(r)}async closeAfterDevLaunchCancellation(){const t=Le("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{Kd(),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(()=>Kd())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Og),this.iframe.setAttribute("referrerpolicy",Mg),this.iframe.setAttribute("sandbox",nf)}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.hostVisible&&this.capabilityGraph?.promptPcHardwareOnEntry(),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),Ot(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(),Ot(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Rp(r,t?.sdkVersion)}catch(n){return this.failRuntime(n),!1}return!0}armHandshakeTimeout(t=!1){this.clearHandshakeTimeout(),!(this.handshakeTimeout<=0)&&(this.handshakeTimeoutTimer=setTimeout(()=>{if(!(this.stateValue==="ready"||this.isInactive())){if(t){this.onIframeError(new Error("开发页面加载超时,请检查 Vite 服务、入口脚本和网络连接"));return}this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"handshake_timeout"}),this.failRuntime(Le("SDK_HANDSHAKE_TIMEOUT","小程序 SDK 握手超时"))}},t?lD: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>=hD)){this.failRuntime(Le("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(yi,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},to),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:yi})}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(yi,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:yi})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&this.failRuntime(Le("DOCUMENT_REVALIDATION_TIMEOUT",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时"))},r.waitingForDocument?fD:to))}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()},to)),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===d0){this.handleCspViolation(t.payload);return}if(t.method!==u0)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(Le("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!sf(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(Le("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=$w(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){Ot(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=cD(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(Le("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:Sg,launchUrlType:Tu(t),networkPolicy:mD})}failRuntime(t){const r=gD(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}),Ot(this.options.onError,pD(r)),Ot(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,Ot(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ot(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 gD(e){const t=Hs(e);return Xs(e)&&"cause"in e&&Kh(t,e.cause),t}function Kh(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:AD(e.cause)}:{}}}const ro=(()=>{const e=Object.getOwnPropertyDescriptor(new Error,"stack")?.get,t=Object.getOwnPropertyDescriptor(new Error,"stack")?.get;return typeof e=="function"&&e===t?e:void 0})(),TD=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function _D(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return;if("value"in r)return r.value;if(t!=="stack"||!ro||r.get!==ro)return;const n=Object.getPrototypeOf(e);if(TD.has(n)){for(const i of["name","message"]){const s=Object.getOwnPropertyDescriptor(e,i),a=Object.getOwnPropertyDescriptor(n,i)??Object.getOwnPropertyDescriptor(Error.prototype,i);if(s&&!("value"in s)||a&&!("value"in a))return}return ro.call(e)}}function AD(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=_D(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 ID(e){return Xs(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Xs(e){return!!e&&typeof e=="object"}function Ot(e,t){try{e?.(t)}catch{}}function bD(e,t,r){try{e?.(t,r)}catch{}}function $d(e){try{const t=new URL(e);return t.protocol==="http:"&&Cw(t.hostname)}catch{return!1}}function yD(e){try{return new URL(e).origin}catch{return}}function ND(e){return Cg()?"*":yD(e)}function wD(e){return`${Wh}
9
-
10
- ${$h}
11
-
12
- URL: ${e}`}function DD(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(wD(e.url))}function Kd(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function SD(){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:yl,knownMethodCount:dr.length,supportsFileCreate:dr.some(i=>i.method===Xn),system:OD(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:MD(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function OD(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 MD(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function CD(e){return Le(Jw,Qh,{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 RD(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 LD(e){if(!Xs(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!Xs(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 ED(e)}function PD(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 a=await new Promise((c,u)=>{const d=i.open("heybox-mini-program-private-account-v1",1);let l=!1;const h=()=>n.signal.removeEventListener("abort",E),f=g=>{l||(l=!0,h(),u(g))},E=()=>f(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{l?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>f(d.error),d.onblocked=()=>f(new Error("账号存储被阻塞")),d.onsuccess=()=>{l?d.result.close():(l=!0,h(),c(d.result))},n.signal.addEventListener("abort",E,{once:!0}),n.signal.aborted&&E()});try{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");return await new Promise((c,u)=>{const d=a.transaction("accounts","readwrite"),l=d.objectStore("accounts"),h=JSON.stringify([t,r]);let f;const E=()=>{try{d.abort()}catch{}g(),u(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",E,{once:!0});const g=()=>n.signal.removeEventListener("abort",E);d.oncomplete=()=>{g(),c(f)},d.onabort=d.onerror=()=>{g(),u(d.error??new Error("账号存储事务失败"))};const b=l.get(h);b.onsuccess=()=>{try{if(typeof b.result=="string"&&/^ak_[0-9a-f]{64}$/.test(b.result))f=b.result;else{const N=s.getRandomValues(new Uint8Array(32));f=`ak_${Array.from(N,y=>y.toString(16).padStart(2,"0")).join("")}`,l.put(f,h)}}catch{d.abort()}}})}finally{a.close()}}}const vD=/^(?: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,kD=new Set(["origin","referer","user-agent"]);function xD(e,t){return eg({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const s={...n,signal:i},a=UD(r),c=await e.authenticatedRequest(a,s);return FD(c)})}).network}function UD(e){const t=BD(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function BD(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!HD(t)))}function HD(e){const t=e.trim().toLowerCase();return kD.has(t)}function FD(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:zD(e.headers)??{}}}function zD(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!jD(t)))}function jD(e){const t=e.trim().toLowerCase();return vD.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function VD(e,t,r){const n=WD(e.presentation,t);return{account:QD(e,t,r),network:xD(e,t),...e.storage===void 0?{}:{storage:qD(e,t)},...e.storage===void 0?{}:GD(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function GD(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 a=r.storage.key(s);if(a===null)continue;const c=r.storage.getItem(a);c!==null&&i.push({area:r.area,key:a,value:c})}return i})}}}function YD(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 QD(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??PD();return{getAccountKey:(i,s,a)=>t.run(a.signal,c=>n(i,s,{...a,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(a=>{t.signal.aborted||i(a)});return r(s)}}}function qD(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 WD(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 a=()=>{s||(s=!0,t.signal.removeEventListener("abort",a),i())};return t.signal.addEventListener("abort",a,{once:!0}),a}),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)=>fg(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 $D(){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 xi(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 xi(i.reason);const s=new AbortController;let a;const c=new Promise((l,h)=>{a=h}),u=n.map(l=>{const h=()=>{s.signal.aborted||s.abort(l.reason),a(xi(l.reason))};return l.addEventListener("abort",h,{once:!0}),{listener:h,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]),h=n.find(f=>f.aborted);if(h)throw xi(h.reason);return l}finally{for(const{listener:l,source:h}of u)h.removeEventListener("abort",l)}}}}function xi(e){return new DOMException("Web Host operation aborted","AbortError")}async function KD(e){const t=$D(),r=new Set;let n=!1;const i=f=>{if(n||t.signal.aborted)return no(f),()=>{};let E=!0;const g=()=>{E&&(E=!1,r.delete(g),no(f))};return r.add(g),g},s=()=>a(e.signal.reason),a=f=>{if(!n){n=!0,e.signal.removeEventListener("abort",s),t.abort(f);for(const E of[...r])E();e.onDispose&&no(e.onDispose)}};e.signal.addEventListener("abort",s,{once:!0}),e.signal.aborted&&a(e.signal.reason);const c=VD(e,t,i);c.storage?.getRaw&&c.storage.setRaw&&(c.scopedStorage=vh({storage:c.storage,diagnostics:c.storageDiagnostics,coordinationKey:e.storage.storage,lock:kh,resolveScope:async()=>Ph((await h()).configuration)}));const u=ef(c,{hostCapabilities:e.hostCapabilities,hasUserDataPresentation:e.userDataPresentation!==void 0,hasUserDataSettings:e.userDataPresentation?.openDataPermissions!==void 0}),d=YD(e,t);let l;const h=()=>l??=t.run(void 0,f=>e.resolveLaunch(f));return{platform:"web",ports:c,environment:d,resolveLaunch:h,...e.authPresentation===void 0?{}:{authPresentation:ZD(e.authPresentation,t)},...e.userDataPresentation===void 0?{}:{userDataPresentation:XD(e.userDataPresentation,t)},hostCapabilities:u.effectiveCapabilities,dispose:a}}function no(e){try{e()}catch{}}function ZD(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 XD(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 JD(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 a;const c=new Promise(u=>{a=u});return e.signal.addEventListener("abort",a,{once:!0}),e.signal.aborted&&a(),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,h]of u)h.kind!=="directory"||!/^hb-game-saves-[a-f0-9-]{36}$/.test(l)||await e.locks.request(r(l),{ifAvailable:!0},async f=>{f&&await Zd(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",a),u&&await Zd(u,t).catch(()=>{})}}).catch(i),s.catch(()=>{}),s}async function Zd(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 io=8*1024*1024,e1=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),t1="/__hb_sdk__/game-save-download",st=(e,t)=>({code:e,message:t});function r1(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=JD({getRoot:t,locks:r,signal:e.signal}),s=new WeakMap,a=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 st("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"?st("FILE_NOT_FOUND","存档缓存不存在"):y}}function h(g){const b={kind:"file",mode:"readwrite",name:g.split("/").at(-1),async create(N,y){c(y);const w=d(g),I=await u();if(N.exclusive)try{throw await I.getFileHandle(w),st("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(x){if(!(x instanceof DOMException&&x.name==="NotFoundError"))throw x}c(y),await I.getFileHandle(w,{create:!0}),c(y)},async remove(N){c(N);const y=d(g);if(i)try{await(await i).removeEntry(y)}catch(w){if(!(w instanceof DOMException&&w.name==="NotFoundError"))throw w}},async read(N){const y=await(await l(g,N)).getFile();if(y.size>io)throw st("FILE_TOO_LARGE","存档文件超过 8 MiB");const w=new Uint8Array(await y.arrayBuffer());try{return c(N),w}catch(I){throw w.fill(0),I}},async write(){throw st("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 f=async()=>{throw st("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},E={kind:"directory",mode:"readwrite",name:"",file:h,directory(g){return{...E,name:g,async create(b,N){if(c(N),g!==".hb-game-saves")return f();await u(),c(N)}}},create:f,stat:f,list:f};return{files:{sandbox:E},transfer:{network:{async open(g,b){if(c(b),!$l(g))throw st("METHOD_FORBIDDEN","仅支持受控存档下载");const N=await(e.fetch??fetch)(t1,{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 st(y.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return a.add(N),{status:N.status,headers:Object.fromEntries(Array.from(N.headers).filter(([y])=>e1.has(y)).map(([y,w])=>[y,[w]])),body:N}},async release(g){a.delete(g),await g.body?.cancel()}},files:{async writeResource(g,b,N,y){let w,I;try{c(y);const x=s.get(g);if(!x||!a.delete(b))throw st("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(N.mode!=="replace-existing")throw st("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(w=await(await l(x,y)).createWritable(),!b.body)throw st("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");I=b.body.getReader();let M=0;for(;;){c(y);const R=await I.read().catch(L=>{throw c(y),st(L instanceof DOMException&&L.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(c(y),R.done)break;if(M+=R.value.byteLength,M>Math.min(N.maxBytes??io,io))throw st("FILE_TOO_LARGE","存档文件超过 8 MiB");await w.write(new Uint8Array(R.value)),y.onProgress(M)}if(N.expectedBytes!==void 0&&M!==N.expectedBytes)throw st("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return c(y),await w.close(),w=void 0,{committedBytes:M}}catch(x){throw x instanceof DOMException&&x.name==="QuotaExceededError"?st("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):x}finally{await I?.cancel().catch(()=>{}),I||await b.body?.cancel().catch(()=>{}),await w?.abort().catch(()=>{}),a.delete(b)}}}}}}function Bt(e,t){throw{code:e,message:t}}function Mn(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 n1(e){return{declaredPermissions:e.declaredPermissions??{},platforms:[...e.platforms??[]].sort(),runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy}}function i1(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 u=e.readState();u.userId||(i(),Bt("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:d,browser:l}=u,h=wE(d.developmentSnapshot);(d.source!=="remote"||!d.miniProgramId||!d.localDevLaunchToken||!d.expiresAt||d.expiresAt<=t()||!h||!d.developmentSnapshotDigest||!/^[a-f0-9]{64}$/.test(d.developmentSnapshotDigest))&&(i(),Bt("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态"));let f;try{f=ql({...h,declared_permissions:l.declaredPermissions??{},platforms:l.platforms??[]})}catch{}(l.source!=="remote"||l.miniProgramId!==d.miniProgramId||l.devSessionId!==h.session_id||d.devSessionId!==h.session_id||d.contextRevision!==h.revision||f!==d.developmentSnapshot||Mn(l.runtimePermissions)!==Mn(d.runtimePermissions)||Mn(l.networkPolicy)!==Mn(d.networkPolicy))&&(i(),Bt("AUTHORIZATION_CONTEXT_CHANGED","开发快照正在更新,请稍后重试"));const E={mini_program_id:d.miniProgramId,launch_kind:"remote-dev",version_identity:`dev:${h.session_id}:${h.revision}`,sdk_version:h.sdk_version,local_dev_launch_token:d.localDevLaunchToken,dev_snapshot_digest:d.developmentSnapshotDigest,dev_network_enabled:u.networkEnabled};return{body:E,key:Mn([u.userId,u.accountRevision,E,l.contextRevision,n1(l)]),expiresAt:d.expiresAt}}async function a(u,d){const l=d.signal;let h;try{h=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:u.body,timeout:1e4},d)}catch(N){l.throwIfAborted();const y=N&&typeof N=="object"&&"code"in N?String(N.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(y)&&Bt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(y)||N instanceof DOMException&&["AbortError","TimeoutError"].includes(N.name))throw N;Bt("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}l.throwIfAborted(),await e.refreshAccount(l),l.throwIfAborted(),s().key!==u.key&&Bt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const f=h.data;(h.status===401||f?.status==="login"||f?.status==="relogin")&&Bt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(h.status!==200||f?.status!=="ok")&&Bt("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const E=f.result,g=Number(E?.expires_at)*1e3;(typeof E?.token!="string"||!E.token.trim()||!Number.isSafeInteger(E?.expires_at)||!Number.isSafeInteger(g)||g<=t()||!["legacy","local","server"].includes(String(E.user_data_mode)))&&Bt("INVALID_RESPONSE","开发运行授权响应无效");const b={token:E.token,expiresAt:Math.min(g,u.expiresAt),steamAccount:E.steam_account===!0,userDataMode:E.user_data_mode};return r={key:u.key,value:b},b}const c={async get(u){const d=AbortSignal.any([u.signal,e.signal]);d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted();const l=s();if(r?.key===l.key&&r.value.expiresAt>t()+3e4)return r.value;i();let h=n.get(l.key);if(!h||h.controller.signal.aborted){const E=new AbortController,g=a(l,{...u,signal:AbortSignal.any([E.signal,e.signal])});h={promise:g,controller:E,users:0},n.set(l.key,h);const b=h;g.finally(()=>{n.get(l.key)===b&&n.delete(l.key)}).catch(()=>{})}h.users++;let f;try{const E=await Promise.race([h.promise,new Promise((g,b)=>{f=()=>b(d.reason),d.addEventListener("abort",f,{once:!0}),d.aborted&&f()})]);return d.throwIfAborted(),s().key!==l.key&&Bt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),E}finally{d.removeEventListener("abort",f),--h.users===0&&h.controller.abort()}}};return{...c,async resolveLaunchConfiguration(u,d){const l=AbortSignal.any([d.signal,e.signal]);l.throwIfAborted(),await e.refreshAccount(l),l.throwIfAborted();const h=e.readState();if(!u.canonicalIdentity?.miniProgramId||!h.userId||!h.signed.localDevLaunchToken)return u;const f=await c.get({...d,signal:l});return{...u,runtimeFeatures:{steamAccount:f.steamAccount,userDataMode:f.userDataMode}}}}}function Xd(e,t){return ui(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:ui(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 Vn(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=xl(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:k0({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 s1(e){if(!ui(e)||!Jd(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!ui(t)||!Jd(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const a1={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Bc(e){const t=ot(e.localDevGrant?pc({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}}:o1()}function Zh(e,t,r){return r?.localDevGrant?pc({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:c1(e,t,t.networkRequest.useOfficialDomain)}function o1(){return{networkRequest:{...a1.networkRequest}}}function c1(e,t,r){const n=ot(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const a of Lr){const c=n.permissions[a];c&&i.push(a==="network"?{key:a,status:t.networkRequest.status,config:{useOfficialDomain:r}}:a==="user_game_data"||a==="post"?{key:a,status:c.status,config:{...c.config}}:{key:a,status:c.status,config:{}})}const s=ui(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 ui(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Jd(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function u1(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(h){c={ok:!1},!n&&!u.signal.aborted&&a(h);continue}finally{t===u&&(t=void 0)}if(n)return{ok:!1};let l;try{l=e.apply(d)}catch(h){c={ok:!1},n||a(h);continue}if(n)return{ok:!1};if(c={ok:!0},!!e.hasChanged(l))try{await e.onChanged(l)}catch(h){c={ok:!1},n||a(h)}}return n?{ok:!1}:c}function a(c){try{e.onError(c)}catch{}}}function d1(e){return u1({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 l1(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,s;return{schedule:a,reset(){n=t,c()},dispose(){i||(i=!0,c())}};function a(){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),a()}},n))}function c(){s!==void 0&&e.timers.clearTimeout(s),s=void 0}}const so=new WeakMap;function Hc(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}const{root:n,signal:i}=e;so.set(n,document.activeElement);const s=[...n.querySelectorAll("button[data-action]")];n.dataset.hostDialog="true",n.style.zIndex="40";const a=()=>[...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",f);const g=a()===n;if(n.remove(),g){const b=a();b&&(b.inert=!1,b.removeAttribute("aria-hidden"));let N=so.get(n)??null;for(;N instanceof HTMLElement&&!N.isConnected;){const y=N.closest("[data-host-dialog]");N=y?so.get(y)??null:null}N instanceof HTMLElement&&(!b||b.contains(N))?N.focus():b?.querySelector("button")?.focus()}},d=Om({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 h(g){c=g,d.finish(g===e.cancelAction?"cancelled":"confirmed")}function f(g){if(a()!==n||(g.key==="Escape"&&e.cancelAction&&(g.preventDefault(),h(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",()=>h(g.dataset.action));n.addEventListener("click",g=>{g.target===n&&e.cancelAction&&h(e.cancelAction)}),n.dataset.interactionId=d.interactionId;const E=a();E&&(E.inert=!0,E.setAttribute("aria-hidden","true")),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n),i?.addEventListener("abort",l,{once:!0}),document.addEventListener("keydown",f),s[0]?.focus(),i?.aborted?l():e.onShown?.()})}function At(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}const el="hb-sdk-action-dialog-style";async function Ca(e){await Xh(e)}async function f1(e){return await Xh({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function Xh(e){p1();const t=document.createElement("div");return t.className="hb-sdk-action-dialog",t.innerHTML=`
13
- <div class="hb-sdk-action-dialog__panel">
14
- <h2>${At(e.title)}</h2>
15
- <pre class="hb-sdk-action-dialog__detail">${At(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 Hc({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 h1(e,t){await Ca({method:"navigation.openAppPage",title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+cn(e.params)].join(`
21
- `),signal:t.signal,callId:t.requestId})}async function m1(e,t){await Ca({method:"navigation.openAppPage",title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+cn(e.extra)].join(`
22
- `),signal:t.signal,callId:t.requestId})}async function E1(e,t){await Ca({method:"share.showShareMenu",title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+cn(e.channel),"post: "+cn(e.post)].join(`
23
- `),signal:t.signal,callId:t.requestId})}async function g1(e,t){await Ca({method:"share.screenshot",title:"截图分享",detail:["rect: "+cn(e.rect),"post: "+cn(e.post)].join(`
24
- `),signal:t.signal,callId:t.requestId})}function cn(e){return JSON.stringify(e,null,2)}function p1(){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 T1={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};async function _1(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">${At(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
84
- <ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(n=>`<li>${At(T1[n]||n)}</li>`).join("")}</ul>
85
- ${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${At(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 Hc({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function A1(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:Qc,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,firstParty:e.firstParty===!0,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:Ma},sdkVersion:Qc},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const tl="hb-sdk-user-data-dialog-style",I1=new Map(Ea.map(e=>[e.key,e.name]));function b1(e){return(nr(e)?I1.get(e):void 0)??"游戏资料"}function y1(e){return e==="upload"?"可上传":"无网络权限"}async function N1(e){D1();const t=e.miniProgramName?.trim()||"当前小程序",r=b1(e.resource),n=`“${t}”想读取你的${r}`,i=y1(e.egress),s=YE[e.egress],a=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>${At(n)}</h2>
94
- <dl class="hb-sdk-user-data-dialog__meta">
95
- <dt>范围</dt><dd>${At(e.scopeText)}</dd>
96
- <dt>用途</dt><dd>${At(e.purposeText)}</dd>
97
- </dl>
98
- <p class="hb-sdk-user-data-dialog__egress" data-egress="${At(e.egress)}">
99
- <span class="hb-sdk-user-data-dialog__egress-label" aria-hidden="true">${At(a)}</span>
100
- <span class="hb-sdk-user-data-dialog__egress-tag">${At(i)}</span>
101
- <span>${At(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 Hc({root:c,title:n,method:"user.dataPermission.confirm",mode:"browser",signal:e.signal,...e.onShown?{onShown:e.onShown}:{},cancelAction:"cancelled"});return{decision:w1(u)}}function w1(e){return e==="deny"||e==="session"||e==="persistent"?e:"cancelled"}function D1(){if(document.getElementById(tl))return;const e=document.createElement("style");e.id=tl,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 S1(e){let t,r,n,i,s,a=0,c=0,u=0,d=!1,l=Promise.resolve();const h=new Set,f=()=>{const y=e.resolveScope();return y?JSON.stringify(y):void 0},E=()=>{if(!d)for(const y of h)y()},g=async()=>{if(d||u)return;const y=t,w=f(),I=++a;if(!y||!w){r=void 0,i=void 0,E();return}try{const x=await y.getSnapshot();if(d||I!==a||t!==y||w!==f())return;r=x,n=w,i=void 0}catch(x){if(d||I!==a||t!==y||w!==f())return;r=void 0,s=w,i=x instanceof Error?x.message:"许可状态不可用"}E()},b=y=>{const w=t,I=f(),x=c;if(d||!w||!I)return Promise.resolve();const V=++a;u++;const M=l.then(async()=>{if(!(d||c!==x||I!==f()))try{const R=await y(w);if(d||V!==a||c!==x||I!==f())return;r=R,n=I,i=void 0}catch(R){if(d||V!==a||c!==x||I!==f())return;r=void 0,s=I,i=R instanceof Error?R.message:"许可设置失败"}}).finally(()=>{c===x&&u--,E()});return l=M,M},N=()=>{c++,a++,u=0,l=Promise.resolve(),t=void 0,r=void 0,i=void 0};return{snapshot(){const y=f(),w=y&&y===n?r:void 0,I=e.declared?.();return{scenario:"unknown",dataScenario:"unknown",egressTier:e.egressTier(),declaredSource:I?.source??"manifest",permissionStateReady:w!==void 0,stateError:y&&y===s?i:void 0,simulatedSession:[],resources:Ea.map(x=>{const V=w?.resources.find(R=>R.resource===x.key),M=V?.allowed===!0;return{resource:x.key,name:x.name,declared:I?.resources.includes(x.key)??!1,decision:V?.decision??"ask",revision:V?.revision??0,sessionAllowed:V?.sessionAllowed??!1,sessionSimulated:!1,licensed:M,...M?{sourceStatus:"unknown"}:{}}})}},subscribe(y){return d||h.add(y),()=>h.delete(y)},bind(y){d||(N(),t=y,g())},refresh:g,revokeSession:()=>b(y=>y.revokeSession()),resetAll:()=>b(y=>y.resetAll()),clearSession(){N(),E()},dispose(){d=!0,N(),h.clear()}}}function O1(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 M1(e){const t=ot(e.runtimePermissions);let r={};return t.valid&&t.permissions.user_game_data?.status==="enabled"?r=si(t.permissions.user_game_data.config.resources):e.runtimePermissions===void 0&&e.declaredPermissions?.user_game_data?.enabled&&(r=si(e.declaredPermissions.user_game_data.resources)),{resources:L0(r),source:"manifest"}}const C1=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"]}),R1="host.userDataTelemetry",rl=80;function L1(e){return{method:R1,detail:{...e.payload,eventName:e.name,message:P1(e)}}}function P1(e){const t=C1[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}: ${Jh(i)}`)}return[e.name,...r].join(" · ")}function Jh(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=>Jh(r)).join(",");else try{t=JSON.stringify(e)??""}catch{t="[无法序列化]"}return t.length>rl?`${t.slice(0,rl)}…`:t}const v1=44;function k1(e){const t=()=>e.isCapsuleHidden?.()?0:v1,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:Pm,showLoading:Lm,hideLoading:Rm,vibrate:Cm,openAppPage:h1,openWindow:m1,showShareMenu:E1,captureAndShare:g1,setScreenshotChromeHidden:Mm}}const nl=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],Ui=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],il={"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 x1{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]:[...nl];for(const n of r){const i=this.preparations.get(n);for(const s of i?.operation?.timers??[])this.clearSchedule(s);i?.operation?.reject(et("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:il[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:Ui[0]),i.operation.promise;let s,a;const c=new Promise((d,l)=>{s=d,a=l}),u={cancelled:!1,listeners:new Set([r.onProgress]),promise:c,reject:a,resolve:s,timers:new Set};{const d={status:{state:"preparing",progress:Ui[0]},operation:u};this.preparations.set(n,d),this.diagnostic("prepare.started",n),Ui.forEach((l,h)=>{const f=this.schedule(()=>{if(u.timers.delete(f),!u.cancelled){d.status={state:"preparing",progress:l};try{u.listeners.forEach(E=>E(l))}catch(E){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:E instanceof Error?E.message:String(E)}),u.reject(E);return}if(this.diagnostic("prepare.progress",n,{phase:l.phase}),h===Ui.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(et("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)}}},h+1);u.timers.add(f)})}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(et("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(h0,{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 et("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw et("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw et("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:il[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 et("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw et("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 et("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw et("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 et("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw et("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 et("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(l0,{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(f0,{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 et("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw et("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!nl.includes(t))throw et("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 U1=Object.freeze({[na]:!0,[ia]:!0,[sa]:!0,[aa]:!0,[oa]:!0,[ca]:!0,[ua]:!0,[da]:!0,[la]:!0,[fa]:!0,[ha]:!0,[ma]:!0,[ti]:!0,[ei]:!0,[ri]:!0});function B1(e){return new x1(e)}function et(e,t){return Object.assign(new Error(t),{code:e})}function H1(e={}){const t=e.source??Y1(e.document??document),r=e.readMetadata??Q1,n=e.createPreviewUrl??(d=>URL.createObjectURL(d)),i=e.revokePreviewUrl??(d=>URL.revokeObjectURL(d)),s=new WeakMap,a=new Set,c=d=>{if(!(!d||!a.has(d))){a.delete(d);try{i(d)}catch{}}},u=()=>{for(const d of[...a])c(d)};return e.signal?.addEventListener("abort",u,{once:!0}),{async pick(d,l){switch(vn(l.signal),e.getMode?.()??"normal"){case"cancel":throw je("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");case"system-permission-denied":throw je("MEDIA_SYSTEM_PERMISSION_DENIED","系统未授予相机或相册权限");case"prepare-failure":throw je("MEDIA_PREPARE_FAILED","媒体准备失败,未保留部分结果");case"preview-unavailable":throw je("MEDIA_PREVIEW_UNAVAILABLE","当前 Host 无法提供受控媒体预览")}const h=d.source==="camera"?[await t.capture({mediaType:d.mediaType})]:await F1(t,d);if(vn(l.signal),d.source==="camera"&&h.length!==1)throw je("MEDIA_PREPARE_FAILED","相机模拟必须恰好返回 1 项");const f=[];try{for(const E of h)vn(l.signal),f.push(await j1(E,d,l.signal,r,n,s,a));vn(l.signal)}catch(E){for(const g of f)c(s.get(g.file));throw E}return f},release(d){for(const l of d)c(s.get(l.file))}}}async function F1(e,t){const r=await e.pickAlbum({accept:z1(t.mediaType),maxCount:t.maxCount,multiple:t.maxCount>1});if(!r||r.length===0)throw je("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");if(r.length>t.maxCount)throw je("MEDIA_PREPARE_FAILED",`本次选择 ${r.length} 项,超过 maxCount ${t.maxCount}`);return r}function z1(e){switch(e){case"image":return"image/*";case"video":return"video/*";default:return"image/*,video/*"}}async function j1(e,t,r,n,i,s,a){const c=V1(e.type);if(!c)throw je("MEDIA_PREPARE_FAILED",`浏览器未提供可识别的媒体类型: ${e.name}`);if(t.mediaType!=="all"&&t.mediaType!==c)throw je("MEDIA_PREPARE_FAILED",`所选媒体 ${e.name} 与 mediaType 不匹配`);const u=await n(e);vn(r);const d=sl(u.width),l=sl(u.height);if(d===void 0||l===void 0)throw je("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的显示尺寸`);if(c==="video"){if(al(u.durationMs)===void 0)throw je("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的视频时长`)}else if(u.durationMs!==void 0)throw je("MEDIA_PREPARE_FAILED",`图片 ${e.name} 不应携带视频时长`);const h=i(e);if(!h)throw je("MEDIA_PREVIEW_UNAVAILABLE","无法提供受控媒体预览");const f=G1(e);s.set(f,h),a.add(h);const E={type:c,mimeType:e.type,size:e.size,width:d,height:l,previewUrl:h,file:f};return c==="video"?{...E,durationMs:al(u.durationMs)}:E}function V1(e){if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video"}function G1(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 Y1(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()},a=d=>{i||(i=!0,s(),r(d))},c=()=>a(n.files?Array.from(n.files):[]),u=()=>a(void 0);n.addEventListener("change",c),n.addEventListener("cancel",u),e.body.append(n),n.click()})},capture(t){return t.mediaType==="video"?Z1():K1()}}}async function Q1(e){return e.type.startsWith("video/")?W1(e):q1(e)}async function q1(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(je("MEDIA_PREPARE_FAILED","无法解码所选图片")),r.src=t}),{width:r.naturalWidth,height:r.naturalHeight}}finally{URL.revokeObjectURL(t)}}async function W1(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(je("MEDIA_PREPARE_FAILED","无法读取所选视频元数据")),r.src=t});let n=r.duration;return Number.isFinite(n)||(n=await $1(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 $1(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 K1(){const e=document.createElement("canvas");e.width=640,e.height=480;const t=e.getContext("2d");if(!t)throw je("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 je("MEDIA_PREPARE_FAILED","无法生成测试图片");return new File([n],"browser-dev-camera.png",{type:"image/png"})}async function Z1(){const e=document.createElement("canvas");e.width=320,e.height=240;const t=e.getContext("2d");if(!t)throw je("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=e.captureStream?.bind(e),n=globalThis.MediaRecorder;if(!r||!n)throw je("MEDIA_PREPARE_FAILED","当前浏览器不支持 MediaRecorder 视频模拟");const i=r.call(e,12),s=new n(i,{mimeType:X1(n)}),a=[],c=new Promise((l,h)=>{s.ondataavailable=f=>{f.data.size>0&&a.push(f.data)},s.onstop=()=>l(),s.onerror=()=>h(je("MEDIA_PREPARE_FAILED","模拟拍摄录制失败"))});s.start();const u=Date.now();await J1(t,e,()=>Date.now()-u<900),s.stop(),await c;for(const l of i.getTracks())l.stop();const d=new Blob(a,{type:s.mimeType||"video/webm"});if(d.size===0)throw je("MEDIA_PREPARE_FAILED","模拟拍摄未生成视频数据");return new File([d],"browser-dev-camera.webm",{type:d.type})}function X1(e){for(const t of["video/webm;codecs=vp8","video/webm","video/mp4"])if(e.isTypeSupported?.(t))return t;return"video/webm"}async function J1(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 vn(e){if(e.aborted){const t=new Error("Browser Dev Host 媒体选择已取消");throw t.name="AbortError",t}}function je(e,t){const r=new Error(t);return r.name="BrowserDevMediaError",r.code=e,r}function sl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:void 0}function al(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function eS(e){const t=ot(e.runtimePermissions),r=pc({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=ot(e.publishedRuntimePermissions),s=ot(r.runtimePermissions);for(const a of gc){const c=a.key,u={network:"Network",companion:"Companion",appProtocol:"AppProtocol"}[c]??a.name;if(!e.declaredPermissions?.[c]?.enabled)continue;const d=t.valid&&t.permissions[c]?.status==="enabled",l=r.temporaryPermissionKeys.some(h=>h===c);n.push({key:c,label:u,state:a.access==="declaration"?"declared":d?"approved":l?"temporary":"unavailable",facts:{platformApproval:a.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}:{},...a.access!=="declaration"&&!d&&!l?{reason:c==="appProtocol"?"最高危险权限:可执行任意协议并绕过其他 SDK 能力权限;当前没有有效临时授权,线上未批准":"没有有效的本地临时授权,线上未批准"}:{}})}if(e.declaredPermissions?.network?.useOfficialDomain){const a=t.valid&&t.permissions.network?.status==="enabled"&&t.permissions.network.config.useOfficialDomain===!0;n.push({key:"network.useOfficialDomain",label:"官方域名",state:a?"approved":"unavailable",...a?{}:{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 ol="__hb_sdk_mini_dev_console_installed__",tS=["log","debug","info","warn","error"];function rS(e,t=console){if(t[ol])return;let r=!1;for(const n of tS){const i=t[n];if(typeof i!="function")continue;const s=function(...a){try{e(n,a)}catch{}return i.apply(this,a)};try{t[n]=s,r=!0}catch{break}}r&&(t[ol]=!0)}const Fo=1,cl=64*1024,nS=64,iS=/^[A-Za-z0-9_-]{22}$/;class pt extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function sS(e,t=!1){const r=oS(e,t);switch(zo(r,"Server message"),cS(r),r.type){case"grant":return Gn(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),Yn(r.connectionEpoch,"connectionEpoch"),Nr(r.nextClientSequence,"nextClientSequence"),Nr(r.nextServerSequence,"nextServerSequence"),ul(r.snapshot),r;case"event":return Gn(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),Yn(r.connectionEpoch,"connectionEpoch"),Nr(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&hr("event must be account.changed or status.changed"),ul(r.snapshot),r;case"heartbeat":return Gn(r,["version","type","connectionEpoch","sequence"],"heartbeat"),Yn(r.connectionEpoch,"connectionEpoch"),Nr(r.sequence,"sequence"),r;default:return hr("Unknown server message type")}}function aS(e){const t=e.connectionEpoch;Yn(t,"connectionEpoch"),Nr(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(Yn(n.connectionEpoch,"connectionEpoch"),Nr(n.sequence,"sequence"),n.connectionEpoch!==t)throw new pt("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new pt("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new pt("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function oS(e,t){if(t)throw new pt("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new pt("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>cl)throw new pt("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>cl)throw new pt("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return uS(e),JSON.parse(e)}catch(r){throw r instanceof pt?r:new pt("INVALID_JSON","Channel frame must contain strict JSON")}}function ul(e){zo(e,"snapshot"),Gn(e,["account","permissions"],"snapshot"),zo(e.account,"snapshot.account"),Gn(e.account,["revision"],"snapshot.account"),Nr(e.account.revision,"snapshot.account.revision"),s1(e.permissions)||hr("snapshot.permissions is invalid")}function cS(e){e.version!==Fo&&hr("version must be 1")}function zo(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&hr(`${t} must be a plain JSON object`)}function Gn(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)))&&hr(`${r} fields are invalid`)}function Nr(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&hr(`${t} must be a non-negative safe integer`)}function Yn(e,t){(typeof e!="string"||!iS.test(e))&&hr(`${t} must be a 22-character base64url value`)}function hr(e){throw new pt("INVALID_MESSAGE",e)}function uS(e){new dS(e).scan()}class dS{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 pt("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 pt("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 dl=[1e3,2e3,4e3,8e3,15e3];function lS(e){const t=new Set,r=e.webSocketFactory??(j=>new WebSocket(j)),n=e.randomValues??(j=>crypto.getRandomValues(j)),i=e.timers??{clearTimeout:j=>window.clearTimeout(j),setTimeout:(j,ee)=>window.setTimeout(j,ee)},s=e.onlineTarget??(typeof window>"u"?void 0:window),a=e.visibilityTarget??(typeof document>"u"?void 0:document),c=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let u,d,l,h=!1,f=0,E,g=!1,b=!1;const N=new Set,y=(j,ee)=>{if(!(!e.onDiagnostic||N.has(j))){N.add(j);try{e.onDiagnostic({phase:j,...ee?{code:ee}:{}})}catch{}}},w=(j,ee,k=!1)=>{if(l&&j.account.revision<l.account.revision)return;const z=l&&JSON.stringify(j)===JSON.stringify(l);if(l=j,!(z&&!k))for(const F of t)F(j,ee)},I=()=>{if(h||E!==void 0||u)return;const j=dl[Math.min(f,dl.length-1)];f+=1,E=i.setTimeout(()=>{E=void 0,Y()},j)},x=()=>{h||!g||u||(E!==void 0&&(i.clearTimeout(E),E=void 0),Y())},V=()=>{c()&&x()},M=()=>{a&&!a.hidden&&x()},R=()=>{b||(b=!0,s?.addEventListener("online",V),a?.addEventListener("visibilitychange",M))},L=()=>{b&&(b=!1,s?.removeEventListener("online",V),a?.removeEventListener("visibilitychange",M))},Y=()=>{if(h||u)return;g=!0,R(),E!==void 0&&(i.clearTimeout(E),E=void 0);let j,ee;try{j=r(e.url)}catch{y("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),I();return}try{ee=hS(n)}catch{y("entropy","NONCE_GENERATION_FAILED");try{j?.close(1011,"channel initialization failed")}catch{}I();return}u=j;let k,z,F;const U=()=>{j.removeEventListener("open",P),j.removeEventListener("message",C),j.removeEventListener("close",Q),j.removeEventListener("error",S),d===U&&(d=void 0)},H=()=>{if(u===j){u=void 0,U();try{j.close(1008,"invalid channel state")}catch{}I()}},P=()=>{if(!(h||u!==j))try{j.send(JSON.stringify({version:Fo,type:"hello",csrfToken:e.csrfToken,clientNonce:ee}))}catch{y("send","HELLO_SEND_FAILED"),H()}},C=q=>{if(h||u!==j)return;if(typeof q.data!="string"){y("parse","TEXT_FRAME_REQUIRED"),H();return}let W;try{W=sS(q.data)}catch(Z){y("parse",Z instanceof pt?Z.code:"INVALID_MESSAGE"),H();return}if(W.type==="grant"){if(F){y("sequence","DUPLICATE_GRANT"),H();return}k=W.connectionEpoch,z=W.nextClientSequence,F=aS({connectionEpoch:k,nextSequence:W.nextServerSequence}),f=0,N.clear(),w(W.snapshot,{type:"grant"});return}if(!F||!k||z===void 0){y("sequence","MESSAGE_BEFORE_GRANT"),H();return}try{F.accept(W)}catch{y("sequence","INVALID_SEQUENCE"),H();return}if(W.type==="heartbeat"){try{j.send(JSON.stringify({version:Fo,type:"heartbeat.ack",connectionEpoch:k,sequence:z}))}catch{y("send","HEARTBEAT_ACK_SEND_FAILED"),H()}z=z===Number.MAX_SAFE_INTEGER?void 0:z+1;return}w(W.snapshot,{type:"event",event:W.event},!0)},Q=()=>{u===j&&(y("close","SOCKET_CLOSED"),u=void 0,U(),I())},S=()=>{y("open","SOCKET_ERROR"),H()};j.addEventListener("open",P),j.addEventListener("message",C),j.addEventListener("close",Q),j.addEventListener("error",S),d=U};return{connect:Y,subscribeUpdates(j){return t.add(j),()=>t.delete(j)},dispose(){if(h)return;h=!0,g=!1,L(),E!==void 0&&i.clearTimeout(E),E=void 0;const j=u;u=void 0,d?.(),j?.close(1e3,"client disposed"),t.clear()}}}function fS(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,s=e[n+1],a=e[n+2];r+=t[i>>2],r+=t[(i&3)<<4|(s??0)>>4],s!==void 0&&(r+=t[(s&15)<<2|(a??0)>>6]),a!==void 0&&(r+=t[a&63])}return r}function hS(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=fS(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let Fe=!1,em=!1,Ke;const tm=new AbortController;try{rS((e,t)=>{wr(`console.${e}`,{source:"host",message:t.map(r=>CS(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const mS="/__hb_sdk_bootstrap__",ES="/__hb_sdk__/network",gS="/session/status",pS="/session/request",TS="/session/events",_S=1e3,AS=1e3,IS=15e3,ll="dark",bS=["windows","macos","linux","unknown"],rm=new URL(location.href).searchParams,nm=rm.get("mini_url"),ct=rm.get("ui_preview")==="1",yS={get device(){return nO("#device")}};if(!nm&&!ct)throw yS.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const im=nm??"about:blank",Be=await _m(),Fc=ct?void 0:await Ct.configure({csrfToken:Be.csrfToken??"",diagnosticsToken:Be.diagnosticsToken??"",signal:tm.signal,query:KS,onDropped:e=>{re.diagnosticsDropped=e},onOwnershipLost:fm});re.diagnosticTargetId=Fc?.targetId??"";re.diagnosticOwnerId=Fc?.ownerId??"";re.diagnosticTargetName=Fc?.metadata.displayName??"";re.openPlatformBaseUrl=Be.openPlatformBaseUrl;re.devReadiness=Be.devReadiness;re.miniProgramSupportsDesktop=Be.miniProgramSupportsDesktop;re.miniProgramPlatforms=Be.devContext.platforms??[];re.desktopLaunch.workspaceCardsEnabled=Be.workspaceCardsEnabled;El(Be.hostPlatform);gl(Be.windowForm);Be.lanAddresses;Be.defaultLanAddressId;Be.mobileLaunchRedirect;let sm=Be.nativeAppLaunchUnavailableReason,Qn=Be.devSessionId,jo=Be.miniProgramManifestAccessToken,Ki=Be.workspaceCardsEnabled,am=Gc(Be),bt=Be.devContext,Zr=Be.browserDevContext,$e=Vn(Zr);ta();let un=Bc($e),Ra=0;const Pr=new AbortController;let zc=0,Gt,Vo=0,Go,Yo,ao=!1;const dn=Wm({apply:$m,waitForLayout:async e=>{await es(),await Al(e),await Il(e)}});let jc=!1;function oo(e){if(e.throwIfAborted(),Fe)throw new Ar("SESSION_CLOSED","调试台已关闭");if(re.diagnosticOwnershipLost)throw new Ar("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!jc)throw new Ar("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(Kr)throw new Ar("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const Qo=Qm({observe:()=>{const e=li()?{width:Ji.value.width,height:Ji.value.height}:{width:go.value.screenWidth,height:go.value.screenHeight};return{preset:re.deviceSelectionId,orientation:li()?e.width>=e.height?"landscape":"portrait":re.display.orientation,runtimeStatus:re.runtimeStatus,viewport:e,instanceId:Ke?.mounted?Ke.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:Zm()}},async selectPreset(e,t){oo(t),re.deviceSelectOpen=!1;const r=re.previewMode,n=Ke;Km(e),await es(),t.throwIfAborted(),re.previewMode!==r&&await fl(n,t)},async applyOrientation(e,t){oo(t),re.deviceSelectOpen=!1,await dn.applyDisplay({mode:e,hideCapsule:re.display.capsuleHidden},t)},async reload(e){oo(e),re.deviceSelectOpen=!1;const t=Ke;fr("runtime.restart",{boundary:zc+1}),kr("manual restart").catch(()=>{}),await fl(t,e)},async waitForLayout(e){await es(),e.throwIfAborted(),await Al(e),await Il(e)}}),Zi=n0(),om={...Qo.bridge,prepareCapture:Zi.prepare,restoreCapture:Zi.restore,cancel(e){Qo.bridge.cancel(e),Zi.cancel(e)}};window.__HB_SDK_PREVIEW__=om;async function fl(e,t){for(;;){if(t.throwIfAborted(),Fe)throw new Ar("SESSION_CLOSED","调试台已关闭");if(Ke!==e&&Gt===void 0){const r=re.runtimeStatus;if(r==="ready"||ct&&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 qo,Wo,$o,Ko,Zo,Xo,hl=Date.now(),Kr=!1,Xr=-1,di=!1,Zt,Jo,ec,Xi,_r;const Js=new Set,ml="hb-sdk:browser-dev-host:user-data-device";function NS(){try{const e=localStorage.getItem(ml)?.trim();if(e)return e;const t=typeof crypto.randomUUID=="function"?crypto.randomUUID():`mock-${Date.now().toString(36)}`;return localStorage.setItem(ml,t),t}catch{return"browser-mock-device"}}const wS=NS();function DS(){return{miniProgramId:bt.miniProgramId?.trim().toLowerCase()||"anonymous-mini-program",userId:Zt?.trim()||"anonymous-user",deviceId:wS,environment:"development"}}function cm(){return Zh($e.runtimePermissions,un,$e)}function SS(){const e=ot(cm());return e.valid&&e.permissions.network?.status==="enabled"?"upload":"no_network"}function OS(){return M1({declaredPermissions:$e.declaredPermissions,runtimePermissions:cm()})}const Yt=S1({resolveScope:DS,egressTier:SS,declared:OS});function ln(){em&&qm({...Yt.snapshot(),targetId:re.diagnosticTargetId,instanceId:Ke?.instanceId})}Yt.subscribe(ln);em=!0;ln();function co(){const e=Yt.snapshot().stateError;if(e)throw new Error(e)}vm({async refresh(){await Yt.refresh(),co()},async revokeSession(){await Yt.revokeSession(),co()},async resetAll(){await Yt.resetAll(),co()}});const tc=B1({onDiagnostic:({action:e,alias:t,detail:r})=>fr(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),fn=d1({applyStatus:e=>pm(e,!0),fetchStatus:e=>gm(Yc(Pr.signal,e)),getCanonicalRevision:()=>Xr,onError:XS,reconcile:()=>BS(Ra)}),rc=l1({connectEvents:Tm,invalidate:()=>fn.invalidate(),isDisposed:()=>Fe,maxDelayMs:IS,minDelayMs:AS,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let uo=0,Bi="",lo=!1,nc,ic;function um(){ct||Fe||re.diagnosticOwnershipLost||Ct.poll().finally(()=>{!Fe&&!re.diagnosticOwnershipLost&&(ic=window.setTimeout(um,1e3))})}um();await ea(!1);Am();bm(Im(Be));ct&&RS();fi();ct||await lm();MS();dm();GS();await kr("initial");ct||(Tm(),xS());jc=!0;function dm(){!ct&&!Fe&&(nc=window.setTimeout(()=>{lm().finally(dm)},1e3))}async function lm(){if(!(lo||Fe)){lo=!0;try{const e=await fetch(`${qc}?after=${uo}&limit=500`,{headers:{"x-hb-sdk-csrf":Be.csrfToken??""},signal:AbortSignal.any([Pr.signal,AbortSignal.timeout(5e3)])});if(!e.ok){re.diagnosticsStale=!0;return}const t=await e.json();if(Fe)return;if(Bi&&t.epoch!==Bi){uo=0,Bi=t.epoch,km();return}Bi=t.epoch,re.uploadSessions=t.uploadSessions;const r=await fetch(`${qc}?mode=inspect`,{headers:{"x-hb-sdk-csrf":Be.csrfToken??""},signal:AbortSignal.any([Pr.signal,AbortSignal.timeout(5e3)])});if(r.ok){const s=await r.json();re.diagnosticInstances=s.instances,re.diagnosticTargets=s.targets,re.diagnosticPrimaryTargetId=s.primaryTargetId;const a=s.targets.find(c=>c.targetId===re.diagnosticTargetId);a&&(re.diagnosticTargetName=a.metadata.displayName),a&&(a.state==="closed"||a.ownerId!==re.diagnosticOwnerId)&&fm()}re.diagnosticsStale=!r.ok,re.diagnosticsGap=re.diagnosticsGap||t.gap===!0;const n=new Map(re.diagnosticTargets.map(s=>[s.targetId,s.metadata.displayName])),i=new Map(re.diagnosticInstances.map(s=>[s.instanceId,n.get(s.targetId)]));for(const s of t.items){const a=xm(s);a&&(a.targetName=n.get(s.targetId)??i.get(s.instanceId),a.uploadSessionId=s.uploadSessionId,a.uploadSessionName=t.uploadSessions.find(c=>c.id===s.uploadSessionId)?.name,a.dedupeKey=void 0,Um(a,s.cursor))}uo=t.nextCursor}catch{re.diagnosticsStale=!0}finally{lo=!1}}}function MS(){window.addEventListener("beforeunload",JS),window.addEventListener("hb-sdk:refresh-storage",fi),qo=Bm(()=>document.querySelector("#host-fullscreen-exit-mount")),Wo=Tn(()=>[qn.value,ho.value,Hi.value?.state,Hi.value?.stale,Hi.value?.capabilities.storage].join("|"),()=>{re.storage=[],re.storageError="",fi()}),$o=Tn(()=>re.devicePresetId,()=>dn.notifyViewportChange(),{flush:"post"}),Ko=Tn(()=>re.previewMode,()=>{Xt("preview mode changed"),pl(!1),Hm(!1),hn("preview mode changed")},{flush:"sync"}),Zo=Tn(()=>Ji.value,()=>dn.notifyViewportChange(),{flush:"post"}),Xo=Tn(()=>re.desktopWindow.closed,(e,t)=>{if(li()){if(e){Xt("desktop window closed"),re.runtimeStatus="closed";return}t&&re.runtimeStatus==="closed"&&hn("desktop window reopened")}},{flush:"sync"})}function CS(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 hn(e){Fe||Gt!==void 0||(fr("runtime.restart",{boundary:zc+1}),Gt=window.setTimeout(()=>{Gt=void 0,Fe||kr(e)},0))}async function kr(e,t=im,r){if(Fe||Kr||re.diagnosticOwnershipLost)return;if(Gt!==void 0&&window.clearTimeout(Gt),Gt=void 0,Xt(e),li()&&re.desktopWindow.closed){re.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=Fm(i,u=>{ct||Ct.event(i,u)}),a={instanceId:i,launchUrl:t,locationBasePath:r,interactions:s,sequence:++zc,state:"starting",iframe:n,terminal:new AbortController,permissions:wm(un),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(a.iframe.dataset.hbSdkInstanceId=a.instanceId,Ke=a,re.runtimeStatus="loading",mm(),ct||Ct.send({operation:"register",instanceId:a.instanceId}),await es(),!tt(a))return;const c=Sm("#device");if(!c){fo(a,new Error("预览容器尚未挂载"));return}if(ct){c.innerHTML='<div class="browser-mock-preview"><span class="browser-mock-preview__icon">UI</span><strong>Browser Mock</strong><small>mp_preview</small></div>',re.runtimeStatus="idle";return}c.replaceChildren(a.iframe),a.mounted=!0,Ct.send({operation:"activate",instanceId:a.instanceId});try{const u=await KD(LS(a));if(!tt(a)){u.dispose();return}a.assembly=u,u.ports.companion=tc.port,u.ports.media=H1({getMode:()=>re.mediaSimulation,signal:a.terminal.signal});const d=r1({signal:a.terminal.signal,csrfToken:()=>Be.csrfToken??""}),l=i1({signal:a.terminal.signal,refreshAccount:f=>ea(!0,f),request:Em,readState:()=>({signed:bt,browser:$e,userId:Zt,accountRevision:Xr,networkEnabled:a.permissions.networkRequest.status==="enabled"})}),h=LD({iframe:a.iframe,authorizationContext:l,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}:{},...U1},authPresentation:u.authPresentation,userDataPresentation:u.userDataPresentation,companionPresentation:tc.presentation,resolveLaunchConfiguration:async()=>l.resolveLaunchConfiguration((await u.resolveLaunch()).configuration,{signal:a.terminal.signal}),dispose:()=>sc(a),onDevDocumentReload:(f,E)=>{tt(a)&&kr("development document reloaded",f,E)},onDevUploadSession:f=>{tt(a)&&(a.uploadSessionId=f,mn(a,{uploadSessionId:f}))},onReady:()=>{tt(a)&&(a.state="ready",a.hadReady=!0,oc.value=d?h.diagnostics.gameSaves:void 0,re.runtimeStatus="ready",mn(a),wr("runtime.ready",{generation:a.sequence},Date.now(),void 0,a.instanceId))},onUserDataTelemetry:f=>{Yt.refresh();const E=L1(f);wr(E.method,E.detail,Date.now(),"info",a.instanceId)},onTrace:f=>kS(a,f),onError:f=>{tt(a)&&fo(a,f)},onCapabilityTrace:f=>{wr(f.method,{...f,source:"host"},f.timestamp,void 0,a.instanceId),tt(a)&&f.method==="storage.setStorage"&&f.outcome==="success"&&fi()}});a.runtime=h,await h.start(),tt(a)&&Yt.bind(h.getDataPermissionBridge())}catch(u){if(!tt(a))return;fo(a,u),wr("runtime.start.failed",ym(u,a),Date.now(),"error",a.instanceId),a.terminal.abort(u),a.runtime?.destroy(),a.iframe.remove(),sc(a)}}function fm(){Fe||re.diagnosticOwnershipLost||(re.diagnosticOwnershipLost=!0,Xt("预览页面授权已失效"),re.runtimeStatus="closed",jc=!1)}function tt(e){return Ke===e&&!Fe&&!e.terminal.signal.aborted&&e.state!=="closed"&&e.state!=="failed"}function mn(e,t={}){Ct.send({operation:"update",instanceId:e.instanceId,state:e.state,...t})}function hm(e,t){e.mounted&&(e.mounted=!1,Ct.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function sc(e){Ke===e&&(oc.value=void 0),e.interactions.dispose();const t=e.assembly;e.assembly=void 0,t?.dispose()}function fo(e,t){e.state==="failed"||e.state==="closed"||(e.state="failed",e.interactions.dispose(),mn(e,{error:ym(t,e),...e.uploadSessionId?{uploadSessionId:e.uploadSessionId}:{}}),hm(e,"Runtime failed"),Ke===e&&(re.runtimeStatus="error"))}function Xt(e){const t=Ke;t&&(Ke=void 0,oc.value=void 0,Yt.clearSession(),t.state!=="failed"&&(t.state="closed",mn(t,{reason:e})),hm(t,e),(!qn.value||qn.value===re.diagnosticTargetId)&&(Vo+=1,Go?.abort()),zm(),tc.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),sc(t),dn.reset())}function RS(){const e=Jm();re.diagnosticTargetId=e.targetId,re.diagnosticOwnerId=e.ownerId,re.diagnosticPrimaryTargetId=e.targetId,re.diagnosticTargetName=e.metadata.displayName,re.diagnosticTargets=[e],re.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"}};re.diagnosticTargets.push(t),re.diagnosticInstances.push({...re.diagnosticInstances[0],instanceId:t.currentInstanceId,targetId:t.targetId,ownerId:t.ownerId,kind:"mobile"}),mo({...Eo("console.error",{source:"app",message:"真机示例:请求超时"},Date.now(),"error"),targetId:t.targetId,instanceId:t.currentInstanceId}),fr("runtime.ready",{generation:1}),mo(Eo("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info")),fr("user.getInfo",{durationMs:34,outcome:"success"}),fr("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function LS(e){const t=e.terminal.signal,r=$e,n=Qn,i=Zh(r.runtimePermissions,e.permissions,r),s=li();return{signal:t,account:{async getCurrentUserId(){return(await ea(!1,t)).user_id},async ensureAuthenticated({signal:a}){await ea(!1,a)},onChange(a){return Js.add(a),()=>Js.delete(a)}},authenticatedRequest:Em,storage:{area:"local",storage:O1(localStorage)},presentation:k1({close:async()=>{tt(e)&&(Xt("mini program closed"),mm(),re.runtimeStatus="closed",s&&pl(!0))},reload:()=>{tt(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:a=>{tt(e)&&Tl(a)},...s?{getViewportMetrics:()=>{const a=Ji.value;return{windowWidth:a.width,windowHeight:a.height,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio,safeArea:{left:0,right:a.width,top:0,bottom:a.height}}},getNavigationBarHeight:()=>Xm}:{getDeviceMetrics:()=>go.value,applyDisplay:(a,c)=>dn.applyDisplay(a,c),isCapsuleHidden:()=>re.display.capsuleHidden},onViewportChange:a=>dn.onViewportChange(a)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:a=>{document.title=a}},resolveLaunch:async()=>({configuration:A1({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,firstParty:r.source==="remote"&&r.firstParty===!0,...re.miniProgram.bound&&re.miniProgram.name.trim()?{miniProgramName:re.miniProgram.name}:{},...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:s?re.hostPlatform:jm.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:a=>_1(a),confirmFollowAuthor:a=>f1(a)},userDataPresentation:{confirmDataPermission:N1},protocol:PS(e)}}function li(){return re.previewMode==="desktop"}function PS(e){return{async invoke(t){wr("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:vS(t)},Date.now(),void 0,e.instanceId)}}}function vS(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 yt(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function mm(){document.documentElement.dataset.navigationBarStyle=ll,Tl(ll)}function kS(e,t){tt(e)&&t.type==="document_validation"&&typeof t.documentVerifying=="boolean"&&mn(e,{documentVerifying:t.documentVerifying}),Fe||Ct.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(Vm({...t,generation:e.sequence})),...t.errorCode?{errorCode:t.errorCode}:{}}),e.runtimeId!==t.runtimeId&&(e.runtimeId=t.runtimeId,mn(e,{runtimeId:t.runtimeId})),tt(e)&&e.pendingNavigationReload&&t.type==="bridge_response"&&t.method==="navigation.reload"&&t.outcome==="success"&&(e.pendingNavigationReload=!1,hn("navigation.reload"))}async function Em(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 VS(n?ES:pS,{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&&fn.invalidate();const s=await i.json();if(!i.ok)throw s;return s}async function ea(e,t){const r=Ra,n=await gm(Yc(Pr.signal,t));return Nm(r)?pm(n,e).status:ac()}async function gm(e){return await(await fetch(gS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function pm(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Xr)return{changed:!1,status:ac()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?Ve(e.nickname):void 0,i=e.authenticated?Ve(e.avatar):void 0,s=e.revision!==Xr||e.authenticated!==di||r!==Zt||n!==Jo||i!==ec;return Xr=e.revision,di=e.authenticated,Zt=r,Jo=n,ec=i,Am(),ln(),t&&s&&Js.forEach(a=>a(Zt)),{changed:s,status:ac()}}function ac(){return{authenticated:di,revision:Xr,...di&&Zt?{user_id:Zt}:{}}}function xS(){if(!(!Be.csrfToken||Fe))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",_r=lS({csrfToken:Be.csrfToken,onDiagnostic:t=>fr("channel.diagnostic",t),url:e.toString()}),_r.subscribeUpdates((t,r)=>US(t,r)),_r.connect()}catch{_r?.dispose(),_r=void 0}}function US(e,t){fn.invalidate(e.account.revision),rO(un,e.permissions)?t.type==="event"&&t.event==="status.changed"&&kr("status changed"):(un=wm(e.permissions),HS())}function Tm(){if(Xi?.close(),Xi=void 0,!Zt||Fe)return;const e=new EventSource(TS);Xi=e,e.addEventListener("account-invalidated",()=>{fn.invalidate()}),e.addEventListener("account-revision",()=>{fn.invalidate()}),e.onopen=()=>{rc.reset()},e.onerror=()=>{e.close(),rc.schedule()}}async function BS(e){Nm(e)&&await kr("account revision changed")}async function HS(){Fe||await kr("permission changed")}async function _m(e){const t=await fetch(mS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:Yc(AbortSignal.timeout(5e3),e)});if(!t.ok)throw new Error("Browser Dev Host bootstrap request failed");const r=await t.json();if(!yt(r))throw new Error("Browser Dev Host bootstrap is invalid");const n=tO(r.mobileLaunchRedirect);if(Object.hasOwn(r,"mobileLaunchRedirect")&&r.mobileLaunchRedirect!==void 0&&!n)throw new QS;return{openPlatformBaseUrl:typeof r.openPlatformBaseUrl=="string"?r.openPlatformBaseUrl:void 0,devReadiness:jS(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:Xd(r.devContext,r.runtimePermissions),browserDevContext:Xd(r.browserDevContext??r.devContext,r.runtimePermissions),lanAddresses:Array.isArray(r.lanAddresses)?r.lanAddresses.filter(eO):[],loginAvailable:r.loginAvailable===!0,miniProgram:WS(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:zS(r.windowForm),hostPlatform:FS(r.hostPlatform)}}function FS(e){return bS.includes(e)?e:"unknown"}function zS(e){if(!yt(e))return;const t=a=>typeof a=="number"&&Number.isFinite(a)&&a>0?a: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 jS(e){if(!yt(e))return;const t=a=>{if(!(!yt(a)||!["ready","pending","blocked","not-configured"].includes(String(a.state))))return{state:a.state,...typeof a.reason=="string"?{reason:a.reason.slice(0,240)}:{}}},r=t(e.browser),n=t(e.mobile),i=t(e.companion);if(!r||!n||!i||!yt(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(a=>yt(a)&&typeof a.alias=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(a.alias)&&["windows-x64","macos-arm64"].includes(String(a.target))).map(({alias:a,target:c})=>({alias:a,target:c})):[]}}}async function VS(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),Be.csrfToken&&r.set("x-hb-sdk-csrf",Be.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function GS(){Vc(),ct||(Yo=window.setInterval(()=>{qS()},_S))}function YS(e){const t=yr($e),r=!!bt.localDevLaunchToken,n=bt.developmentSnapshotDigest;re.devReadiness=e.devReadiness,re.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,re.miniProgramPlatforms=e.devContext.platforms??[],El(e.hostPlatform),gl(e.windowForm),Ki=e.workspaceCardsEnabled,am=Gc(e),bt=e.devContext,Zr=e.browserDevContext,$e=Vn(Zr),un=Bc($e),ta(),e.lanAddresses,e.defaultLanAddressId,e.mobileLaunchRedirect,sm=e.nativeAppLaunchUnavailableReason,Qn=e.devSessionId,jo=e.miniProgramManifestAccessToken,bm(Im(e)),Vc(),(t!==yr($e)||r!==!!bt.localDevLaunchToken||n!==bt.developmentSnapshotDigest&&(Ke?.state==="starting"||Ke?.state==="failed"))&&(Xt("local permission context changed"),hn("local permission context changed"))}function ta(){if(ct){re.localPermissions=e0(),re.devContextWarning="";return}re.localPermissions=eS($e),re.devContextWarning=$e.source==="anonymous"?"未连接线上上下文":$e.warning?"本地上下文受限,请检查 CLI 状态":"",ln()}function Vc(){let e;try{e=Gm(im)}catch{}const t=bt.miniProgramId?.trim().toLowerCase();let r=sm?.trim()??"";!r&&(bt.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!bt.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&Ki&&!Qn&&(r="本地调试会话尚未就绪"),!r&&bt.expiresAt!==void 0&&bt.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),_l({...e?{address:e}:{},...t?{miniProgramId:t}:{},...Ki&&Qn?{devSessionId:Qn}:{},...jo?{miniProgramManifestToken:jo}:{},workspaceCardsEnabled:Ki,ready:r==="",...r?{unavailableReason:r}:{}})}class QS extends Error{}async function qS(){if(!(ao||Fe)){ao=!0;try{const e=await _m();hl=Date.now();const t=Kr;Kr=!1;const r=Gc(e);if(!t&&r===am&&yr(Vn(e.browserDevContext))===yr($e)){Zr=e.browserDevContext,$e=Vn(Zr),ta();return}YS(e),t&&hn("CLI dev session reconnected")}catch{const t=Vn(Zr);yr(t)!==yr($e)&&($e=t,un=Bc($e),ta(),Xt("local permission context expired"),hn("local permission context expired"),Vc()),Date.now()-hl>=3e4&&!Kr&&(Kr=!0,Xt("CLI dev session disconnected"),Sm("#device")?.replaceChildren(),re.runtimeStatus="closed",re.localPermissions=[],re.devContextWarning="调试会话已断开",_l({ready:!1,unavailableReason:"调试会话已断开"}),re.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}})}finally{ao=!1}}}function Gc(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 Am(){if(!di){re.account={authenticated:!1,avatar:"",nickname:"未登录"};return}re.account={authenticated:!0,avatar:ec??"",nickname:Jo||Zt||"已登录"}}function Im(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function bm(e){if(!!!e?.miniProgramId||!e){re.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试",description:"",version:""},ln();return}re.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??""},ln()}function WS(e){if(e===null)return null;if(!yt(e))return;const t=Ve(e.miniProgramId)??Ve(e.mini_program_id);if(t)return{miniProgramId:t,...Ve(e.description)?{description:Ve(e.description)}:{},...Ve(e.name)?{name:Ve(e.name)}:{},...Ve(e.iconUrl)??Ve(e.icon_url)?{iconUrl:Ve(e.iconUrl)??Ve(e.icon_url)}:{},...Ve(e.status)?{status:Ve(e.status)}:{},...Ve(e.version)?{version:Ve(e.version)}:{},...Ve(e.developerName)??Ve(e.developer_name)?{developerName:Ve(e.developerName)??Ve(e.developer_name)}:{}}}function Ve(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function fi(){const e=++Vo;Go?.abort();const t=new AbortController;Go=t;const r=qn.value,n=!r||r===re.diagnosticTargetId,i=Hi.value,s=ho.value||(n?Ke?.instanceId:void 0),a=()=>!Fe&&e===Vo&&r===qn.value&&s===(ho.value||(n?Ke?.instanceId:void 0));if(!n&&(!i||!s||i.stale||i.state!=="attached"||!i.capabilities.storage)){re.storage=[],re.storageError=!i||!i.capabilities.storage?"当前设备不支持存储诊断":"当前设备未连接或没有运行实例";return}if(ct){re.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}],re.storageError="";return}if(!s){re.storage=[],re.storageError="";return}try{const c=await Ym({instanceId:s,resource:"storage"},{csrfToken:Be.csrfToken,signal:AbortSignal.any([t.signal,Pr.signal])});if(!a())return;if(c.code)throw new Error(c.error??"Storage 诊断查询失败");re.storage=c.value,re.storageError=""}catch(c){if(!a())return;re.storage=[],re.storageError=Dm(c)}}function ym(e,t=Ke){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"),a=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",...a?{name:a}:{},...s?{stack:s}:{},...c?{cause:c}:{}}}function wr(e,t,r=Date.now(),n,i){$S(Eo(e,t,r,n==="debug"?"log":n),i)}function $S(e,t){if(Fe)return;if(ct){mo({...e,targetId:re.diagnosticTargetId});return}const r=yt(e.detail)?e.detail:{};Ct.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}:{},...yt(r.network)?{network:r.network}:{}})}async function KS(e){const t=Ke;if(!t||e.instanceId!==t.instanceId||!tt(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([Pr.signal,t.terminal.signal,AbortSignal.timeout(Math.max(1,e.deadline-Date.now()))]);let s,a;try{a=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!tt(t)||r!==t.runtime||e.instanceId!==t.instanceId?{code:"closed",error:"查询期间实例已结束"}:{value:a}}function ZS(e,t){fr("host.message",{message:e,status:t})}function XS(e){Fe||ZS(Dm(e),"error")}function fr(e,t){wr(e,t)}function JS(){Ct.close(),nc!==void 0&&window.clearTimeout(nc),ic!==void 0&&window.clearTimeout(ic),!Fe&&(Fe=!0,Zi.dispose(),Qo.dispose(),window.__HB_SDK_PREVIEW__===om&&delete window.__HB_SDK_PREVIEW__,window.removeEventListener("hb-sdk:refresh-storage",fi),Ra+=1,Pr.abort(new DOMException("Browser Dev Host disposed","AbortError")),fn.dispose(),Xt("Browser Dev Host disposed"),Yt.dispose(),Ct.send({operation:"close-target",reason:"Browser Dev Host disposed"}),window.setTimeout(()=>tm.abort(),2e3),Xi?.close(),_r?.dispose(),_r=void 0,rc.dispose(),Gt!==void 0&&window.clearTimeout(Gt),Gt=void 0,Yo!==void 0&&window.clearInterval(Yo),Js.clear(),qo?.(),qo=void 0,Wo?.(),Wo=void 0,$o?.(),$o=void 0,Ko?.(),Ko=void 0,Zo?.(),Zo=void 0,Xo?.(),Xo=void 0)}function Yc(e,t){return t?AbortSignal.any([e,t]):e}function Nm(e){return!Fe&&e===Ra}function eO(e){return yt(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 tO(e){if(!(!yt(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 wm(e){return{networkRequest:{...e.networkRequest}}}function rO(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function Dm(e){return e instanceof Error&&e.message?e.message:"操作失败"}function yt(e){return Object.prototype.toString.call(e)==="[object Object]"}function nO(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function Sm(e){return document.querySelector(e)??void 0}