@idosgames/core 0.26.6 → 0.26.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/dist/{GameHost-xACJW0x5.d.cts → GameHost-gNo-pSSn.d.cts} +4 -0
- package/dist/{GameHost-xACJW0x5.d.ts → GameHost-gNo-pSSn.d.ts} +4 -0
- package/dist/{VoiceController-BMXi4MNo.d.ts → VoiceController-BHAlGvEd.d.ts} +16346 -235
- package/dist/{VoiceController-BWb8NTp2.d.cts → VoiceController-FdN8yiN8.d.cts} +16346 -235
- package/dist/chunk-S24V5BGG.js +2 -0
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +43 -5
- package/dist/index.d.ts +43 -5
- package/dist/index.js +2 -2
- package/dist/platform/index.cjs +1 -1
- package/dist/platform/index.d.cts +2 -2
- package/dist/platform/index.d.ts +2 -2
- package/dist/platform/index.js +1 -1
- package/dist/realtime/index.d.cts +3 -3
- package/dist/realtime/index.d.ts +3 -3
- package/package.json +1 -1
- package/dist/chunk-YZ32MQXQ.js +0 -2
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var zod=require('zod'),ni=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ni__default=/*#__PURE__*/_interopDefault(ni);var qi=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,s=>{i(),t(s);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let s of [...i])s(t);}removeAllListeners(){this.listeners.clear();}};function ql(n){return {get:e=>n.getString(e),set:(e,t)=>n.setString(e,t),remove:e=>n.remove(e)}}var Ll="https://api.idosgames.com";function Bl(n,e){return {titleID:n.titleID,titleTemplateID:n.titleTemplateID??"default",buildKey:n.buildKey??"",baseUrl:(n.baseUrl??Ll).replace(/\/+$/,""),devBuild:n.devBuild??false,debugLogging:n.debugLogging??false,configStorage:n.configStorage??ql(e.storage),locale:n.locale??e.getLanguage(),appVersion:n.appVersion??""}}function G(){return crypto.randomUUID()}var qf="idos-host-files",as="files";function ls(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error);})}function Lf(n){return n.slice().buffer}var fi=class{map=new Map;async read(e){let t=this.map.get(e);return t?t.bytes.slice():null}async write(e,t){return this.map.set(e,{bytes:t.slice(),updatedAt:Date.now()}),true}async remove(e){this.map.delete(e);}async list(e=""){let t=[];for(let[i,s]of this.map)i.startsWith(e)&&t.push({key:i,size:s.bytes.byteLength,updatedAt:s.updatedAt});return t.sort((i,s)=>s.updatedAt-i.updatedAt)}},Yt=class{db=null;fallback=new fi;open(){return this.db||(this.db=(async()=>{try{if(typeof indexedDB>"u")return null;let e=indexedDB.open(qf,1);return e.onupgradeneeded=()=>{e.result.objectStoreNames.contains(as)||e.result.createObjectStore(as,{keyPath:"key"});},await ls(e)}catch{return null}})()),this.db}async store(e){let t=await this.open();if(!t)return null;try{return t.transaction(as,e).objectStore(as)}catch{return null}}async read(e){let t=await this.store("readonly");if(!t)return this.fallback.read(e);try{let i=await ls(t.get(e));return i?new Uint8Array(i.bytes):null}catch{return null}}async write(e,t){let i=await this.store("readwrite");if(!i)return this.fallback.write(e,t);try{let s={key:e,bytes:Lf(t),size:t.byteLength,updatedAt:Date.now()};return await ls(i.put(s)),!0}catch{return false}}async remove(e){let t=await this.store("readwrite");if(!t)return this.fallback.remove(e);try{await ls(t.delete(e));}catch{}}async list(e=""){let t=await this.store("readonly");if(!t)return this.fallback.list(e);try{let i=e&&typeof IDBKeyRange<"u"?IDBKeyRange.bound(e,e+"\uFFFF"):void 0,s=[];return await new Promise((r,o)=>{let c=t.openCursor(i);c.onerror=()=>o(c.error),c.onsuccess=()=>{let h=c.result;if(!h)return r();let g=h.value;g.key.startsWith(e)&&s.push({key:g.key,size:g.size,updatedAt:g.updatedAt}),h.continue();};}),s.sort((r,o)=>o.updatedAt-r.updatedAt)}catch{return []}}};function Li(){return typeof document<"u"&&typeof document.createElement=="function"}function us(n={}){return Li()?new Promise(e=>{let t=false,i=document.createElement("input");i.type="file",n.accept?.length&&(i.accept=n.accept.join(",")),i.multiple=n.multiple===true,i.style.display="none";let s=r=>{t||(t=true,i.remove(),e(r));};i.addEventListener("cancel",()=>s([])),i.addEventListener("change",()=>{let r=[...i.files??[]];Promise.all(r.map(async o=>{try{return {bytes:new Uint8Array(await o.arrayBuffer()),name:o.name,mime:o.type||"application/octet-stream"}}catch{return null}})).then(o=>s(o.filter(c=>c!==null)));}),document.body?.appendChild(i),i.click();}):Promise.resolve([])}var Gl="idos_device_id",wo="idos:platformSignIn:declined:",lt="UNAVAILABLE",gi=Object.freeze({autoSignIn:false,signIn:false,rewardedAds:false,titleAds:false,storePurchases:false,creditsPayments:true,creditsConfirm:false,cryptoTopUp:false,sceneCaptureRequests:false,share:false,vibration:false,sharedMemory:false,filePicker:false,pushNotifications:false}),Bt=class{storage;files;visible=true;visibilityListeners=new Set;linkListeners=new Set;constructor(e,t=new fi){this.storage=e,this.files=t;}buyProduct(e){return Promise.resolve({ok:false,error:lt})}finishPurchase(e,t){return Promise.resolve(false)}pendingPurchases(){return Promise.resolve([])}pickFiles(e){return Promise.resolve([])}requestPushToken(e){return Promise.resolve({error:lt})}getDeviceID(){let e=this.storage.getString(Gl);return e||(e=this.newDeviceID(),this.storage.setString(Gl,e)),e}newDeviceID(){return G()}setSignInDeclined(e,t){t?this.storage.setString(wo+e,"1"):this.storage.remove(wo+e);}isSignInDeclined(e){return this.storage.getString(wo+e)==="1"}isVisible(){return this.visible}onVisibilityChange(e){return this.visibilityListeners.add(e),()=>{this.visibilityListeners.delete(e);}}onLinkOpened(e){return this.linkListeners.add(e),()=>{this.linkListeners.delete(e);}}emitLink(e){for(let t of [...this.linkListeners])try{t(e);}catch{}}setVisible(e){if(e!==this.visible){this.visible=e;for(let t of [...this.visibilityListeners])try{t(e);}catch{}}}};function cs(n){return (typeof n=="number"?[n]:[...n]).map(t=>Math.max(0,Math.round(t)))}var Xt=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,t){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,t);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},Bi=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,t){this.map.set(e,t);}remove(e){this.map.delete(e);}};var gt={Virtual:"Virtual",Crypto:"Crypto"},Ri=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),ps={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},Ci=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),Ee={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},ds=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),Bf={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},hs=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),Gf={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},ms=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),Ff={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},Gi=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),ze={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};var Fi=class extends Bt{id="memory";supports;clientPlatform;deviceId;constructor(e={}){let t="getString"in e?{storage:e}:e;super(t.storage??new Bi),this.supports=Object.freeze({...gi,...t.supports}),this.clientPlatform=t.clientPlatform??Ee.Web,this.deviceId=t.deviceId??"memory-device";}setVisibleForTest(e){this.setVisible(e);}newDeviceID(){return this.deviceId}getPlatform(){return "Web"}getClientPlatform(){return this.clientPlatform}getFullURL(){return ""}getStartParameter(){return null}getReferrer(){return null}getTelegramInitDataRaw(){return null}getDeviceModel(){return "Memory"}getLanguage(){return ""}async signIn(){return {error:lt}}async showRewardedAd(){return {ok:false,error:lt}}async confirmCredits(){return {ok:false,error:lt}}async topUp(){return {ok:false,error:lt}}openInvoice(){}openUrl(){}async share(){return "unavailable"}async shareFile(){return "unavailable"}async copyText(){return false}vibrate(){}createWorker(){return null}};function Ni(n){return [n.text,n.url].filter(e=>!!e).join(" ")}function fs(){return globalThis.crossOriginIsolated===true&&typeof SharedArrayBuffer<"u"}function gs(n,e={}){if(typeof Worker>"u")return null;try{let t=typeof location<"u"?location.href:void 0,i=t?new URL(n,t):new URL(n),s={type:"module",name:e.name};if(i.protocol==="blob:"||i.protocol==="data:"||!t||i.origin===new URL(t).origin)return new Worker(i.href,s);let r=URL.createObjectURL(new Blob([`import ${JSON.stringify(i.href)};`],{type:"text/javascript"}));return new Worker(r,s)}catch{return null}}var ko=1,Fl="__IDOS_HOST__";function zo(){let n=globalThis[Fl];return !n||typeof n!="object"||n.protocol!==1||typeof n.post!="function"?null:n}var Nf={signIn:30*6e4,showRewardedAd:5*6e4,confirmCredits:10*6e4,topUp:15*6e4,openInvoice:3e4,openUrl:3e4,share:10*6e4,shareFile:10*6e4,copyText:3e4,vibrate:3e4,buyProduct:30*6e4,finishPurchase:6e4,pendingPurchases:6e4,requestPushToken:10*6e4};function _f(n){switch((n??"").toLowerCase()){case "android":return Ee.Android;case "ios":return Ee.Ios;case "web":return Ee.Web;default:return Ee.Unknown}}var _i=class extends Bt{id;supports;shell;pending=new Map;nextId=1;constructor(e,t=new Xt){super(t,new Yt),this.shell=e,this.id=`native:${e.id??"unknown"}`;let i=e.capabilities??{},s=r=>i[r]??gi[r];this.supports=Object.freeze({autoSignIn:s("autoSignIn"),signIn:s("signIn")||s("autoSignIn"),rewardedAds:s("rewardedAds")||s("titleAds"),titleAds:s("titleAds"),storePurchases:s("storePurchases"),creditsPayments:s("creditsPayments"),creditsConfirm:s("creditsConfirm"),cryptoTopUp:s("cryptoTopUp"),sceneCaptureRequests:false,share:s("share"),vibration:s("vibration"),sharedMemory:fs(),filePicker:Li(),pushNotifications:s("pushNotifications")}),e.receive=r=>this.receive(r),e.info?.visible===false&&this.setVisible(false);}receive(e){let t;try{t=JSON.parse(e);}catch{return}if(!(!t||t.v!==1)){if(t.kind==="response"&&typeof t.id=="string"){let i=this.pending.get(t.id);if(!i)return;this.pending.delete(t.id),clearTimeout(i.timer),i.resolve(t.ok===true?{ok:true,result:t.result??{}}:{ok:false,error:typeof t.error=="string"?t.error:"FAILED"});return}if(t.kind==="event"&&t.name==="visibility"){let i=t.data;typeof i?.visible=="boolean"&&this.setVisible(i.visible);return}if(t.kind==="event"&&t.name==="link"){let i=t.data;typeof i?.url=="string"&&i.url&&this.emitLink(i.url);}}}request(e,t){let i=`r${this.nextId++}`,s={v:1,kind:"request",id:i,method:e,params:t};return new Promise(r=>{let o=setTimeout(()=>{this.pending.delete(i),r({ok:false,error:"TIMEOUT"});},Nf[e]);this.pending.set(i,{resolve:r,timer:o});try{this.shell.post(JSON.stringify(s));}catch{clearTimeout(o),this.pending.delete(i),r({ok:false,error:"UNAVAILABLE"});}})}notify(e,t){this.request(e,t);}newDeviceID(){return this.shell.info?.deviceId||super.newDeviceID()}getPlatform(){return this.getClientPlatform()===Ee.Ios?"iOS":this.getClientPlatform()}getClientPlatform(){return _f(this.shell.clientPlatform)}getFullURL(){return this.shell.info?.launchUrl??""}getStartParameter(){return this.shell.info?.startParameter??null}getReferrer(){return null}getTelegramInitDataRaw(){return null}getDeviceModel(){return this.shell.info?.deviceModel||this.id}getLanguage(){return this.shell.info?.language||""}async signIn(e){if(!this.supports.signIn)return {error:"UNAVAILABLE"};let t=await this.request("signIn",{titleID:e});if(!t.ok)return {error:t.error};let{code:i,ticket:s}=t.result;return typeof s=="string"&&s.length>0?{ticket:s}:typeof i=="string"&&i.length>0?{code:i}:{error:"no_code"}}async showRewardedAd(e){if(!this.supports.rewardedAds)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("showRewardedAd",e);return t.ok?{ok:true,via:t.result.via==="unit"?"unit":"ad"}:{ok:false,error:t.error}}async confirmCredits(e){if(!this.supports.creditsConfirm)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("confirmCredits",e);return t.ok?{ok:true}:{ok:false,error:t.error}}async topUp(e){if(!this.supports.cryptoTopUp)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("topUp",e);return t.ok?{ok:true}:{ok:false,error:t.error}}openInvoice(e){this.notify("openInvoice",{url:e});}async buyProduct(e){if(!this.supports.storePurchases)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("buyProduct",e);if(!t.ok)return {ok:false,error:t.error};let i=t.result.receipt;return i&&typeof i.receipt=="string"&&i.receipt?{ok:true,receipt:i}:{ok:false,error:"FAILED"}}async finishPurchase(e,t){return this.supports.storePurchases?(await this.request("finishPurchase",{receipt:e,consumable:t})).ok:false}async pendingPurchases(){if(!this.supports.storePurchases)return [];let e=await this.request("pendingPurchases",{});return !e.ok||!Array.isArray(e.result.receipts)?[]:e.result.receipts.filter(t=>t&&typeof t.receipt=="string"&&t.receipt)}async requestPushToken(e){if(!this.supports.pushNotifications)return {error:"UNAVAILABLE"};let t=await this.request("requestPushToken",{prompt:e.prompt===true});if(!t.ok)return {error:t.error};let{token:i,transport:s}=t.result;return typeof i!="string"||!i?{error:"UNAVAILABLE"}:{token:i,transport:s==="Apns"?"Apns":"Fcm"}}openUrl(e){this.notify("openUrl",{url:e});}async share(e){if(!this.supports.share)return await this.copyText(Ni(e))?"copied":"unavailable";let t=await this.request("share",e);return t.ok?t.result.outcome??"shared":t.error==="CANCELLED"?"cancelled":"unavailable"}pickFiles(e){return us(e)}async shareFile(e){let t=await this.request("shareFile",{name:e.name,mime:e.mime,data:Vf(e.bytes)});return t.ok?t.result.outcome??"shared":t.error==="CANCELLED"?"cancelled":"unavailable"}async copyText(e){return (await this.request("copyText",{text:e})).ok}vibrate(e){this.supports.vibration&&this.notify("vibrate",{pattern:cs(e)});}createWorker(e,t){return gs(e,t)}};function Vf(n){let e="";for(let i=0;i<n.length;i+=32768)e+=String.fromCharCode(...n.subarray(i,i+32768));return btoa(e)}function Gt(){return globalThis.Telegram?.WebApp??null}function _l(){let n=globalThis,e=n.Capacitor?.getPlatform?.();if(e)return Nl(e);let t=n.cordova?.platformId;return t?Nl(t):n.navigator?.userAgent??""?Ee.Web:Ee.Unknown}function Nl(n){let e=n.toLowerCase();return e==="android"?Ee.Android:e==="ios"?Ee.Ios:e==="web"?Ee.Web:Ee.Unknown}var wt=["https://idosgames.com","https://www.idosgames.com"],ys="https://platform.idosgames.com",Vl=/^[a-z0-9]{8}-preview\.idos\.games$/;function Mo(n){return n==="localhost"||n==="127.0.0.1"||n==="[::1]"||n.endsWith(".localhost")}function Oo(){if(typeof window>"u")return false;let n=window.location.hostname.toLowerCase();return Vl.test(n)?true:Mo(n)&&globalThis.__IDOS_PREVIEW__!=null}function ei(n){if(typeof window<"u"&&Vl.test(window.location.hostname.toLowerCase()))return n===ys;if(wt.includes(n))return true;if(typeof window>"u"||!Mo(window.location.hostname))return false;try{return Mo(new URL(n).hostname)}catch{return false}}var jl="IDOS_PLATFORM_WALLET_ACK",Wl="PLATFORM_WALLET_UNAVAILABLE",jf=5e3,Wf=18e4;function Hf(){if(ei(ys))return [ys];let n=[...wt],e=window.location.ancestorOrigins?.[0];return e&&!n.includes(e)&&ei(e)&&n.push(e),n}function Kf(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function kt(n,e,t,i={}){let s={ok:false,error:Wl,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(s);let r=window.parent;if(!r)return Promise.resolve(s);let o=Kf(),c=i.answerTimeoutMs??Wf;return new Promise(h=>{let g=false,V,oe=ue=>{g||(g=true,window.removeEventListener("message",be),clearTimeout(V),h(ue));},be=ue=>{if(!ei(ue.origin))return;let ge=ue.data;if(!(!ge||ge.requestId!==o)){if(ge.type===jl){clearTimeout(V),V=setTimeout(()=>oe({ok:false,error:"TIMEOUT",data:{}}),c);return}ge.type===e&&oe({ok:ge.ok===true,error:typeof ge.error=="string"?ge.error:void 0,data:ge});}};V=setTimeout(()=>oe(s),jf),window.addEventListener("message",be);for(let ue of Hf())try{r.postMessage({type:n,requestId:o,...t},ue);}catch{}})}var Eo={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},Qf=30*6e4;function Hl(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(Oo())return false;let n=window.location.ancestorOrigins?.[0];if(n&&!wt.includes(n))try{let e=new URL(n).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}function Uo(){if(typeof window>"u"||!Oo())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function Kl(n){let e=await kt(Eo.request,Eo.response,{titleID:n,supports:["pgs"]},{answerTimeoutMs:Qf}),t=e.data.ticket;if(e.ok&&typeof t=="string"&&t.length>0)return {ticket:t};let i=e.data.code;return e.ok&&typeof i=="string"&&i.length>0?{code:i}:{error:e.error??"no_code"}}var qo={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},$f=15*6e4,Jf=/^[a-z0-9]{8}-preview\.idos\.games$/;function Si(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !Jf.test(window.location.hostname.toLowerCase())}async function Ql(n){let e=await kt(qo.request,qo.response,{titleID:n.titleID,userID:n.userID,currencyID:n.currencyID,amount:n.amount},{answerTimeoutMs:$f});return e.ok?{ok:true}:{ok:false,error:e.error}}var Lo={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},Zf=5*6e4;function $l(){return Si()}async function Jl(n){let e=await kt(Lo.request,Lo.response,{titleID:n.titleID,userID:n.userID,requestID:n.requestID,placementID:n.placementID,adUnitID:n.adUnitID??null},{answerTimeoutMs:Zf});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var Bo={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},Yf=10*6e4,Xf=["DECLINED","NOT_ENOUGH_CREDITS"];function Zl(){let n=globalThis.navigator?.userAgent??"";if(!/\biDosGamesApp\/(?:player|studio)\//.test(n))return true;let e=/\biDosGamesPlatform\/(ios|android)\b/.exec(n);return (e?e[1]:/\bAndroid\b/.test(n)?"android":"ios")!=="ios"}function Yl(){return Si()}async function Xl(n){let e=await kt(Bo.request,Bo.response,{titleID:n.titleID,confirmationID:n.confirmationID},{answerTimeoutMs:Yf});return e.ok?{ok:true}:{ok:false,error:e.error}}var tu="IDOS_APP_FRAME_HIDDEN";function ti(){return globalThis.navigator??null}function Rs(){return typeof window<"u"}function eu(){if(!Rs())return false;try{return window.self!==window.top}catch{return true}}var Vi=class extends Bt{id;supports;hiddenBySite=false;documentHidden=false;constructor(e=new Xt){if(super(e,new Yt),!Rs()){this.id="web",this.supports=gi;return}let t=ti(),i=Hl();this.supports=Object.freeze({autoSignIn:i,signIn:i||Uo(),rewardedAds:$l(),titleAds:false,storePurchases:false,creditsPayments:Zl(),creditsConfirm:Yl(),cryptoTopUp:Si(),sceneCaptureRequests:eu(),share:typeof t?.share=="function",vibration:typeof t?.vibrate=="function",sharedMemory:fs(),filePicker:Li(),pushNotifications:false}),this.id=Gt()?"telegram":Uo()?"preview":this.supports.cryptoTopUp?"site":"web",this.watchVisibility(),window.addEventListener("hashchange",()=>this.emitLink(window.location.href));}watchVisibility(){typeof document<"u"&&(this.documentHidden=document.visibilityState==="hidden",document.addEventListener("visibilitychange",()=>{this.documentHidden=document.visibilityState==="hidden",this.update();})),eu()&&window.addEventListener("message",e=>{let t=e.data;!t||t.type!==tu||ei(e.origin)&&(this.hiddenBySite=t.hidden===true,this.update());}),this.update();}update(){this.setVisible(!this.documentHidden&&!this.hiddenBySite);}getPlatform(){return Gt()?.platform??"Web"}getClientPlatform(){return _l()}getFullURL(){return Rs()?window.location.href:""}getStartParameter(){let e=Gt()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){return typeof document>"u"?null:document.referrer||null}getTelegramInitDataRaw(){let e=Gt()?.initData;return e&&e.length>0?e:null}getDeviceModel(){return ti()?.userAgent||"Web"}getLanguage(){return ti()?.language||""}async signIn(e){return this.supports.signIn?Kl(e):{error:lt}}async showRewardedAd(e){return this.supports.rewardedAds?Jl(e):{ok:false,error:lt}}async confirmCredits(e){return this.supports.creditsConfirm?Xl(e):{ok:false,error:lt}}async topUp(e){return this.supports.cryptoTopUp?Ql(e):{ok:false,error:lt}}openInvoice(e){let t=Gt();if(t?.openInvoice){t.openInvoice(e);return}this.openUrl(e);}openUrl(e){let t=Gt();if(t?.openTelegramLink&&/^https:\/\/t\.me\//i.test(e)){t.openTelegramLink(e);return}Rs()&&window.open(e,"_blank","noopener");}async share(e){let t=ti();if(t?.share)try{return await t.share({url:e.url||void 0,title:e.title,text:e.text}),"shared"}catch(i){if(i?.name==="AbortError")return "cancelled"}return await this.copyText(Ni(e))?"copied":"unavailable"}pickFiles(e){return us(e)}async shareFile(e){if(typeof document>"u"||typeof Blob>"u")return "unavailable";let t=new Blob([e.bytes],{type:e.mime}),i=ti();if(typeof File<"u"&&i?.share&&i.canShare){let r=new File([t],e.name,{type:e.mime});if(i.canShare({files:[r]}))try{return await i.share({files:[r],title:e.name}),"shared"}catch(o){if(o?.name==="AbortError")return "cancelled"}}let s=document.createElement("a");return s.href=URL.createObjectURL(t),s.download=e.name,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(s.href),3e4),"saved"}async copyText(e){let t=ti();if(t?.clipboard)try{return await t.clipboard.writeText(e),!0}catch{}return eg(e)}vibrate(e){try{ti()?.vibrate?.(cs(e));}catch{}}createWorker(e,t){return gs(e,t)}};function eg(n){if(typeof document>"u"||!document.body)return false;let e=document.createElement("textarea");e.value=n,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();let t=false;try{t=document.execCommand("copy");}catch{t=false;}return e.remove(),t}function Go(){let n=zo();return n?new _i(n):typeof window>"u"?new Fi:new Vi}var Fo="idos_acq",iu=["gclid","fbclid","ttclid","msclkid","yclid"],tg=["ref","r"],ig=["ref_","ref-","ref=","r_","r-"];var si=class{constructor(e){this.host=e;}host;capture(){let e=this.readFromEnvironment();sg(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=og(this.host.getDeviceModel());return s&&(i.OsVersion=s),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.host.storage.remove(Fo);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let i=nu(ru(t));if(i)return i}return Cs(t)}readFromEnvironment(){let e={},t=ru(this.host.getFullURL());ii(e,"UtmSource",t.get("utm_source")),ii(e,"UtmMedium",t.get("utm_medium")),ii(e,"UtmCampaign",t.get("utm_campaign")),ii(e,"UtmTerm",t.get("utm_term")),ii(e,"UtmContent",t.get("utm_content")),ii(e,"ClaimToken",t.get("idos_click"));for(let g of iu){let V=t.get(g);if(V){e.ClickID=V;break}}let i=this.host.getStartParameter()??"",s=ng(i);if(s){for(let g of rg)ii(e,g,s.get(ou[g])??null);for(let g of iu){let V=s.get(g);if(V){e.ClickID=V;break}}}let r=Cs(s?s.get("ref")??s.get("r")??"":i),o=nu(t),c=r||o;c&&(e.ReferralCode=c,e.ChannelHint=r?"telegram":"query");let h=this.host.getReferrer();return h&&(e.Referrer=h),e}read(){try{let e=this.host.storage.getString(Fo);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.host.storage.setString(Fo,JSON.stringify(e));}catch{}}};function sg(n){return !!(n.UtmSource||n.UtmMedium||n.UtmCampaign||n.ClickID||n.Referrer||n.ReferralCode||n.ClaimToken)}function ii(n,e,t){t&&(n[e]=t);}var su="a1_",ou={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},rg=Object.keys(ou);function ng(n){let e=(n||"").trim();if(!e.startsWith(su))return null;let t=e.slice(su.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),r=Uint8Array.from(s,h=>h.charCodeAt(0)),o=new TextDecoder().decode(r),c=new URLSearchParams(o);return [...c.keys()].length>0?c:null}catch{return null}}function ru(n){try{let e=n.indexOf("?");return new URLSearchParams(e>=0?n.slice(e):"")}catch{return new URLSearchParams}}function nu(n){for(let e of tg){let t=n.get(e);if(t)return Cs(t)}return null}function Cs(n){let e=(n||"").trim();if(!e)return null;for(let t of ig)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function og(n){let e=n||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var au="idos_usage_pending",lu="idos_usage_session",uu="idos_usage_closed_session",cu="idos_usage_new_session",pu="idos_usage_last_activity",ji=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;stopVisibility=null;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=!this.ctx.host.isVisible(),this.timer=setInterval(()=>this.tick(),200*1e3),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=e=>{if(!e){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,i=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,i,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(au),this.currentSessionSeconds=this.readNumber(lu),this.pendingClosedSessionSeconds=this.readNumber(uu),this.isNewSessionPending=this.readNumber(cu)!==0;let e=this.readNumber(pu);this.currentSessionSeconds>0&&e>0&&(Date.now()-e)/1e3>=1800&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,Math.floor(this.currentSessionSeconds)),this.currentSessionSeconds=0);}persist(){this.writeNumber(au,this.pendingSeconds),this.writeNumber(lu,this.currentSessionSeconds),this.writeNumber(uu,this.pendingClosedSessionSeconds),this.writeNumber(cu,this.isNewSessionPending?1:0),this.writeNumber(pu,Date.now());}readNumber(e){let t=this.ctx.host.storage.getString(e),i=t?Number(t):0;return Number.isFinite(i)&&i>0?i:0}writeNumber(e,t){try{this.ctx.host.storage.setString(e,String(Math.floor(t)));}catch{}}};function F(n){return {ok:true,data:n}}function u(n,e){return {ok:false,reason:n,error:e}}var a=u("unauthorized","Not logged in.");function ag(n){return n.ok}function lg(n){return !n.ok}var W=zod.z.union([zod.z.number(),zod.z.string()]).transform((n,e)=>{let t=typeof n=="string"?Number(n):n;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(n)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((n,e)=>{let t=typeof n=="number"?String(n):n.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(n)}`}),zod.z.NEVER):t}),p=zod.z.string();var No=zod.z.object({Type:Ci.nullish(),CurrencyID:zod.z.string().nullish(),Amount:W.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),ug=zod.z.object({Type:ms.nullish(),EntityID:zod.z.string()}),cg=zod.z.object({Address:ug.nullish(),Amount:W.nullish(),Source:zod.z.string().nullish()}),pe=zod.z.object({Entries:zod.z.array(No).nullish(),EventTokens:zod.z.array(cg).nullish()}),du=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:pe.nullish()}),Q=zod.z.object({Standard:pe.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(du).nullish()}),zt=zod.z.object({Standard:pe.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(du).nullish()}),O=zod.z.object({Grant:Q.nullish(),Consume:zt.nullish()}),Mt=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:O.nullish(),ToResult:O.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:pe.nullish()});var pg=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),dg={Completed:"Completed",Started:"Started",StepReached:"StepReached"},hg=zod.z.object({FlowIDs:zod.z.array(zod.z.string()).nullish(),Mode:zod.z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:zod.z.string().nullish(),Negate:zod.z.boolean().nullish(),SkippedCountsAsCompleted:zod.z.boolean().nullish()}).passthrough(),Z=zod.z.object({Segments:zod.z.array(zod.z.string()).nullish(),MinPremiumTier:zod.z.number().nullish(),RequiredPremiumIDs:zod.z.array(zod.z.string()).nullish(),MinLevel:zod.z.number().nullish(),MaxLevel:zod.z.number().nullish(),Countries:zod.z.array(zod.z.string()).nullish(),RegisteredWithinDays:zod.z.number().nullish(),ActiveWithinDays:zod.z.number().nullish(),Experiment:pg.nullish(),Tutorial:hg.nullish(),Platforms:zod.z.array(ds).nullish()}).passthrough();var Se=zod.z.object({TotalCap:zod.z.number().nullish(),DailyCap:zod.z.number().nullish(),DailyWeightCap:zod.z.number().nullish(),PerActivationCap:zod.z.number().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish()}).passthrough();var mg=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),fg=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),gg=zod.z.object({AnchorUtc:zod.z.string().nullish(),MaxCycles:zod.z.number().nullish(),PauseBetweenPhasesSec:zod.z.number().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish()}).passthrough();zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();var yg=zod.z.object({Reset:zod.z.string().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:zod.z.string().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();zod.z.object({SourceType:zod.z.string().nullish(),TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var ut=zod.z.object({SourceType:zod.z.string().nullish(),BaseWeight:zod.z.number().nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish(),TileTypeFilter:zod.z.array(zod.z.string()).nullish(),TileIndexFilter:zod.z.array(zod.z.number()).nullish(),ChanceOutcomeFilter:zod.z.array(zod.z.string()).nullish(),OutcomeFilter:zod.z.array(zod.z.string()).nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Limits:Se.nullish()}).passthrough(),Re=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:fg.nullish(),Chain:gg.nullish(),Cyclic:yg.nullish(),ActivationTriggers:zod.z.array(ut).nullish(),Relative:mg.nullish()}).passthrough();var Rg={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},Cg=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Sg={Step:"Step",Linear:"Linear",Geometric:"Geometric"},xg=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),bg=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),je=zod.z.object({Base:zod.z.number().nullish(),Shape:Cg.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(bg).nullish(),Interpolation:xg.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var Dg=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:Q.nullish()}).passthrough(),Pg=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),_o=zod.z.object({Bundles:zod.z.array(Dg).nullish(),Multipliers:zod.z.array(Pg).nullish()}).passthrough();var Ig=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Ss=zod.z.object({Source:Ig.nullish(),SourceKey:zod.z.string().nullish(),Curve:je.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:pe.nullish(),ExcludeRewards:pe.nullish()}).passthrough(),hu=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),_e=zod.z.object({MilestoneID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredProgress:zod.z.number().nullish(),Rewards:Q.nullish(),BonusRewards:Q.nullish(),SeasonTierRewards:_o.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),xi=zod.z.object({Milestones:zod.z.record(zod.z.string(),_e).nullish()}).passthrough();var K=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var vg=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),ri=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxBalance:zod.z.number().nullish(),MaxPerGrant:zod.z.number().nullish(),DailyEarnCap:zod.z.number().nullish(),BurnOnEventEnd:zod.z.boolean().nullish(),BurnConversion:vg.nullish()}).passthrough();var Tg=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),mu=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:Tg.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(n=>n),H=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),mu).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var we=n=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:n.nullish()}),bt=n=>zod.z.object({ServerTimeUtc:p,Items:zod.z.array(we(n)),Resources:O.nullish(),Inventory:H.nullish()});var Ag={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},fu=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),wg=zod.z.object({}).passthrough().transform(n=>n),kg=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:p.nullish(),CycleEndUtc:p.nullish(),PointsTotalEarned:W.nullish(),PointsCurrent:W.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Vo=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:W.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:fu}),gu=zod.z.object({State:wg.nullish(),PointsTracks:zod.z.record(zod.z.string(),kg).nullish()}),jo=zod.z.object({ServerTimeUtc:p,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:fu.nullish(),Resources:O.nullish(),Inventory:H.nullish()}),Wo=zod.z.object({ServerTimeUtc:p,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:W.nullish(),Resources:O.nullish(),Inventory:H.nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),yu=zod.z.object({ServerTimeUtc:p,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:O.nullish(),Inventory:H.nullish()}),Ru=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(Vo).nullish()}),Cu=zod.z.array(we(jo)),Su=zod.z.array(we(Wo)),zg={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Mg=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Og={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Eg=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),xu=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:Mg.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(ut).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),Ho=zod.z.object({Milestones:K.nullish(),Linking:K.nullish(),Availability:K.nullish(),Reward:K.nullish(),Objectives:K.nullish()}).passthrough(),Ug=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),bu=zod.z.object({CycleIDs:zod.z.array(zod.z.string()).nullish(),GroupID:zod.z.string().nullish(),PhaseIDs:zod.z.array(zod.z.string()).nullish(),RequiredQuestIDs:zod.z.array(zod.z.string()).nullish(),PrerequisiteMode:Eg.nullish()}).passthrough(),Du=zod.z.object({Schedule:Re.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Pu=zod.z.object({Grant:Q.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),qg=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Ug.nullish(),Linking:bu.nullish(),Availability:Du.nullish(),Objectives:zod.z.record(zod.z.string(),xu).nullish(),Reward:Pu.nullish(),Presets:Ho.nullish()}).passthrough(),Lg=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:Z.nullish(),Reward:Q.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Bg=zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Gate:Z.nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:Ho.nullish(),PointsToken:ri.nullish()}).passthrough(),Gg=zod.z.object({Milestones:zod.z.record(zod.z.string(),xi).nullish(),Linking:zod.z.record(zod.z.string(),bu).nullish(),Availability:zod.z.record(zod.z.string(),Du).nullish(),Reward:zod.z.record(zod.z.string(),Pu).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),xu)).nullish()}).passthrough(),Fg=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Gate:Z.nullish(),PointsToken:ri.nullish(),GroupCompletions:zod.z.record(zod.z.string(),Lg).nullish(),Phases:zod.z.record(zod.z.string(),Bg).nullish(),Presets:Ho.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),bs=zod.z.object({Cycles:zod.z.record(zod.z.string(),Fg).nullish(),Quests:zod.z.record(zod.z.string(),qg).nullish(),Presets:Gg.nullish()}).passthrough(),Rt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var Ng={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},_g=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),Vg={Never:"Never",OnRequest:"OnRequest",Always:"Always"},jg=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),Wg={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},Hg=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),Kg={GameLoop:"GameLoop"},Qg={Raid:"Raid",Attack:"Attack"},$g=zod.z.object({Title:zod.z.string().nullish(),TitleKey:zod.z.string().nullish(),Body:zod.z.string().nullish(),BodyKey:zod.z.string().nullish(),AnchorID:zod.z.string().nullish(),HighlightTarget:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),UiHint:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Jg=zod.z.object({Mode:_g.nullish(),Triggers:zod.z.array(ut).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),Zg=zod.z.object({Grant:Q.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Yg=zod.z.object({TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),RandomActionType:zod.z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),Xg=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:Yg.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),ey=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),Ko=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:$g.nullish(),Completion:Jg.nullish(),Effects:Zg.nullish(),Script:Xg.nullish(),Policy:ey.nullish()}).passthrough(),ty=zod.z.object({DisplayName:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),Description:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Iu=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:ut.nullish()}).passthrough(),vu=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:jg.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Tu=zod.z.object({Grant:Q.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),iy=zod.z.object({Availability:K.nullish(),Policy:K.nullish(),Reward:K.nullish(),Steps:K.nullish()}).passthrough(),sy=zod.z.object({FlowID:zod.z.string().nullish(),Identity:ty.nullish(),Availability:Iu.nullish(),Policy:vu.nullish(),Steps:zod.z.record(zod.z.string(),Ko).nullish(),Reward:Tu.nullish(),Presets:iy.nullish()}).passthrough(),ry=zod.z.object({BlockingFlowIDs:zod.z.array(zod.z.string()).nullish(),BlockedModules:zod.z.array(zod.z.string()).nullish(),BlockedActions:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),BlockBeforeStart:zod.z.boolean().nullish(),SkipLiftsBlock:zod.z.boolean().nullish()}).passthrough(),ny=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:ry.nullish()}).passthrough(),oy=zod.z.object({Availability:zod.z.record(zod.z.string(),Iu).nullish(),Policy:zod.z.record(zod.z.string(),vu).nullish(),Reward:zod.z.record(zod.z.string(),Tu).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Ko)).nullish()}).passthrough(),Au=zod.z.object({Flows:zod.z.record(zod.z.string(),sy).nullish(),Settings:ny.nullish(),Presets:oy.nullish()}).passthrough(),ay=zod.z.object({}).passthrough().transform(n=>n),wu=zod.z.object({FlowID:zod.z.string(),Status:Hg,CurrentStepID:zod.z.string().nullish(),CurrentStep:Ko.nullish(),TotalSteps:zod.z.number(),CompletedSteps:zod.z.number(),CanSkip:zod.z.boolean(),RewardClaimed:zod.z.boolean(),RewardPending:zod.z.boolean(),VariantID:zod.z.string().nullish()}).passthrough(),Ds=zod.z.object({State:ay.nullish(),Flows:zod.z.array(wu).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Nt=zod.z.object({Flow:wu.nullish()}).passthrough(),ku=zod.z.object({FlowID:zod.z.string().nullish(),Granted:O.nullish()}).passthrough(),zu=zod.z.array(we(Nt)),Mu=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),ct={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Ps(n){return Array.isArray(n)?n.filter(e=>e!==null).map(Ps):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==null).map(([e,t])=>[e,Ps(t)])):n}var Is=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var vs=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Ou(n){return n===429||n>=500&&n<=599}function Ts(n,e=Math.random){let t=Math.min(500*Math.pow(2,n-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function _t(n){return new Promise(e=>setTimeout(e,n))}var Eu=15e3;async function Uu(n){try{let t=JSON.parse(await n.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(n.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function qu(n,e=Math.random){return n+10+Math.min(250,n*.2)*e()}function Lu(n,e=Math.random){let t=n<=1?1500:n===2?4e3:6e3;return t+t*.1*e()}var Qo=15,Bu=1e3,As=class{constructor(e=Qo,t=()=>Date.now(),i=_t){this.perSecond=e;this.now=t;this.wait=i;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=Bu;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(Bu-(e-this.starts[0])+5);}}};var ly=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function Di(n){if(!n)return null;let e=ly.exec(n);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let r=new ni__default.default(i),o=new ni__default.default(s),c=o.minus(ni__default.default.max(r,0));return c.lte(0)?null:{currencyID:t,required:o.toNumber(),available:r.toNumber(),missing:c.toNumber(),missingAmount:c.toFixed()}}var uy=12e3,cy=new Set(["RelatedEntityID"]);function py(n,e){if(e===null||typeof e!="object"||Array.isArray(e))return n;let t={};for(let[i,s]of Object.entries(e))cy.has(i)||(t[i]=s);try{return `${n}|${JSON.stringify(t)}`}catch{return n}}var dy=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(Vo).nullish(),TutorialProgress:zod.z.array(Mu).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),ws=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new vs;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new Is(e.throttleMs),this.pacer=new As(e.maxRequestsPerSecond??Qo),this.clientPlatform=e.clientPlatform??Ee.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,s={}){let r=s.throttleKey??py(e,t);if(!this.throttler.tryAcquire(r))return u("throttled","Throttled");if(!this.inflight.add(r))return u("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,c=JSON.stringify(t),h=s.ticket??null,g=s.silent??!1,V=s.timeoutMs??uy,oe=s.autoRetry??!0,be=!1,ue=!1,ge=0;for(;;){let At;s.keepalive||await this.pacer.take();try{At=await this.doFetch(o,c,h,V,s.keepalive??!1);}catch{if(oe&&ge<3){ge++,await _t(Ts(ge));continue}return this.connectionFailure("Internet Connection Error",g)}let tt=At.status;if(tt>=200&&tt<300){let ne=!ue&&this.cryptoTopUpHandler!==null,Ae=await this.parseSuccess(At,i,g,e,ne);if(!Ae.ok&&ne){let de=Di(Ae.error);if(de){if(ue=!0,await this.runTopUp(de))continue;g||this.emitter.emit("error:global",Ae.error);}}return Ae}if(tt===401){if(!be&&this.sessionRefreshHandler){be=!0;let ne=null;try{ne=await this.sessionRefreshHandler();}catch{ne=null;}if(ne){h=ne;continue}}return this.emitter.emit("auth:unauthorized",void 0),u("unauthorized","Unauthorized")}if(Ou(tt)){let ne=tt===429?await Uu(At):null;if(ne!==null&&ne>Eu)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ne/1e3)} s`,g);if(oe&&ge<3){ge++,await _t(ne!==null?qu(ne):tt===429?Lu(ge):Ts(ge));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${tt})`,g)}let Ei="";try{Ei=await At.text();}catch{}if(tt===409&&/operation in progress/i.test(Ei)&&oe&&ge<3){ge++,await _t(Ts(ge));continue}return this.handleWebError(Ei,tt,g)}}finally{this.inflight.remove(r),this.lowerBusy();}}async doFetch(e,t,i,s,r=false){let o=new AbortController,c=setTimeout(()=>{o.abort();},s);try{let h={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(h.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:h,signal:o.signal,...r?{keepalive:!0}:{}})}finally{clearTimeout(c);}}async parseSuccess(e,t,i,s,r=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",i)}let c;try{c=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",i)}let h=dy.safeParse(c);if(!h.success)return this.globalError("Malformed response envelope",i);if(!h.data.Success){let ue=h.data.Error??"Server returned Success=false",ge=r&&Di(ue);return !i&&!ge&&this.emitter.emit("error:global",ue),u("server",ue)}let g=h.data.StateVersions;g&&Object.keys(g).length>0&&this.emitter.emit("user:stateVersions",{epoch:h.data.StateEpoch??null,versions:g});let V=h.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);let oe=h.data.TutorialProgress;oe&&oe.length>0&&this.emitter.emit("tutorial:systemProgress",oe);let be=t.safeParse(h.data.Data);if(!be.success){let ue=t.safeParse(Ps(h.data.Data));ue.success&&(be=ue);}if(!be.success){let ue=`Validation error (${s}): ${be.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",ue),i||this.emitter.emit("error:global",ue),u("validation",ue)}return F(be.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),u("server","PLAY_ACCESS_REQUIRED");s=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),u("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),u("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),u("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function Pi(n){return (typeof n=="string"?n:n.toISOString()).slice(0,10)}function Wi(n){return `${Pi(n)}T00:00:00.000Z`}function Gu(n){let e=new Date(n);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Fu(n,e){return new Date(n.getTime()+e*6e4).toISOString()}function Zo(n,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;n.InventoryV2??={};let r=n.InventoryV2,o=i.toISOString(),c=new Map,h=new Map,g=new Map,V=new Map,oe=new Map,be=new Map,ue=new Map,ge=new Map,At=e.Grant?.PremiumTiers??[],tt=At.length;for(let ne=0;;ne++){let Ae,de;if(ne===0)Ae=e.Grant?.Standard?.Entries,de=false;else if(ne-1<tt)Ae=At[ne-1]?.Resources?.Entries,de=false;else if(ne===1+tt)Ae=e.Consume?.Standard?.Entries,de=true;else break;if(Ae)for(let ce of Ae){if(ce.Type==null)continue;let he=Math.max(0,ce.Amount??0);if(!(he<=0))switch(ce.Type){case "VirtualCurrency":{if(!ce.CurrencyID)continue;let me=de?h:c;me.set(ce.CurrencyID,(me.get(ce.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!ce.CurrencyID)continue;let me=de?V:g;me.set(ce.CurrencyID,(me.get(ce.CurrencyID)??new ni__default.default(0)).plus(he));break}case "Item":{if(!ce.ItemID)continue;let me=my(t,ce.CatalogID,ce.ItemID),Pe=(me?me.IsStackable??true:true)?de?be:oe:de?ge:ue;Pe.set(ce.ItemID,(Pe.get(ce.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=c.size>0||h.size>0,s.vcChanged){r.VirtualCurrencies??={};for(let ne of new Set([...c.keys(),...h.keys()])){let Ae=c.get(ne)??0,de=h.get(ne)??0,ce=Ae-de,he=r.VirtualCurrencies[ne];he?(he.Amount+=ce,he.UpdatedAt=o,he.Daily&&Pi(he.Daily.PeriodStartUtc)===Pi(i)?(he.Daily.Earned+=Ae,he.Daily.Spent+=de):he.Daily={PeriodStartUtc:Wi(i),Earned:Ae,Spent:de}):r.VirtualCurrencies[ne]={Amount:ce,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:Wi(i),Earned:Ae,Spent:de}};}}if(s.ccChanged=g.size>0||V.size>0,s.ccChanged){r.CryptoCurrencies??={};for(let ne of new Set([...g.keys(),...V.keys()])){let Ae=g.get(ne)??new ni__default.default(0),de=V.get(ne)??new ni__default.default(0),ce=Ae.minus(de),he=r.CryptoCurrencies[ne];he?(he.Amount=new ni__default.default(he.Amount).plus(ce).toString(),he.UpdatedAt=o):r.CryptoCurrencies[ne]={Amount:ce.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(s.itemsChanged=oe.size>0||be.size>0||ue.size>0||ge.size>0,s.itemsChanged){r.Items??={},r.UnstackableItems??={};let ne=r.UnstackableItems,Ae=new Set([...oe.keys(),...be.keys(),...ue.keys(),...ge.keys()]);for(let de of Ae){let ce=(oe.get(de)??0)-(be.get(de)??0),he=(ue.get(de)??0)-(ge.get(de)??0),me=ce+he,at=r.Items[de];at?(ce!==0&&(at.StackableAmount+=ce),he!==0&&(at.UnstackableAmount+=he),me!==0&&(at.TotalAmount+=me)):r.Items[de]={StackableAmount:Math.max(0,ce),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,me)};}for(let[de,ce]of ge){if(ce<=0)continue;let he=Object.values(ne).filter(me=>me.ItemID===de&&me.EquippedSlot==null&&(me.ExpiresAt==null||new Date(me.ExpiresAt)>i)).sort(hy).slice(0,ce).map(me=>me.ItemInstanceID);for(let me of he)delete ne[me];}for(let[de,ce]of ue){let he=fy(t,de);for(let me=0;me<ce;me++){let at=G();ne[at]={ItemInstanceID:at,ItemID:de,CatalogID:he,RemainingUses:1,AcquiredAt:o};}}}n.EventToken??={};let Ei=n.EventToken;for(let ne=0;;ne++){let Ae,de;if(ne===0)Ae=e.Grant?.Standard?.EventTokens,de=false;else if(ne-1<tt)Ae=At[ne-1]?.Resources?.EventTokens,de=false;else if(ne===1+tt)Ae=e.Consume?.Standard?.EventTokens,de=true;else break;if(!(!Ae||Ae.length===0))for(let ce of Ae){let he=ce.Address;if(!he||he.Type==null)continue;let me=ce.Amount??0;if(me<=0)continue;let at=gy(Ei,he.Type);if(!at)continue;let Pe=at[he.EntityID];Pe||(Pe={},at[he.EntityID]=Pe),Pe.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Pe.Daily??={Date:Wi(i),TotalEarned:0},Pe.Meta??={};let Ui=ce.Source&&ce.Source.length>0?ce.Source:"CustomAction";de?(Pe.Balance.Current-=me,Pe.Balance.TotalSpent+=me):(Pe.Balance.Current+=me,Pe.Balance.TotalEarned+=me,Pi(Pe.Daily.Date)!==Pi(i)&&(Pe.Daily={Date:Wi(i),TotalEarned:0}),Pe.Daily.TotalEarned+=me,Pe.Daily.EarnedBySource??={},Pe.Daily.EarnedBySource[Ui]=(Pe.Daily.EarnedBySource[Ui]??0)+me,Pe.Daily.TriggersBySource??={},Pe.Daily.TriggersBySource[Ui]=(Pe.Daily.TriggersBySource[Ui]??0)+1,Pe.Daily.LastTriggerBySource??={},Pe.Daily.LastTriggerBySource[Ui]=o,Pe.Meta.JoinedAtUtc||(Pe.Meta.JoinedAtUtc=o),Pe.Meta.LastEarnedAtUtc=o),s.tokensChanged=true;}}return s}function hy(n,e){return n.AcquiredAt!==e.AcquiredAt?n.AcquiredAt<e.AcquiredAt?-1:1:n.ItemInstanceID===e.ItemInstanceID?0:n.ItemInstanceID<e.ItemInstanceID?-1:1}function my(n,e,t){let i=n?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let r=s.Items?.[t];if(r)return r}}}function fy(n,e){let t=n?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function gy(n,e){switch(e){case "TimedEvent":return n.TimedEvent??={};case "Quest":return n.Quest??={};case "Leaderboard":return n.Leaderboard??={};case "CoopEvent":return n.CoopEvent??={};case "Season":return n.Season??={};default:return null}}function Nu(n,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},r=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let h of Object.values(s))h?.ItemID&&o.add(h.ItemID);for(let h of r){let g=n[h]?.ItemID;g&&o.add(g);}if(o.size===0)return i;let c=h=>r.has(h)||h in s;if(e){for(let[h,g]of Object.entries(e))h in n||c(h)||g&&o.has(g.ItemID)&&i.drop.push(h);for(let[h,g]of Object.entries(n))h in e||c(h)||g&&o.has(g.ItemID)&&(i.restore[h]=g);}return i}function Yo(n,e){return n===e||n.startsWith(`${e}:`)}var zs=class n{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){n.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];n.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){n.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let s=Zo(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let r=this.currentState,o={...r.InventoryV2?.UnstackableItems??{}},c=Zo(r,e,i,s),h=Nu(o,r.InventoryV2?.UnstackableItems,t),g=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],oe=h.drop.length>0||Object.keys(h.restore).length>0||g.length>0||V.length>0;if(oe){r.InventoryV2??={},r.InventoryV2.UnstackableItems??={};let be=r.InventoryV2.UnstackableItems;for(let ue of h.drop)delete be[ue];for(let[ue,ge]of Object.entries(h.restore))be[ue]=ge;for(let[ue,ge]of g)be[ue]=ge;for(let ue of V)delete be[ue];}this.emitResourceChanges(c,oe);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let r=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof ni__default.default?t:new ni__default.default(t),c=s===void 0?new ni__default.default(0):s instanceof ni__default.default?s:new ni__default.default(s),h=i??new Date().toISOString(),g=r[e];g?(g.Amount=new ni__default.default(g.Amount).plus(o).toString(),c.isZero()||(g.Frozen=new ni__default.default(g.Frozen??0).plus(c).toString()),g.UpdatedAt=h):r[e]={Amount:o.toString(),Frozen:c.toString(),CreatedAt:h,UpdatedAt:h},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,r=s[e];r||(r={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=r),r.TotalPurchases+=t,r.LastPurchasedAt=i,i>=r.DailyResetUtc?(r.DailyPurchases=t,r.DailyResetUtc=Gu(i)):r.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let r=new Date().toISOString();for(let o of t)o.RuleID&&(s.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:r});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchRewardWindowState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Windows??={},this.currentState.Reward.Windows[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let r=s.Cycles[t];if(!r)return;r.Quests??={};let o=r.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let r=s.PermanentQuests[e]??={QuestID:e,Status:i};r.Status=i,i==="Claimed"&&(r.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,r=t[s]??={};r.Balance??={Current:0,TotalEarned:0,TotalSpent:0},r.Balance.Current=i.PointsCurrent??0,r.Balance.TotalEarned=i.PointsTotalEarned??0,r.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(r.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let r=s.Steps[i.StepID]??={StepID:i.StepID};r.Progress=i.Progress,i.Completed&&(r.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let r=t.Cycles[i.CycleID];if(!r)continue;r.Quests??={},s=r.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let r=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};r.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(r.Completed=true,r.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(Yo(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[r,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((s?r!==s:!Yo(r,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let r=this.activeEventsCache?.ActiveEvents;if(r)for(let o of r)o.Type!==e||o.TimedEventID!==t||s&&o.TokenEntityID&&o.TokenEntityID!==s||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,s){if(!e)return;let r=this.ensureLeaderboardProgress(e);(r.ScoreCycleVersion??0)<s&&(r.ScoreEarnedThisCycle=0,r.ClaimedMilestoneIDs=[],r.BracketID=null),r.CurrentScore=t,r.ScoreEarnedThisCycle=(r.ScoreEarnedThisCycle??0)+i,r.ScoreCycleVersion=s,r.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let s=false;for(let r of Object.values(i))for(let o of Object.values(r.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[s,r]of Object.entries(e.ChangedInstances??{}))t[s]=r,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(i)){let r=i[s];r&&r.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,s,r){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,c={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:r??null};if(e==="Private")o.Private??={},o.Private[t]=c;else if(e==="Public")o.Public??={},o.Public[t]=c;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let s=i.BuildingStates.find(r=>r.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},r=s.PendingWithdrawals??[];t.size>0&&(r=r.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!r.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(r=[...r,i]),s.PendingWithdrawals=r;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var Ms=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,i]of Object.entries(e))this.sections.has(t)||this.sections.set(t,i);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let i=this.config?.[e];return i??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var Os=class{user;config;constructor(e){this.user=new zs(e),this.config=new Ms;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function yy(n){return n}var Ry=0,Cy=1500,Sy=3,Us=class{constructor(e,t,i=null,s="",r="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=s;this.loginMode=r;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return F(void 0);let i=Date.now(),s=[],r=[];for(let h of new Set(e)){let g=this.rules.get(h);if(g&&(t?.force||g.needsServer(i))){s.push(this.runRule(h,g));continue}(t?.force||!this.state.isStateFresh(h,t?.maxAgeMs))&&r.push(h);}let c=(await Promise.all([...s,r.length>0?this.queueSlice(r):Promise.resolve(F(void 0))])).find(h=>!h.ok);return c&&!c.ok?c:F(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},Ry),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(s=>i=s);try{let s=this.state?await this.state.readStateSlice(e):F(void 0),r=s.ok?F(void 0):s;for(let o of t)o(r);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=Es(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let g=this.fresh(s,i?.maxAgeMs);if(g)return F(g.data);let V=this.loginFailures.get(s);if(V)return this.loginFailures.delete(s),V;let oe=this.inflight.get(s);if(oe)return oe}let r=this.generation.get(s)??0,o=Date.now(),h=t().then(g=>{if(!g.ok)return g;let V=Date.now();if((this.generation.get(s)??0)===r)return this.entries.set(s,{data:g.data,storedAt:V,expiresAt:Xo(e,g.data,V)}),g;let oe=this.entries.get(s);if(oe&&oe.storedAt>=o)return g;let be=Xo(e,g.data,V);return this.entries.set(s,{data:g.data,storedAt:V,expiresAt:Math.min(be??1/0,V+Cy)}),g}).finally(()=>{this.inflight.get(s)===h&&this.inflight.delete(s);});return this.inflight.set(s,h),h}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let s=t.Key?t.Key:void 0,r=Es(i.view,s);if(!t.Success){this.loginFailures.set(r,u("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(r),i.apply(o.data,s),this.put(i.view,o.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let r=_u({Name:s,Key:t});this.used.get(r)?.n!==this.session&&(this.used.set(r,{Name:s,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>Sy||this.used.set(_u(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(Es(e,t))?.data}put(e,t,i){this.register(e);let s=Es(e,i);this.bump(s);let r=Date.now();this.entries.set(s,{data:t,storedAt:r,expiresAt:Xo(e,t,r)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===i||s.startsWith(`${i}|`))&&this.drop(s);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let s=Date.now();if(!(i.expiresAt!==null&&s>=i.expiresAt)&&!(t!==void 0&&s-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(s=>t.has(s))&&this.invalidate(i);}};function Es(n,e){return e===void 0?n.key:`${n.key}|${e}`}function _u(n){return n.Key?`${n.Name}|${n.Key}`:n.Name}function Xo(n,e,t){let i=n.expiresAt?.(e)??null,s=n.ttlMs!==void 0?t+n.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var qs=class{constructor(e,t){this.storage=e;this.authTypeKey=`Saved_AuthType_${t}`,this.emailKey=`Saved_Auth_Email_${t}`,this.passwordKey=`Saved_Auth_Password_${t}`,this.refreshTokenKey=`Saved_Auth_RefreshToken_${t}`;}storage;authTypeKey;emailKey;passwordKey;refreshTokenKey;get lastAuthType(){let e=this.storage.getString(this.authTypeKey);return xy(e)?e:ze.None}saveAuthType(e){this.storage.setString(this.authTypeKey,e);}get savedEmail(){return this.storage.getString(this.emailKey)??""}get savedPassword(){return this.storage.getString(this.passwordKey)??""}saveEmailAndPassword(e,t){this.storage.setString(this.emailKey,e),this.storage.setString(this.passwordKey,t);}get savedRefreshToken(){return this.storage.getString(this.refreshTokenKey)??""}saveRefreshToken(e){e?this.storage.setString(this.refreshTokenKey,e):this.storage.remove(this.refreshTokenKey);}clear(){this.storage.remove(this.authTypeKey),this.storage.remove(this.emailKey),this.storage.remove(this.passwordKey),this.storage.remove(this.refreshTokenKey);}};function xy(n){return n!==null&&Object.values(ze).includes(n)}var by=8,Dy=100,Py=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,Ls=["GameLoop"];function Iy(n){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(n)}var Bs=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=ze.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let s=this.authContext;if(!s)return a;let r=this.baseRequest();r.UserID=s.userID,r.ClientSessionTicket=s.clientSessionTicket,r.WalletAddress=e,r.NetworkID=t,i&&(r.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(r);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return a;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(i);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.host.getDeviceID(),e.Device=this.ctx.host.getDeviceModel(),e.Platform=this.ctx.host.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(ze.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.host.getTelegramInitDataRaw();if(!e)return u("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let s=await this.ctx.api.authentication.loginWithEmail(i);if(!s.ok)return s;this.applyAuthContext(s.data);let r=await this.fetchAndApplyClientState(ze.Email);return r.ok&&this.keepEmailCredentials(e,t),r}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.host.getDeviceID(),i.Device=this.ctx.host.getDeviceModel(),i.Platform=this.ctx.host.getPlatform();let s=await this.ctx.api.authentication.registerWithEmail(i);return s.ok?(this.pendingRegistration={email:e,password:t},F({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!s.ok)return s;this.applyAuthContext(s.data);let r=await this.fetchAndApplyClientState(ze.Email);return r.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,r}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?F(void 0):i}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let i=await this.ctx.api.authentication.loginWithGoogle(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Google)):i}async loginWithApple(e,t){if(!e?.trim())return u("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(ze.Apple)):s}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=i,s.Platform=this.ctx.host.getPlatform(),s.Device=this.ctx.host.getDeviceModel(),s.DeviceID=this.ctx.host.getDeviceID();let r=await this.ctx.api.authentication.loginWithWallet(s);return r.ok?(this.applyAuthContext(r.data),this.fetchAndApplyClientState(ze.Wallet)):r}async loginWithSsoCode(e){if(!e)return u("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.host.getDeviceID(),t.Device=this.ctx.host.getDeviceModel(),t.Platform=this.ctx.host.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.iDosGames)):i}async loginWithPlatformGameTicket(e){if(!e)return u("client","Platform game ticket is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.PlatformGameTicket=e;let i=await this.ctx.userService.prepareLoginClientState(Ls,Ls);t.ClientState=i.request;let s=await this.ctx.api.authentication.resolvePlatformGameSession(t);if(!s.ok)return s;this.applyAuthContext(s.data),this.platformGameSession=true;let r=s.data.ClientState;return this.fetchAndApplyClientState(ze.iDosGames,r?()=>i.finish(r):void 0)}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=i,this.ctx.api.authentication.resetPassword(s)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==ze.None?e:ze.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let s=await this.ctx.api.authentication.refreshSession(i);return s.ok?(this.applyRefresh(s.data),"ok"):(Iy(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case ze.Email:return this.loginWithEmail(t,i);case ze.Device:case ze.None:return this.loginWithDeviceID();case ze.Telegram:return this.loginWithTelegram();default:return Promise.resolve(u("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;if(this.platformGameSession){this.refreshing=true;try{let t=await this.ctx.host.signIn(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let s=await this.ctx.api.authentication.resolvePlatformGameSession(i);return s.ok?(this.applyAuthContext(s.data),this.platformGameSession=!0,s.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==ze.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===ze.None)return null;this.refreshing=true;try{return (await this.replay(e,this.sessionEmail||this.ctx.authStore.savedEmail,this.sessionPassword||this.ctx.authStore.savedPassword)).ok&&this.authContext?this.authContext.clientSessionTicket:null}catch{return null}finally{this.refreshing=false;}}logout(){this.authContext=null,this.playAccessStatus=null,this.forgetSession(),this.ctx.authStore.clear(),this.ctx.data.reset(),this.ctx.emitter.emit("auth:loggedOut",void 0);}static isValidEmail(e){return e.length>0&&Py.test(e)}static isValidPasswordLength(e){return e.length>=by&&e.length<=Dy}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=ze.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e,t){let i=t?await t():await this.ctx.userService.getClientStateExcept(Ls,Ls);return i.ok&&(this.sessionAuthType=e,this.rememberSession?(this.ctx.authStore.saveAuthType(e),this.ctx.authStore.saveRefreshToken(this.sessionRefreshToken)):this.ctx.authStore.clear(),this.ctx.emitter.emit("auth:loggedIn",void 0)),i}};var vy="idos:cfg",Ii=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Vu(t)}`:e&&e.length>0?`f:${Vu(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${vy}:${this.titleId}:${e}`}};function Vu(n){return [...n].map(e=>e.toLowerCase()).sort().join(",")}var ju="idos:loc",vi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[s,r]of Object.entries(t))typeof r=="number"&&r>0&&(i[s]=r);return i}catch{return {}}}async noteVersion(e,t){let i=await this.readVersions();i[e]!==t&&(i[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(i)));}keyOf(e){return `${ju}:${this.titleId}:${e}`}versionsKey(){return `${ju}:${this.titleId}:versions`}};var Ty="idos:sec",Gs=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let i=JSON.parse(t);return !i||typeof i!="object"||i.v!==e||!i.s||typeof i.s!="object"?{}:i.s}catch{return {}}}async write(e,t){try{let i={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(i));}catch{}}keyOf(){return `${Ty}:${this.titleId}`}};var Ay="idos:state",Fs=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,s){if(!(!e||!t))try{let r={e:t,v:i,s};await this.storage.set(this.keyOf(e),JSON.stringify(r));}catch{}}keyOf(e){return `${Ay}:${this.titleId}:${e}`}};function wy(n,e){if(!n)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return n;let i={};for(let[s,r]of Object.entries(n))t.has(s.toLowerCase())||(i[s]=r);return i}function ea(n,e,t,i){let s={...n??{}};if(!e||!t||!i)return s;for(let[r,o]of Object.entries(t))i[r]===o&&r in e&&(s[r]=e[r]);return s}function ky(n){return {...n??{}}}function ta(n){return typeof n.StateEpoch=="string"&&n.StateEpoch.length>0?n.StateEpoch:null}var Ns=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let s=this.confirmedAt[e];return s===void 0?false:t===void 0||i-s<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=wy(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let r=Object.keys(this.versions);this.reset(e),this.notify(r);}return}let i=Date.now(),s=[];for(let[r,o]of Object.entries(t)){let c=this.versions[r];c!==o&&(c!==void 0&&o===c+1?(this.versions[r]=o,this.confirmedAt[r]=i):(delete this.versions[r],delete this.confirmedAt[r]),s.push(r),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=ky(t);let s=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=s;this.dirty=true;let r=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&r.add(o);this.notify([...r]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[r,o]of Object.entries(t??{}))this.versions[r]!==o&&s.push(r),this.versions[r]=o,this.confirmedAt[r]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Wu=u("server","Title configuration is unavailable (CDN and API both failed)."),_s=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:G()}:null}get configCache(){return this.cache??=new Ii(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new vi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new Gs(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new Ns(new Fs(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return a;let t=Ii.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let r=await this.ctx.api.user.getClientState(e);if(!r.ok)return r;let o=await this.resolveTitleConfig(r.data,t,i,{Fields:e.TitleFields});return o==null?Wu:(this.finishStateHandshake(r.data,s),await this.restoreSections(r.data.TitleConfigVersion,o),await this.applyClientState(r.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(r.data.Views),await this.applyLocalization(r.data.Localization),await this.flushState(s),r)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let r=this.stateStore.currentEpoch;r&&(e.KnownStateEpoch=r);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=ea(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=ta(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,i,s){let r=e.TitleConfigVersion;if(i&&r&&i.v===r)return i.c;if(e.TitleConfigUrl){let c=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(c!=null)return r&&await this.configCache.write(t,r,c),c}let o=await this.fetchConfigFromApi(s);return o!=null?(r&&await this.configCache.write(t,r,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return a;let s=await this.prepareClientStateExcept(i,e,t,true),r=await this.ctx.api.user.getClientStateExcept(i);return r.ok?this.finishClientStateExcept(s,r.data):r}async prepareLoginClientState(e,t){let i={BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:G()},s=await this.prepareClientStateExcept(i,e,t,false);return {request:i,finish:async r=>{let o=this.ctx.auth.context?.userID??null;return o&&await this.stateStore.load(o),s.handshake={userId:o,cached:null,sent:void 0},this.finishClientStateExcept(s,r)}}}async prepareClientStateExcept(e,t,i,s){e.ExcludeFields=t,e.ExcludeTitleFields=i;let r=Ii.scopeOf(null,i??[]),o=await this.configCache.read(r);o&&(e.KnownTitleConfigVersion=o.v),await this.prepareLocalization(e);let c=s?await this.prepareStateHandshake(e,t??null):{userId:null,cached:null,sent:void 0};return await this.prepareLoginViews(e),{scope:r,cached:o,handshake:c,excludeFields:t,excludeTitleFields:i}}async finishClientStateExcept(e,t){let i=await this.resolveTitleConfig(t,e.scope,e.cached,{ExcludeFields:e.excludeTitleFields??[]});return i==null?Wu:(this.finishStateHandshake(t,e.handshake),await this.restoreSections(t.TitleConfigVersion,i),await this.applyClientState(t,i,e.excludeFields,e.excludeTitleFields),this.ctx.cache.acceptLoginViews(t.Views),await this.applyLocalization(t.Localization),await this.flushState(e.handshake),F(t))}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let i=t,s={};for(let[r,o]of Object.entries(await this.sectionCache.read(e)))i[r]==null&&(s[r]=o);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((r,o)=>{i[r]!=null||o==null||(s[r]=o,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let r=await this.fetchLocalizationFromApi(t,s?.v??0);return r??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let r=s.data;if(r.NotModified)return null;let o=r.Entries??{},c=r.Version??0,h=r.Locale??e;return c>0&&await this.localizationCache.write(h,c,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):a}async getUserState(e){let t=this.baseRequest();if(!t)return a;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let r=ea(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=r;let o=i.sent??{},c=Object.entries(s.data.StateVersions??{}).filter(([g,V])=>o[g]!==V||this.ctx.data.user.state?.[g]===void 0).map(([g])=>g);this.ctx.data.user.applyUserStateContainers(r,c);let h=ta(s.data);return h&&(this.stateStore.afterSliceRead(h,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let s=this.baseRequest();if(!s)return a;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=i;let r=await this.ctx.api.user.addUsageTime(s);return r.ok&&this.ctx.emitter.emit("user:usageTimeAdded",r.data),r}async deleteUserAccount(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return a;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,s){let r=i?.includes("GameLoop")===true,o=s?.includes("GameLoop")===true,c=r?this.ctx.data.user.state?.GameLoop:void 0,h=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let g=this.ctx.data.user.state;r&&g&&g.GameLoop==null&&(g.GameLoop=c);let V=this.ctx.data.config.titlePublicConfiguration;o&&V&&V.GameLoop==null&&(V.GameLoop=h),this.ctx.emitter.emit("user:clientStateReceived",e);}};var js=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return u("client","SpendID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${G()}`},s=await this.ctx.api.currency.spend(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",s.data)),s}async convert(e,t,i,s,r,o){if(!t)return u("client","SourceID is required.");if(!s)return u("client","TargetID is required.");if(r<=0)return u("client","Amount must be positive.");if(e===i&&t===s)return u("client","Source and target must differ.");if(e===gt.Crypto||i===gt.Crypto)return u("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return a;let c={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(r)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${s}_${G()}`},h=await this.ctx.api.currency.convert(c);if(h.ok){let g=h.data,V={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:g.SourceID,Amount:g.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:g.TargetID,Amount:g.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",g);}return h}async cryptoConvert(e,t,i,s,r,o){let c=r instanceof ni__default.default?r:new ni__default.default(r);if(!t)return u("client","SourceID is required.");if(!s)return u("client","TargetID is required.");if(c.lte(0))return u("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return u("client","Source and target must differ.");if(e===gt.Virtual&&i===gt.Virtual)return u("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===gt.Virtual&&!c.isInteger())return u("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:c.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${s}_${G()}`},g=await this.ctx.api.currency.cryptoConvert(h);if(g.ok){let V=g.data,oe=[],be=[];if(V.SourceType===gt.Virtual&&oe.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===gt.Virtual&&be.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),oe.length>0||be.length>0){let ue={Consume:oe.length>0?{Standard:{Entries:oe}}:null,Grant:be.length>0?{Standard:{Entries:be}}:null};this.ctx.data.user.applyResourceOperation(ue,this.ctx.data.config.itemDefinitions);}V.SourceType===gt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new ni__default.default(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===gt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new ni__default.default(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return g}};var Ws=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i,s){let r=e.trim();if(!r)return u("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:r,SelectedOptionID:i,CreditsConfirmationID:s,RelatedEntityID:`upgrade_item_${r}_${G()}`};t&&t.length>0&&(o.FodderInstanceIDs=[...t]);let c=await this.ctx.api.item.upgradeLevel(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(c.data.ItemInstanceID??r,c.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",c.data)),c}async upgradeLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let s of i.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var Hs=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:zt.nullish(),AllowedPlatforms:zod.z.array(ds).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ae=zod.z.record(zod.z.string(),Hs),zy=zod.z.object({Store:hs,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var Hi={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},fe=zod.z.object({ConfirmationID:zod.z.string(),Url:zod.z.string(),Status:zod.z.string(),PriceCredits:zod.z.number(),ExpiresAt:p}).passthrough(),Hu=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),My={LoginRequired:"CREDITS_LOGIN_REQUIRED",NotEnough:"NOT_ENOUGH_CREDITS",SellerUnknown:"CREDITS_SELLER_UNKNOWN",PriceChanged:"CREDITS_PRICE_CHANGED",ConfirmationPending:"CREDITS_CONFIRMATION_PENDING",ConfirmationDeclined:"CREDITS_CONFIRMATION_DECLINED",ConfirmationExpired:"CREDITS_CONFIRMATION_EXPIRED",ConfirmationNotFound:"CREDITS_CONFIRMATION_NOT_FOUND",ConfirmationMismatch:"CREDITS_CONFIRMATION_MISMATCH",BatchForbidden:"CREDITS_BATCH_FORBIDDEN",NotAllowedHere:"CREDITS_NOT_ALLOWED_HERE",MixedWithStorePayment:"CREDITS_MIXED_WITH_STORE_PAYMENT",SellerNotReady:"CREDITS_SELLER_NOT_READY",ConfirmationInUse:"CREDITS_CONFIRMATION_IN_USE"},ia=zod.z.object({ServerTimeUtc:p,OfferID:zod.z.string(),Count:zod.z.number(),Resources:O.nullish(),Inventory:H.nullish(),CreditsConfirmation:fe.nullish()}),Ku=zod.z.array(we(ia)),Oy=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:p,LastPurchasedAt:p}),Ey=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:p}),Qu=zod.z.object({Purchases:zod.z.record(zod.z.string(),Oy).nullish(),Rotations:zod.z.record(zod.z.string(),Ey).nullish()}).passthrough().transform(n=>n),Ot=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ks=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),Uy={Fixed:"Fixed",Title:"Title",Player:"Player"},qy=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:Z.nullish()}).passthrough(),$u=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(qy).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),Ly=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Rotation:K.nullish()}).passthrough(),By=zod.z.object({SlotID:zod.z.string().nullish(),Identity:Ot.nullish(),Availability:Ks.nullish(),Rotation:$u.nullish(),Presets:Ly.nullish()}).passthrough(),Gy=zod.z.object({Identity:K.nullish(),Availability:K.nullish()}).passthrough(),Fy=zod.z.object({SectionID:zod.z.string().nullish(),Identity:Ot.nullish(),Availability:Ks.nullish(),Slots:zod.z.record(zod.z.string(),By).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:Gy.nullish()}).passthrough(),Ju=zod.z.object({Sections:zod.z.record(zod.z.string(),Fy).nullish()}).passthrough(),Ny=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Layout:K.nullish()}).passthrough(),_y=zod.z.object({StoreID:zod.z.string().nullish(),Identity:Ot.nullish(),Availability:Ks.nullish(),Layout:Ju.nullish(),Presets:Ny.nullish()}).passthrough(),Zu=zod.z.object({Options:ae.nullish(),CompareAt:zod.z.record(zod.z.string(),zt).nullish()}).passthrough(),Yu=zod.z.object({Grant:Q.nullish()}).passthrough(),Xu=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Vy=zod.z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish(),Availability:K.nullish()}).passthrough(),jy=zod.z.object({OfferID:zod.z.string().nullish(),Identity:Ot.nullish(),Pricing:Zu.nullish(),Reward:Yu.nullish(),Availability:Xu.nullish(),Presets:Vy.nullish()}).passthrough(),Wy=zod.z.object({Identity:zod.z.record(zod.z.string(),Ot).nullish(),Availability:zod.z.record(zod.z.string(),Ks).nullish(),Layout:zod.z.record(zod.z.string(),Ju).nullish(),Rotation:zod.z.record(zod.z.string(),$u).nullish(),Pricing:zod.z.record(zod.z.string(),Zu).nullish(),Reward:zod.z.record(zod.z.string(),Yu).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Xu).nullish()}).passthrough(),Qs=zod.z.object({Stores:zod.z.record(zod.z.string(),_y).nullish(),StoreOffers:zod.z.record(zod.z.string(),jy).nullish(),Presets:Wy.nullish()}).passthrough(),Hy=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:p.nullish()}).passthrough(),Ky=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:zt.nullish(),CompareAtCost:zt.nullish(),DiscountPercent:zod.z.number().nullish(),IsFree:zod.z.boolean(),IsAdPaid:zod.z.boolean(),IsStorePaid:zod.z.boolean(),IsCreditsPaid:zod.z.boolean().nullish(),CreditsPrice:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Qy=zod.z.object({OfferID:zod.z.string(),Identity:Ot.nullish(),PriceOptions:zod.z.array(Ky).nullish(),Rewards:Q.nullish(),State:Hy.nullish()}).passthrough(),$y=zod.z.object({SlotID:zod.z.string(),Identity:Ot.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:p.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:Qy.nullish()}).passthrough(),Jy=zod.z.object({SectionID:zod.z.string(),Identity:Ot.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array($y).nullish()}).passthrough(),Zy=zod.z.object({StoreID:zod.z.string(),Identity:Ot.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:p.nullish(),Sections:zod.z.array(Jy).nullish()}).passthrough(),$s=zod.z.object({ServerTimeUtc:p,Stores:zod.z.array(Zy).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Et={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},Yy="OFFER_NOT_IN_ROTATION";var ec="Store",tc={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:n=>{let e=null;for(let t of n.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let r=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(r)&&(e===null||r<e)&&(e=r);}return e}},Js=class{constructor(e){this.ctx=e;e.cache.bindLoginView(tc,{schema:$s,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return u("client","OfferID is required.");if(t<1)return u("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return a;let r={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${s.userID}_${G()}`},o=await this.ctx.api.store.purchase(r);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;this.ctx.data.user.patchStorePurchase(e,t,c.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",c);}return o}async purchaseWithCredits(e,t=1,i={}){return await this.ctx.credits.pay(s=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:s}),{onConfirmation:i.onConfirmation,signal:i.signal,pollMs:i.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):a}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):a}async purchaseBatch(e){if(!e||e.length===0)return u("client","purchases is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let s=false;for(let r of i.data)!r.Success||!r.Data||!r.Data.OfferID||(this.ctx.data.user.patchStorePurchase(r.Data.OfferID,r.Data.Count,r.Data.ServerTimeUtc),!s&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(ec,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ec,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(tc,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let r=s.RefreshesAtUtc;r&&(e===null||Date.parse(r)<Date.parse(e))&&(e=r);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var Zs=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let i=await e(void 0);if(!i.ok||!i.data.CreditsConfirmation)return i;let s=i.data.CreditsConfirmation,r=()=>e(s.ConfirmationID);if(this.ctx.host.supports.creditsConfirm){let h=await this.ctx.host.confirmCredits({titleID:this.ctx.settings.titleID,confirmationID:s.ConfirmationID});if(h.ok)return await r();if(h.error==="DECLINED")return u("server","CREDITS_CONFIRMATION_DECLINED");if(h.error==="NOT_ENOUGH_CREDITS")return u("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(s);let o=Math.max(1e3,t.pollMs??2500),c=Date.parse(s.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return u("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>c)return u("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(V=>setTimeout(V,o));let h=await this.ctx.store.getCreditsConfirmation(s.ConfirmationID);if(!h.ok)continue;let g=h.data.Status;if(g!==Hi.Pending)return g===Hi.Declined?u("server","CREDITS_CONFIRMATION_DECLINED"):g===Hi.Expired?u("server","CREDITS_CONFIRMATION_EXPIRED"):await r()}}};var Ys=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?F(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return u("client","Receipt is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},r=await this.ctx.api.purchase.validatePurchase(s);return r.ok&&this.applyValidation(r.data),r}async buyWithTelegramStars(e,t){if(!e)return u("client","productID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(i);return s.ok&&t?.open!==false&&this.ctx.host.openInvoice(s.data.InvoiceLink),s}async buy(e){if(!e)return u("client","productID is required.");if(!this.ctx.host.supports.storePurchases)return u("client","UNAVAILABLE");if(!this.ctx.auth.context)return a;let t=await this.getDefinitions();if(!t.ok)return t;let i=t.data.Purchase?.Products?.[e],s=this.hostStore(),r=i?.StoreProductIDs?.[s];if(!i||i.Enabled===false||!r)return u("client","NOT_SOLD");let o=this.ctx.buildAuthedBaseRequest(),c=await this.ctx.host.buyProduct({storeProductID:r,type:i.Type??"Consumable",accountID:o.UserID??void 0});return !c.ok||!c.receipt?u("client",c.error??"FAILED"):this.deliver(c.receipt,i)}async restorePending(){if(!this.ctx.host.supports.storePurchases||!this.ctx.auth.context)return 0;let e=await this.ctx.host.pendingPurchases();if(e.length===0)return 0;let t=await this.getDefinitions(),i=t.ok?Object.values(t.data.Purchase?.Products??{}):[],s=0;for(let r of e){let o=i.find(c=>r.storeProductID&&c.StoreProductIDs?.[r.store]===r.storeProductID);(await this.deliver(r,o)).ok&&s++;}return s}async deliver(e,t){let i=await this.validatePurchase(e.store,e.receipt,{signature:e.signature});return i.ok&&await this.ctx.host.finishPurchase(e,(t?.Type??"Consumable")==="Consumable"),i}hostStore(){return this.ctx.host.getClientPlatform()===Ee.Ios?"AppleAppStore":"GooglePlay"}async validatePurchasesBatch(e){if(!e||e.length===0)return u("client","receipts is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let s of i.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var ic=3,Xy=700,Xs=class{constructor(e){this.ctx=e;e.host.supports.cryptoTopUp&&this.setTopUpHandler(this.hostTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return Di(e)}hostTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await this.ctx.host.topUp({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return i.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:i.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=ic;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===ic)break;await _t(Xy);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t)if(i?.Type===ps.Purchase&&i.ProductID)return i.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t){if(i?.Type!==ps.CryptoCurrency||!i.CurrencyID)continue;let s=Number(i.Amount??0);if(!(s>0))continue;let r=this.cryptoBalance(i.CurrencyID);return r>=s?null:{currencyID:i.CurrencyID,required:s,available:r,missing:s-r}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var sc="Lootbox",er=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(sc,e);if(t){let r={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),F(r)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let r=s.data.LootboxDefinitions;r&&(this.ctx.data.config.patchSection(sc,r),this.ctx.emitter.emit("lootbox:definitionsLoaded",r));}return s}async open(e,t,i,s,r){if(!e)return u("client","LootboxID is required.");if(t<1)return u("client","Count must be at least 1.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,CreditsConfirmationID:r,RelatedEntityID:`lootbox_${e}_${i??"default"}_${G()}`},c=await this.ctx.api.lootbox.open(o);if(c.ok&&!c.data.CreditsConfirmation){let h=c.data;h.TriggeredPity&&h.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,h.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(h.Resources,h.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",h);}return c}};var sa="Reward";function tr(n){return n.length>0&&!n.includes(".")&&!n.includes("$")}var ir=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Reward",{needsServer:()=>!t&&Object.values(e.cache.configSection(sa)?.Comebacks??{}).some(i=>i?.TrackPresenceOnRead===true),refresh:async()=>{let i=await this.getUserRewardsState();return i.ok&&(t=true),i}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(sa,e);if(t){let r={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),F(r)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let r=s.data.RewardDefinitions;r&&(this.ctx.data.config.patchSection(sa,r),this.ctx.emitter.emit("reward:definitionsLoaded",r));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${G()}`},s=await this.ctx.api.reward.claimDailyReward(i);if(s.ok){let r=s.data;this.ctx.data.user.patchDailyCalendarState(r.CalendarID,r.DailyState),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",r);}return s}async collectIdleAccrual(e){if(!tr(e))return u("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${G()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let s=i.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return i}async claimComebackReward(e){if(!tr(e))return u("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return i}async claimReward(e){if(!tr(e))return u("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return i}async claimRewardWindow(e,t,i={}){if(!tr(e))return u("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return u("client","Amount must be a positive number.");let s=i.boost??"None";if(s==="Ad"&&!i.adRequestID)return u("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:s,...i.adRequestID?{AdRequestID:i.adRequestID}:{},RelatedEntityID:i.roundID??`reward_window_${e}_${G()}`},o=await this.ctx.api.reward.claimRewardWindow(r);if(o.ok){let c=o.data;this.ctx.data.user.patchRewardWindowState(c.WindowID,c.WindowState),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:windowClaimed",c);}return o}};var sr="Tutorial",rc={key:"tutorial.state",login:"TutorialState",ttlMs:5*6e4,dependsOn:["Tutorial"],invalidateOn:["tutorial:flowStarted","tutorial:flowSkipped","tutorial:flowReset","tutorial:stepChanged","tutorial:stepsCompletedBatch","tutorial:rewardClaimed","tutorial:systemProgress"]},rr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(rc,{schema:Ds,apply:i=>this.applyUserTutorialState(i)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(sr)?.Flows??{}).length>0,refresh:async()=>{let i=await this.getUserTutorialState();return i.ok&&(t=true),i}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(sr,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(sr,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(rc,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${G()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return u("client","FlowID is required.");if(!t||t.length===0)return u("client","stepIDs is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${G()}`},r=await this.ctx.api.tutorial.completeStepsBatch(s);return r.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",r.data)),r}async skipStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.skipStep(i))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${G()}`},s=await this.ctx.api.tutorial.claimFlowReward(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let s=e?.trim();if(!s)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),FlowID:s},o=await t(r);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,s){let r=e?.trim(),o=t?.trim();if(!r)return u("client","FlowID is required.");if(!o)return u("client","StepID is required.");if(!this.ctx.auth.context)return a;let c={...this.ctx.buildAuthedBaseRequest(),FlowID:r,StepID:o};s?.relatedEntityID&&(c.RelatedEntityID=s.relatedEntityID);let h=this.ctx.data.user.state?.Tutorial?.Flows?.[r]?.RewardClaimed===true,g=await i(c);return g.ok&&(this.applyFlowView(g.data),this.mayHavePaid(r,o,h,g.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",g.data)),g}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(sr)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}};var nr=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return a;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return u("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return u("client","campaignID is required.");if(!t)return u("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return a;s.CampaignID=e,s.WalletAddress=t,i&&(s.Amount=i);let r=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return r.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",r.data),r}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Le=zod.z.object({Username:zod.z.string().nullish(),Country:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Premium:zod.z.boolean().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BoardRank:zod.z.number().nullish()}).passthrough();var eR={Global:"Global",Announcement:"Announcement",Group:"Group"},oc=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),tR={None:"None",Language:"Language",Region:"Region"},iR=zod.z.enum(["None","Language","Region"]).catch("None"),sR={Anyone:"Anyone",Friends:"Friends"},rR=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),nR={Reject:"Reject",Mask:"Mask"},oR=zod.z.enum(["Reject","Mask"]).catch("Reject"),aR={Player:"Player",Publisher:"Publisher",System:"System"},lR=zod.z.enum(["Player","Publisher","System"]).catch("Player"),uR={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var cR=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),ac=zod.z.object({Gate:Z.nullish(),Schedule:Re.nullish()}).passthrough(),lc=zod.z.object({Gate:Z.nullish(),Limits:Se.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),uc=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),pR=zod.z.object({Availability:K.nullish(),Write:K.nullish(),Retention:K.nullish()}).passthrough(),dR=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:cR.nullish(),Type:oc.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:iR.nullish(),Capacity:zod.z.number().nullish(),Availability:ac.nullish(),Write:lc.nullish(),Retention:uc.nullish(),Presets:pR.nullish()}).passthrough(),hR=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:rR.nullish(),Limits:Se.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),mR=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:oR.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Se.nullish()}).passthrough(),fR=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),gR=zod.z.object({Availability:zod.z.record(zod.z.string(),ac).nullish(),Write:zod.z.record(zod.z.string(),lc).nullish(),Retention:zod.z.record(zod.z.string(),uc).nullish()}).passthrough(),cc=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),dR).nullish(),Direct:hR.nullish(),Moderation:mR.nullish(),Polling:fR.nullish(),Presets:gR.nullish()}).passthrough(),yR=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),nc=zod.z.object({LastAt:zod.z.string().nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:zod.z.string().nullish(),TotalCount:zod.z.number().nullish(),LastTextHash:zod.z.string().nullish()}).passthrough();zod.z.object({MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish(),Ignored:zod.z.array(zod.z.string()).nullish(),Channels:zod.z.record(zod.z.string(),yR).nullish(),Limits:zod.z.record(zod.z.string(),nc).nullish(),ReportLimits:nc.nullish()}).passthrough();var ra=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),or=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:Le.nullish(),AuthorType:lR.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),RR=zod.z.object({ChannelID:zod.z.string().nullish(),RoomID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Type:oc.nullish(),CanWrite:zod.z.boolean().nullish(),WriteBlockedReason:zod.z.string().nullish(),SlowModeSeconds:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),ar=zod.z.object({Channels:zod.z.array(RR).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),CR=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(or).nullish(),NextCursor:ra.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),pc=zod.z.object({Rooms:zod.z.array(CR).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),dc=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(or).nullish(),NextBefore:ra.nullish()}).passthrough(),hc=zod.z.object({Message:or.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),mc=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Le.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),SR=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Le.nullish(),LastMessage:or.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),fc=zod.z.object({Conversations:zod.z.array(SR).nullish()}).passthrough(),Ti=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:ra.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),gc=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),Je={GetChatDefinitions:"GetChatDefinitions",GetChannels:"GetChannels",Poll:"Poll",GetHistory:"GetHistory",GetConversations:"GetConversations",SendMessage:"SendMessage",OpenDirectChannel:"OpenDirectChannel",MarkRead:"MarkRead",JoinChannel:"JoinChannel",LeaveChannel:"LeaveChannel",ReportMessage:"ReportMessage",IgnoreUser:"IgnoreUser",UnignoreUser:"UnignoreUser"};var yc="Chat",Rc={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},lr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Rc,{schema:ar,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(yc,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(yc,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(Rc,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let s of i.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return i}async getHistory(e,t,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),i&&(s.Limit=i),this.ctx.api.chat.getHistory(s)):a}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return a;s.ChannelID=e,s.Text=t,i&&(s.Locale=i);let r=await this.ctx.api.chat.sendMessage(s);return r.ok&&this.ctx.emitter.emit("chat:sent",r.data),r}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Text=t;let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):a}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):a}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(i);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):a}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):a}async reportMessage(e,t,i,s){let r=this.ctx.authedRequest();return r?(r.RoomID=e,r.MessageID=t,r.Reason=i,s&&(r.Comment=s),this.ctx.api.chat.reportMessage(r)):a}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):a}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):a}resetCursors(){this.cursors.clear();}};var xR={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},bR=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),DR={Player:"player",Title:"title",Creator:"creator"},Ai={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Cc=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),PR=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),na=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:bR.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(PR).nullish()}).passthrough(),Sc=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(na).nullish()}).passthrough(),Ze={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var IR="IDOS_PLATFORM_PUSH_REQUEST",vR="IDOS_PLATFORM_PUSH_RESPONSE",TR=12e4;function xc(n){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let s=false,r=h=>{s||(s=true,window.removeEventListener("message",o),clearTimeout(c),i(h));},o=h=>{let g=h?.data;!g||g.type!==vR||g.requestId!==t||wt.includes(h.origin)&&r(g.ok===true);},c=setTimeout(()=>r(false),TR);window.addEventListener("message",o);for(let h of wt)try{e.postMessage({type:IR,requestId:t,titleID:n},h);}catch{}})}var AR="idos:push:deviceToken:",ur=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),s=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,i.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(this.ctx.host.supports.pushNotifications){if(!e.Configured)return Ze.Unsupported;let r=await this.ctx.host.requestPushToken({prompt:false});return r.error==="BLOCKED"?Ze.Blocked:r.token?this.ctx.host.storage.getString(this.deviceTokenKey())===r.token?Ze.Subscribed:Ze.Idle:r.error==="NOT_GRANTED"?Ze.Idle:Ze.Unsupported}if(!e.Configured||!e.PublicKey)return Ze.Unsupported;if(this.isEmbedded())return Ze.Embedded;if(!this.isSupported())return Ze.Unsupported;let t=Notification.permission;return t==="denied"?Ze.Blocked:t!=="granted"?Ze.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?Ze.Subscribed:Ze.Idle}async subscribe(e={}){let t=await this.getConfig();if(this.ctx.host.supports.pushNotifications)return this.subscribeDevice(t,e);if(!t.Configured||!t.PublicKey)return u("client","Push notifications are not available for this title.");if(this.isEmbedded())return await xc(this.ctx.settings.titleID)?F({Where:"portal",Subscription:null}):u("client","The portal did not complete the subscription.");if(!this.isSupported())return u("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return u("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:wR(t.PublicKey)}),c=this.ctx.authedRequest();if(!c)return a;let h=o.toJSON();c.PushEndpoint=h.endpoint,c.PushP256dh=h.keys?.p256dh,c.PushAuth=h.keys?.auth,c.PushTransport="WebPush",c.PushLocale=e.locale??navigator.language,c.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let g=await this.ctx.api.push.subscribePush(c);return g.ok?(this.ctx.emitter.emit("push:subscribed",g.data),F({Where:"game",Subscription:g.data})):g}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return a;if(this.ctx.host.supports.pushNotifications){let i=this.ctx.host.storage.getString(this.deviceTokenKey());if(!i)return u("client","This device has no push subscription to remove.");e.PushDeviceToken=i;let s=await this.ctx.api.push.unsubscribePush(e);return s.ok&&(this.ctx.host.storage.remove(this.deviceTokenKey()),this.ctx.emitter.emit("push:unsubscribed",void 0)),s}if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return u("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):a}async unsubscribeByHash(e){if(!e)return u("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return a;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}async subscribeDevice(e,t){if(!e.Configured)return u("client","Push notifications are not available for this title.");let i=await this.ctx.host.requestPushToken({prompt:true});if(!i.token)return u("client",i.error==="BLOCKED"?"The player blocked notifications for this app.":"The device gave no push token.");let s=this.ctx.authedRequest();if(!s)return a;s.PushTransport=i.transport??"Fcm",s.PushDeviceToken=i.token,s.PushLocale=t.locale??(this.ctx.host.getLanguage()||void 0),s.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let r=await this.ctx.api.push.subscribePush(s);return r.ok?(this.ctx.host.storage.setString(this.deviceTokenKey(),i.token),this.ctx.emitter.emit("push:subscribed",r.data),F({Where:"game",Subscription:r.data})):r}deviceTokenKey(){return AR+this.ctx.settings.titleID}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function wR(n){let e=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return i}var cr=Object.freeze({}),pr=class{constructor(e){this.ctx=e;}ctx;table={...cr};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new vi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),s=this.lookup(i)??this.lookup(e);return s===void 0?this.onMissing(e):t?kR(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...cr},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return a;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:r,fallbackLocale:o}=i.data,c=null;if(o){let h=await this.loadTableFromApi(o);h.ok&&(c=h.data.table);}return this.table=r,this.fallbackTable=c,this.currentFallbackLocale=o,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:o,entryCount:Object.keys(r).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):a}reset(){this.table={...cr},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:G()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return a;t.Locale=e;let i=await this.cache.read(bc(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let r=s.data,o=r.Locale??bc(e),c=r.Version??0;if(r.NotModified){let g=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:g?.t??{...cr},fallbackLocale:r.FallbackLocale??null}}}let h=r.Entries??{};return c>0&&await this.cache.write(o,c,h),{ok:true,data:{locale:o,table:h,fallbackLocale:r.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let s=this.pluralCategory(i),r=`${e}.${s}`;if(this.lookup(r)!==void 0)return r;let o=`${e}.other`;return this.lookup(o)!==void 0?o:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function kR(n,e){return n.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function bc(n){return n.trim().replace(/_/g,"-").toLowerCase()}var oa="Quest",zR={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:n=>{let e=Date.now(),t=null,i=[...Object.values(n.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(n.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let r=Date.parse(s??"");!Number.isNaN(r)&&r>e&&(t===null||r<t)&&(t=r);}return t}},dr=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let s=e.cache.configSection(oa)?.Cycles;if(!s)return false;let r=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(s)){let c=Date.parse(r[o]?.CycleEndUtc??"");if(Number.isNaN(c)){if(t===0)return true}else if(c<=i&&t<c)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true,{forceRefresh:true});return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(oa,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(oa,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(zR,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let s=i.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let i=e.trim();if(!i)return u("client","QuestID is required.");if(!this.ctx.auth.context)return a;let s=t&&t.trim().length>0?t.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${G()}`},o=await this.ctx.api.quest.claimQuestReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchQuestStatus(c.QuestID,c.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",c);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return u("client","quests is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let s=false;for(let r of i.data)!r.Success||!r.Data||(this.ctx.data.user.patchQuestStatus(r.Data.QuestID,r.Data.CycleID,"Claimed"),!s&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return u("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${G()}`},o=await this.ctx.api.quest.claimMilestoneReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchMilestoneClaimed(c.CycleID,c.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",c);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let s=false;for(let r of i.data)!r.Success||!r.Data||(this.ctx.data.user.patchMilestoneClaimed(r.Data.CycleID,r.Data.MilestoneID),!s&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return u("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${G()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchGroupCompletionClaimed(c.CycleID,c.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",c);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return u("client","MetricID is required.");if(t<0)return u("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},r=await this.ctx.api.quest.addQuestProgress(s);return r.ok&&(this.ctx.data.user.patchQuestProgressUpdates(r.data.Updates),this.ctx.emitter.emit("quest:progressAdded",r.data)),r}};var Dc=zod.z.object({}).passthrough().transform(n=>n);var MR=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),OR=zod.z.object({Schedule:zod.z.array(MR).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),ER=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:p.nullish(),NextBonusStartUtc:p.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),UR=zod.z.object({Milestones:K.nullish()}).passthrough(),aa=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Category:zod.z.string().nullish(),Token:ri.nullish(),TokenSources:zod.z.array(ut).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:UR.nullish(),BonusWindow:OR.nullish()}).passthrough(),qR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:aa.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),LR=zod.z.object({TimedEventID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:Re.nullish(),Content:aa.nullish(),Events:zod.z.array(qR).nullish(),Gate:Z.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),BR=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),GR=zod.z.object({Milestones:zod.z.record(zod.z.string(),xi).nullish()}).passthrough(),hr=zod.z.object({Definitions:zod.z.record(zod.z.string(),LR).nullish(),Settings:BR.nullish(),Presets:GR.nullish()}).passthrough(),FR=zod.z.object({Type:Gi,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:aa.nullish(),Progress:Dc.nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:_e.nullish(),BonusWindow:ER.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),mr=zod.z.object({ActiveEvents:zod.z.array(FR).nullish()}).passthrough(),Pc=zod.z.object({Tokens:zod.z.record(zod.z.string(),Dc).nullish()}),la=zod.z.object({Type:Gi.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),ua=zod.z.object({Type:Gi.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:O.nullish(),Inventory:H.nullish()}),NR=zod.z.object({Type:Gi.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),ca=zod.z.array(we(ua)),Ic=zod.z.array(we(la)),vc=zod.z.array(we(NR)),dt={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Tc="TimedEvent",Ac={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:n=>{let e=null;for(let t of n.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},fr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ac,{schema:mr,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(Ac,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(Tc,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Tc,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,s,r,o,c=1){if(!t)return u("client","LteID is required.");if(!i)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:r,SourceParams:o,RollMultiplier:c},g=await this.ctx.api.timedEvent.grantTokens(h);return g.ok&&(this.ctx.data.user.applyResourceOperation(g.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",g.data)),g}async spendTokens(e,t,i){if(!t)return u("client","LteID is required.");if(i<=0)return u("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},r=await this.ctx.api.timedEvent.spendTokens(s);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",r.data)),r}async claimMilestone(e,t,i){if(!t||!i)return u("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},r=await this.ctx.api.timedEvent.claimMilestone(s);if(r.ok){let o=r.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return r}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return a;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return u("client","spends is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let s=false;for(let r of i.data)!s&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(r.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return u("client","grants is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let s=false;for(let r of i.data)!s&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(r.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let s=i.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var _R=zod.z.object({UserID:zod.z.string(),Score:W.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:p.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:Le.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),Ki=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:W.nullish(),CycleEndUtc:p.nullish(),TopUsers:zod.z.array(_R).nullish(),BracketID:zod.z.string().nullish()}),VR=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:p.nullish(),ClaimDeadlineUtc:p.nullish(),MilestoneTokensEarned:W.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),gr=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:W.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:W.nullish(),MilestoneTokensEarned:W.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(VR).nullish()}),yr=zod.z.object({LeaderboardID:zod.z.string(),NewScore:W,CycleVersion:zod.z.number()}),Rr=zod.z.object({ServerTimeUtc:p,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:O.nullish(),Inventory:H.nullish()}),Cr=zod.z.object({ServerTimeUtc:p,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:O.nullish(),Inventory:H.nullish()}),wc=zod.z.array(we(Ki)),Sr=zod.z.array(we(gr)),kc=zod.z.array(we(Rr)),zc=zod.z.array(we(Cr)),Mc=zod.z.array(we(yr)),jR=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:we(Rr).nullish(),Milestones:zod.z.array(we(Cr)).nullish()}),Oc=zod.z.array(jR),WR=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:we(Ki).nullish(),Progress:we(gr).nullish()}),Ec=zod.z.array(WR),HR=zod.z.string(),Uc=zod.z.object({Rank:zod.z.string().nullish(),Rewards:Q.nullish(),SeasonTierRewards:_o.nullish()}).passthrough(),KR=zod.z.object({RankRewards:zod.z.array(Uc).nullish()}).passthrough(),QR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),$R=zod.z.object({Milestones:K.nullish(),RankRewards:K.nullish()}).passthrough(),JR=zod.z.object({LeaderboardID:zod.z.string(),DisplayName:zod.z.string().nullish(),ScoreDisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsEnabled:zod.z.boolean().nullish(),ScoreAggregation:HR.nullish(),Schedule:Re.nullish(),ChainEvents:zod.z.array(QR).nullish(),Gate:Z.nullish(),TopUsersLimit:zod.z.number().nullish(),MinScoreToEnterTop:zod.z.number().nullish(),BracketSize:zod.z.number().nullish(),LinkedSeasonChainID:zod.z.string().nullish(),RankRewards:zod.z.array(Uc).nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:$R.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(ut).nullish()}).passthrough(),ZR=zod.z.object({Milestones:zod.z.record(zod.z.string(),xi).nullish(),RankRewards:zod.z.record(zod.z.string(),KR).nullish()}).passthrough(),xr=zod.z.object({Definitions:zod.z.record(zod.z.string(),JR).nullish(),Presets:ZR.nullish()}).passthrough(),We={GetDefinitions:"GetDefinitions",GetLeaderboard:"GetLeaderboard",GetMyProgress:"GetMyProgress",SubmitScore:"SubmitScore",SubmitScoreFromSource:"SubmitScoreFromSource",ClaimCycleReward:"ClaimCycleReward",ClaimMilestone:"ClaimMilestone",GetFriendsLeaderboard:"GetFriendsLeaderboard",GetLeaderboardsBatch:"GetLeaderboardsBatch",GetProgressBatch:"GetProgressBatch",ClaimCycleRewardsBatch:"ClaimCycleRewardsBatch",ClaimMilestonesBatch:"ClaimMilestonesBatch",SubmitScoresBatch:"SubmitScoresBatch",ClaimAllRewardsBatch:"ClaimAllRewardsBatch",GetOverviewBatch:"GetOverviewBatch"};var qc="Leaderboard",Lc={key:"leaderboard.progress",login:"LeaderboardProgress",ttlMs:5*6e4,dependsOn:["Leaderboard","EventToken"],invalidateOn:["leaderboard:scoreSubmitted","leaderboard:scoresSubmittedBatch","leaderboard:cycleRewardClaimed","leaderboard:cycleRewardsClaimedBatch","leaderboard:milestoneClaimed","leaderboard:milestonesClaimedBatch","leaderboard:allRewardsClaimedBatch"]},br=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Lc,{schema:Sr,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(qc,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(qc,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return u("client","LeaderboardID is required.");if(t<=0)return u("client","Score must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(i);if(s.ok){let r=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),r.NewScore,t,r.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",r);}return s}async submitScoreFromSource(e,t,i,s,r=1){if(!e)return u("client","LeaderboardID is required.");if(!t)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:r},c=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(c.ok){let h=c.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),h.NewScore,h.NewScore,h.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",h);}return c}async claimCycleReward(e){if(!e)return u("client","LeaderboardID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return i}async claimMilestone(e,t,i){if(!e||!t)return u("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},r=await this.ctx.api.leaderboard.claimMilestone(s);if(r.ok){let o=r.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",o);}return r}async getFriendsLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(u("client","leaderboardIDs is required.")):this.ctx.cache.read(Lc,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return u("client","scores is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let r=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(r),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of s.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(r,o.Data.MilestoneID),o.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(o.Data.Resources,o.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let s of i.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var pa=zod.z.object({}).passthrough().transform(n=>n),Dr=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>Nc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:W.nullish(),UserState:pa.nullish(),NextTier:zod.z.lazy(()=>Fc).nullish()}).passthrough(),Bc=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:W.nullish(),NewStatusTokens:W.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),da=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:O.nullish(),Inventory:H.nullish()}),Gc=bt(da);var Fc=zod.z.object({Tier:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredTokens:W.nullish(),TierReachedReward:Q.nullish()}).passthrough(),Nc=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:W.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(Fc).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var YR=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Seasons:zod.z.array(Nc).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:Z.nullish()}).passthrough(),Pr=zod.z.object({Chains:zod.z.record(zod.z.string(),YR).nullish()}).passthrough(),jt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var _c="Season",Vc={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:n=>{let e=Date.parse(n.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Ir=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Vc,{schema:Dr,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(_c,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(_c,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(Vc,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(u("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return u("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","Amount must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${G()}`},s=await this.ctx.api.season.grantStatusTokens(i);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","TierNumber must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${G()}`},s=await this.ctx.api.season.claimTierReward(i);if(s.ok){let r=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",r);}return s}async claimTierRewardsBatch(e,t){if(!e)return u("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return u("client","TierNumbers is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${G()}`},r=await this.ctx.api.season.claimTierRewardsBatch(s);if(r.ok){let o=r.data;for(let c of o.Items??[]){let h=c.Data?.TierNumber;c.Success&&typeof h=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,h);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return r}};var jc="Premium",vr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(jc,e);if(t){let r={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",r),F(r)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(jc,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(i);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,i="Default",s=1,r){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,CreditsConfirmationID:r,RelatedEntityID:`premium_purchase_${e}_${t}`},c=await this.ctx.api.premium.purchaseItemOrCurrency(o);if(c.ok&&!c.data.CreditsConfirmation){let h=c.data;h.Premium&&this.ctx.data.user.applyPremium(h.Premium),this.ctx.data.user.applyResourceOperation(h.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",h);}return c}async purchaseRealMoney(e,t,i,s,r,o,c,h){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!s||!r)return u("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return a;let g={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:r,PurchaseToken:o,PackageName:c,AppStoreEnvironment:h,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(g);if(V.ok){let oe=V.data;oe.Premium&&this.ctx.data.user.applyPremium(oe.Premium),this.ctx.data.user.applyResourceOperation(oe.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",oe);}return V}};var Tr=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:p.nullish()}),ha=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:W.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),Tr).nullish(),UpdatedAt:p.nullish()}).passthrough(),Wc=zod.z.object({Characters:zod.z.record(zod.z.string(),ha).nullish()}),ma=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),fa=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Hc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Tr).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:H.nullish()}),Kc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:H.nullish()}),XR=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Qc=zod.z.object({ServerTimeUtc:p,Characters:zod.z.record(zod.z.string(),XR).nullish(),Inventory:H.nullish()}),ga=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:O.nullish()}),$c=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:O.nullish(),Inventory:H.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:Tr.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Jc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Tr.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:H.nullish()}),Zc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:H.nullish()}),eC=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:p.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:ae.nullish()}),tC=zod.z.object({CharacterID:zod.z.string(),CharacterOpen:zod.z.boolean().nullish(),DefaultSkinID:zod.z.string().nullish(),WornSkinID:zod.z.string().nullish(),Skins:zod.z.array(eC).nullish()}),Yc=zod.z.object({ServerTimeUtc:p,Characters:zod.z.record(zod.z.string(),tC).nullish()}),Xc=bt(ga),ep=bt(fa),tp=bt(ma),ya=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),ip=zod.z.object({StatID:zod.z.string(),TypeID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish(),Weight:zod.z.number().nullish(),PriceOptions:ae.nullish(),CostCurve:je.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:je.nullish(),RankCurve:je.nullish(),Requirements:zod.z.array(ya).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),iC=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(ya).nullish(),AllowedRarityIDs:zod.z.array(zod.z.string()).nullish(),AllowedItemTags:zod.z.array(zod.z.string()).nullish(),MinItemLevel:zod.z.number().nullish(),MaxItemLevel:zod.z.number().nullish()}).passthrough(),sp=zod.z.object({Slots:zod.z.record(zod.z.string(),iC).nullish()}).passthrough(),rp=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Lore:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),sC=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),rC=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:ae.nullish()}).passthrough(),nC=zod.z.object({Stats:K.nullish(),Levels:K.nullish(),Equipment:K.nullish()}).passthrough(),np=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:ae.nullish(),CostCurve:je.nullish()}).passthrough(),Ra="@skin";function oC(n){return !!n&&n.startsWith("@")}var aC=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),lC=zod.z.object({PriceOptions:ae.nullish(),Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),uC=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(ya).nullish()}).passthrough(),cC=zod.z.object({SkinID:zod.z.string().nullish(),Identity:rp.nullish(),Item:aC.nullish(),Sale:lC.nullish(),Requirements:uC.nullish()}).passthrough(),pC=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),cC).nullish()}).passthrough(),dC=zod.z.object({CharacterID:zod.z.string(),Identity:rp.nullish(),Classification:sC.nullish(),Unlock:rC.nullish(),Presets:nC.nullish(),Equipment:sp.nullish(),Stats:zod.z.record(zod.z.string(),ip).nullish(),RankLadder:np.nullish(),RankStatCurve:je.nullish(),StatMaxLevelCurve:je.nullish(),Skins:pC.nullish()}).passthrough(),hC=zod.z.object({Stats:zod.z.record(zod.z.string(),ip).nullish()}).passthrough(),mC=zod.z.object({RankLadder:np.nullish()}).passthrough(),fC=zod.z.object({Equipment:sp.nullish()}).passthrough(),gC=zod.z.object({Stats:zod.z.record(zod.z.string(),hC).nullish(),Levels:zod.z.record(zod.z.string(),mC).nullish(),Equipment:zod.z.record(zod.z.string(),fC).nullish()}).passthrough(),Ar=zod.z.object({Definitions:zod.z.record(zod.z.string(),dC).nullish(),Presets:gC.nullish()}).passthrough(),He={GetCharacterDefinitions:"GetCharacterDefinitions",GetUserCharacters:"GetUserCharacters",UnlockCharacter:"UnlockCharacter",UpgradeStatLevel:"UpgradeStatLevel",UpgradeCharacterLevel:"UpgradeCharacterLevel",EquipItems:"EquipItems",UnequipItems:"UnequipItems",UnequipAllCharacters:"UnequipAllCharacters",UnlockCharactersBatch:"UnlockCharactersBatch",UpgradeCharacterLevelsBatch:"UpgradeCharacterLevelsBatch",UpgradeStatLevelsBatch:"UpgradeStatLevelsBatch",UnlockSkin:"UnlockSkin",EquipSkin:"EquipSkin",UnequipSkin:"UnequipSkin",GetCharacterSkins:"GetCharacterSkins"},yC="SKIN_ALREADY_OWNED";var Ca="Character",wr=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Ca)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,r])=>r?.Unlock?.UnlockedByDefault===true&&!i[r.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(Ca,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ca,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${G()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok&&!s.data.CreditsConfirmation){let r=s.data;this.ctx.data.user.patchCharacter(r.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},r.Power!=null&&(o.Power=r.Power),o.UpdatedAt=r.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",r);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return u("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${G()}`,SelectedOptionID:i?.selectedOptionID,CreditsConfirmationID:i?.creditsConfirmationID,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},r=await this.ctx.api.character.upgradeStatLevel(s);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;this.ctx.data.user.patchCharacter(o.CharacterID,c=>{c.StatLevels??={},c.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(c.Power=o.Power),c.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return r}async upgradeCharacterLevel(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${G()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok&&!s.data.CreditsConfirmation){let r=s.data;this.ctx.data.user.patchCharacter(r.CharacterID,o=>{o.Level=r.NewLevel,r.Power!=null&&(o.Power=r.Power),o.UpdatedAt=r.ServerTimeUtc,r.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",r);}return s}async equipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(i);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(i);if(s.ok){let r=s.data;this.applyUnequipChangesLocally(e,r),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:r.ClearedSlotIDs??[],power:r.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${G()}`},r=await this.ctx.api.character.unlockSkin(s);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),o.Equipped&&o.Equipment&&this.applySkinLocally(o.CharacterID,o.Equipment,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",o);}return r}async equipSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},r=await this.ctx.api.character.equipSkin(s);if(r.ok){let o=r.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return r}async unequipSkin(e){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let s=i.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):a}applySkinLocally(e,t,i,s){let r=this.ctx.data.user;r.patchCharacterEquipment(e,Ra,t??null),r.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return u("client","characterIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,r=>{r.Level??=1,r.StatLevels??={},r.Equipment??={},s.Power!=null&&(r.Power=s.Power),r.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,r=>{r.Level=s.NewLevel,s.Power!=null&&(r.Power=s.Power),r.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(r.StatLevels??={},r.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,r=>{r.StatLevels??={},r.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(r.Power=s.Power),r.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[s,r]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,s,r);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let r of i)s.patchCharacterEquipment(e,r,null);s.patchCharacter(e,r=>{t.Power!=null&&(r.Power=t.Power),r.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,s]of Object.entries(e.Characters??{})){for(let r of s.ClearedSlotIDs??[])t.patchCharacterEquipment(i,r,null);t.patchCharacter(i,r=>{s.Power!=null&&(r.Power=s.Power),r.UpdatedAt=e.ServerTimeUtc;});}}};var op="Match",kr=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,r,o){let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:r,SelectedOptionID:o,RelatedEntityID:`pvp_create_${c.userID}_${G()}`},g=await this.ctx.api.match.createMatch(h);return g.ok&&(this.ctx.data.user.applyResourceOperation(g.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",g.data)),g}async updateMatch(e,t={}){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(i);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,s){let r=this.ctx.auth.context;if(!r)return a;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${G()}`},c=await this.ctx.api.match.instantBattle(o);if(c.ok){let h=c.data,g=this.ctx.data.config.itemDefinitions;if(h.Resources)this.ctx.data.user.applyResourceOperation(h.Resources,g);else if(h.ResourcesDual){let V=h.ResourcesDual;V.FromUserID===r.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,g):V.ToUserID===r.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,g);}this.ctx.emitter.emit("match:instantBattleCompleted",h);}return c}async saveStrategy(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let s=this.ctx.authedRequest();if(!s)return a;s.Page=e,s.PageSize=t,s.Statuses=i;let r=await this.ctx.api.match.getMyMatches(s);return r.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",r.data),r}async getAvailableMatches(e=0,t=20,i=false){let s=this.ctx.authedRequest();if(!s)return a;s.Page=e,s.PageSize=t,s.OnlyPublic=i;let r=await this.ctx.api.match.getAvailableMatches(s);return r.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",r.data),r}async getDefinitions(e){let t=this.ctx.cache.configSection(op,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(op,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var ap="Craft",zr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ap,e);if(t){let r={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),F(r)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(ap,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,r,o){if(!e)return u("client","CraftID is required.");let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:r,CreditsConfirmationID:o,RelatedEntityID:`craft_${e}_${c.userID}_${G()}`},g=await this.ctx.api.craft.craft(h);return g.ok&&!g.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(g.data.Resources,g.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",g.data)),g}};var Wt=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(Wt),zod.z.record(zod.z.string(),Wt)]));var Ht={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},lp=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),oi={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Qi(n){return n!==oi.Pending&&n!==oi.Running}var RC={Disabled:"AI_DISABLED",FeatureNotFound:"AI_FEATURE_NOT_FOUND",FeatureDisabled:"AI_FEATURE_DISABLED",WrongAction:"AI_WRONG_ACTION",NotAvailableForPlayer:"AI_NOT_AVAILABLE_FOR_PLAYER",FeatureClosed:"AI_FEATURE_CLOSED",LimitReached:"AI_LIMIT_REACHED",Cooldown:"AI_COOLDOWN",BadInput:"AI_BAD_INPUT",PromptRejected:"AI_PROMPT_REJECTED",Unavailable:"AI_UNAVAILABLE",GenerationFailed:"AI_GENERATION_FAILED",GenerationNotFound:"AI_GENERATION_NOT_FOUND"};function CC(n){return n?/\b(AI_[A-Z_]+)\s*:/.exec(n)?.[1]??null:null}var SC=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),xC=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),Mr=zod.z.object({CreditsConfirmation:fe.nullish(),GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:lp.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),Wt).nullish(),Assets:zod.z.array(SC).nullish(),Error:xC.nullish(),Charge:O.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:O.nullish(),Context:zod.z.record(zod.z.string(),Wt).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish()}),up=zod.z.object({Data:zod.z.array(Mr).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),bC=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ct=zod.z.record(zod.z.string(),zod.z.string()),DC=zod.z.object({Key:zod.z.string().nullish(),Role:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),Label:Ct.nullish()}).passthrough(),PC=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Default:zod.z.string().nullish(),Multiline:zod.z.boolean().nullish(),Label:Ct.nullish(),Placeholder:Ct.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string().nullish(),Label:Ct.nullish()}).passthrough()).nullish()}).passthrough(),cp=zod.z.object({Key:zod.z.string(),Kind:zod.z.string().nullish(),Name:Ct.nullish(),Hint:Ct.nullish(),Unit:Ct.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string(),Name:Ct.nullish(),Group:zod.z.string().nullish()}).passthrough()).nullish(),Groups:zod.z.array(zod.z.object({Key:zod.z.string(),Name:Ct.nullish()}).passthrough()).nullish(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),Step:zod.z.number().nullish()}).passthrough(),pp=zod.z.object({PriceOptions:ae.nullish()}).passthrough(),IC=zod.z.object({Id:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Action:zod.z.string().nullish(),IsTrend:zod.z.boolean().nullish(),Category:zod.z.string().nullish(),Order:zod.z.number().nullish(),Name:Ct.nullish(),Description:Ct.nullish(),Preview:zod.z.object({Url:zod.z.string().nullish(),PosterUrl:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough().nullish(),Inputs:zod.z.array(DC).nullish(),Variables:zod.z.array(PC).nullish(),Settings:zod.z.array(cp).nullish()}).passthrough(),vC=zod.z.object({Modality:lp.nullish(),Async:zod.z.boolean().nullish(),Limits:Se.nullish(),PriceOptions:ae.nullish(),Tags:zod.z.array(zod.z.string()).nullish(),HistoryMessages:zod.z.number().nullish(),MaxTokens:zod.z.number().nullish(),AllowImages:zod.z.boolean().nullish(),MaxInputImages:zod.z.number().nullish(),MaxInputImageBytes:zod.z.number().nullish(),AllowedImageTypes:zod.z.array(zod.z.string()).nullish(),MaxImages:zod.z.number().nullish(),AllowEdit:zod.z.boolean().nullish(),AllowReferenceImage:zod.z.boolean().nullish(),MaxPromptChars:zod.z.number().nullish(),LockBehavior:zod.z.boolean().nullish(),ImageSize:zod.z.string().nullish(),VideoSize:zod.z.string().nullish(),VideoSeconds:zod.z.number().nullish(),Voice:zod.z.string().nullish(),AudioFormat:zod.z.string().nullish(),MusicFormat:zod.z.string().nullish(),ThreeDOperation:zod.z.string().nullish(),ThreeDAnimations:zod.z.array(zod.z.string()).nullish(),Reward:Q.nullish(),PromptVariables:zod.z.array(bC).nullish(),AllowFreePrompt:zod.z.boolean().nullish(),PlatformTemplateId:zod.z.string().nullish(),PlatformTemplate:IC.nullish(),Settings:zod.z.array(cp).nullish(),FreePerDay:zod.z.number().nullish(),FreeLeftToday:zod.z.number().nullish()}).passthrough(),dp=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),vC).nullish()}).passthrough(),Be={GetDefinitions:"GetDefinitions",GenerateText:"GenerateText",GetText:"GetText",GenerateImage:"GenerateImage",EditImage:"EditImage",GenerateVideo:"GenerateVideo",GetVideo:"GetVideo",GenerateAudio:"GenerateAudio",GenerateMusic:"GenerateMusic",GenerateThreeD:"GenerateThreeD",GetThreeD:"GetThreeD",ListGenerations:"ListGenerations",GetGeneration:"GetGeneration",GetImage:"GetImage",GetAudio:"GetAudio",GetMusic:"GetMusic",GenerateFromTemplate:"GenerateFromTemplate",EstimateTemplatePrice:"EstimateTemplatePrice"};var hp="AI",TC=/^[A-Za-z0-9_-]{1,128}$/,AC=2e3,wC=5e3,kC=30*6e4;function zC(n,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,n);e?.addEventListener("abort",i,{once:true});})}var Or=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(hp,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(hp,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,i){return this.generate(e,{Text:t},i,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,i){return this.generate(e,{TemplateInputs:t},i,s=>this.ctx.api.ai.generateFromTemplate(s))}async estimateTemplatePrice(e,t,i){return e?this.ctx.auth.context?this.ctx.api.ai.estimateTemplatePrice({...this.ctx.buildAuthedBaseRequest(),FeatureKey:e,Params:t,Variables:i}):a:u("client","FeatureKey is required.")}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):a}async getGeneration(e){if(!e)return u("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):a}isTerminal(e){return Qi(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let c=await this.getGeneration(e);if(!c.ok)return c;i=c.data;}else {if(!e?.GenerationID)return u("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??kC),r=Math.max(1,t.intervalMs??AC),o=Math.max(r,t.maxIntervalMs??wC);for(;!Qi(i.Status);){if(t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");if(Date.now()+r>s)return u("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await zC(r,t.signal),t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");let c=await this.pollFor(i);if(r=Math.min(o,Math.round(r*1.5)),!c.ok){if(c.reason==="connection")continue;return c}i=c.data,Qi(i.Status)||t.onUpdate?.(i);}return F(i)}pollFor(e){switch(e.Modality){case Ht.Text:return this.getText(e.GenerationID);case Ht.Image:return this.getImage(e.GenerationID);case Ht.Audio:return this.getAudio(e.GenerationID);case Ht.Music:return this.getMusic(e.GenerationID);case Ht.Video:return this.getVideo(e.GenerationID);case Ht.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,s){if(!e)return u("client","FeatureKey is required.");let r=i?.relatedEntityID;if(r!==void 0&&!TC.test(r))return u("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,Variables:i?.variables,Params:i?.params,Context:i?.context,RelatedEntityID:r??G()},c=await s(o);return c.ok&&!c.data.CreditsConfirmation&&(await this.reconcileCharge(c.data,true),this.emitView(c.data)),c}async poll(e,t){if(!e)return u("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.GenerationID=e;let s=await t(i);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===oi.Completed&&!this.rewarded.has(e.GenerationID)&&(this.rewarded.add(e.GenerationID),await this.ctx.userService.getUserInventory()),!(!t||!e.Charge||this.charged.has(e.GenerationID))&&(this.charged.add(e.GenerationID),this.ctx.data.user.applyResourceOperation(e.Charge,this.ctx.data.config.itemDefinitions));}emitView(e){this.ctx.emitter.emit("ai:generationUpdated",e),e.Status===oi.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===oi.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Sa="Collection",Er=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let i=e.cache.configSection(Sa),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let r=e.cache.configSection("Season");return Object.values(r?.Chains??{}).some(c=>(c?.Seasons??[]).some(h=>!!h?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Sa,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Sa,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,s){let r=this.ctx.auth.context;if(!r)return a;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${r.userID}_${G()}`},c=await this.ctx.api.collection.openPack(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",c.data)),c}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return a;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${G()}`},o=await this.ctx.api.collection.openCollectionChest(r);return o.ok&&(this.ctx.data.user.applyResourcesWithDelta(o.data.Resources,o.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",o.data)),o}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${G()}`},r=await this.ctx.api.collection.useCollectibleJoker(s);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",r.data)),r}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${G()}`},r=await this.ctx.api.collection.claimSetReward(s);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",r.data)),r}async claimSetRewardsBatch(e){if(!e||e.length===0)return u("client","sets is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let s=false;for(let r of i.data)!s&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${G()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,r,o=false){let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:r,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${c.userID}_${s}_${G()}`},g=await this.ctx.api.collection.sendTradeOffer(h);return g.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",g.data)),g}async cancelTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${G()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${G()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${G()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var MC=zod.z.object({}).passthrough().transform(n=>n),OC={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},EC={Active:"Active",Left:"Left",Replaced:"Replaced"},UC=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),qC=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Le.nullish(),BuildObjectsProgress:UC.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),LC=zod.z.object({Index:zod.z.number().nullish(),OwnerUserID:zod.z.string().nullish(),CurrentProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish(),IsCompleted:zod.z.boolean().nullish()}).passthrough(),BC=zod.z.object({Objects:zod.z.array(LC).nullish()}).passthrough(),mp=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CoopChainID:zod.z.string().nullish(),CoopEventID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),Members:zod.z.array(qC).nullish(),BuildObjectsState:BC.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:zod.z.number().nullish()}).passthrough(),fp=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>gp).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),GC=zod.z.string(),xa=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Weight:zod.z.number().nullish(),MinProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish()}).passthrough(),FC=zod.z.object({Index:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxProgress:zod.z.number().nullish(),CompletionReward:Q.nullish()}).passthrough(),NC=zod.z.object({Objects:zod.z.array(FC).nullish(),PriceOptions:ae.nullish(),SpinnerTable:zod.z.array(xa).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),gp=zod.z.object({CoopEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),EventType:GC.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:NC.nullish(),GrandPrize:Q.nullish()}).passthrough(),_C=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Events:zod.z.array(gp).nullish(),Gate:Z.nullish()}).passthrough(),Ur=zod.z.object({ServerTimeUtc:p.nullish(),UserState:MC.nullish(),ActiveGroup:mp.nullish()}),ba=zod.z.object({ServerTimeUtc:p.nullish(),Group:mp.nullish(),SecondsRemaining:W.nullish()}),yp=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Resources:O.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:xa.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(xa).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),Da=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:O.nullish(),Inventory:H.nullish()}),Rp=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),qr=zod.z.object({Chains:zod.z.record(zod.z.string(),_C).nullish()}).passthrough(),St={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Cp="CoopEvent",Sp={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},Lr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Sp,{schema:Ur,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Cp,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Cp,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return u("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(Sp,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return u("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return u("client","CoopChainID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let s=i.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,s,r){if(!e||!t)return u("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,CreditsConfirmationID:r,RelatedEntityID:G()},c=await this.ctx.api.coopEvent.spin(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(c.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",c.data)),c}async claimObjectReward(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var VC={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},jC={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},WC=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:p.nullish(),CompletedAtUtc:p.nullish(),LastExecutedAtUtc:p.nullish(),NextAvailableAtUtc:p.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),HC=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),xp=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:p.nullish(),ExhaustedAtUtc:p.nullish(),ExpiredAtUtc:p.nullish(),DismissedAtUtc:p.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:p.nullish(),Nodes:zod.z.record(zod.z.string(),WC).nullish(),Tracks:zod.z.record(zod.z.string(),HC).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),KC=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:p.nullish(),ActiveOfferExpiresAtUtc:p.nullish(),ActiveOffer:xp.nullish(),NextCycleStartsAtUtc:p.nullish(),LastUpdatedUtc:p.nullish(),DismissSkipAvailableAtUtc:p.nullish(),LastDismissedAtUtc:p.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),QC=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),$C=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:p.nullish(),LastActivatedAtUtc:p.nullish(),LastExhaustedAtUtc:p.nullish(),NodeCounts:zod.z.record(zod.z.string(),QC).nullish()}).passthrough(),JC=zod.z.object({Slots:zod.z.record(zod.z.string(),KC).nullish(),OfferHistory:zod.z.record(zod.z.string(),$C).nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),ZC={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},YC={Eq:"Eq",Gte:"Gte",Lte:"Lte"},XC=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),Br=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),bp=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),Dp=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),eS=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Behaviour:K.nullish()}).passthrough(),tS=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:Br.nullish(),Availability:bp.nullish(),Behaviour:Dp.nullish(),Queue:zod.z.array(XC).nullish(),Presets:eS.nullish()}).passthrough(),iS=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),sS=zod.z.object({RewardedVideo:iS.nullish()}).passthrough(),rS=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),nS=zod.z.object({Identity:K.nullish(),Graph:K.nullish(),Milestones:K.nullish()}).passthrough(),oS=zod.z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish()}).passthrough(),aS=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),lS=zod.z.object({TrackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),StartValue:zod.z.number().nullish(),MinValue:zod.z.number().nullish(),MaxValue:zod.z.number().nullish(),ClampToMin:zod.z.boolean().nullish(),ClampToMax:zod.z.boolean().nullish(),HiddenFromUI:zod.z.boolean().nullish()}).passthrough(),uS=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(rS).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),Pp=zod.z.object({Options:ae.nullish()}).passthrough(),Ip=zod.z.object({Grants:Q.nullish(),TrackChanges:zod.z.array(aS).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),cS=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:Br.nullish(),Pricing:Pp.nullish(),Reward:Ip.nullish(),Action:sS.nullish(),UnlockRules:uS.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:Se.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:oS.nullish()}).passthrough(),vp=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(cS).nullish(),Tracks:zod.z.array(lS).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),Tp=zod.z.object({Milestones:zod.z.record(zod.z.string(),_e).nullish(),ClaimMode:zod.z.string().nullish(),Token:ri.nullish()}).passthrough(),Ap=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:Br.nullish(),Graph:vp.nullish(),Milestones:Tp.nullish(),Presets:nS.nullish()}).passthrough(),pS=zod.z.object({Identity:zod.z.record(zod.z.string(),Br).nullish(),Availability:zod.z.record(zod.z.string(),bp).nullish(),Behaviour:zod.z.record(zod.z.string(),Dp).nullish(),Graph:zod.z.record(zod.z.string(),vp).nullish(),Milestones:zod.z.record(zod.z.string(),Tp).nullish(),Pricing:zod.z.record(zod.z.string(),Pp).nullish(),Reward:zod.z.record(zod.z.string(),Ip).nullish()}).passthrough(),Pa=zod.z.object({Slots:zod.z.record(zod.z.string(),tS).nullish(),Offers:zod.z.record(zod.z.string(),Ap).nullish(),Presets:pS.nullish()}).passthrough(),wp=zod.z.object({DealOfferDefinitions:Pa.nullish()}),kp=zod.z.object({DealOffers:JC.nullish()}),dS=zod.z.object({EntityID:zod.z.string().nullish(),TotalEarned:zod.z.number().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),ReachedUnclaimedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),hS=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:Ap.nullish(),ActivationState:xp.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:p.nullish(),Cost:zt.nullish(),Milestone:dS.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),Gr=zod.z.object({Slots:zod.z.array(hS).nullish()}),zp=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:H.nullish()}),Mp=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),Op=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),Ep=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:H.nullish()}),Up=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:O.nullish(),Inventory:H.nullish()}),Pt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var mS="DealOffer",qp={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},Fr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(qp,{schema:Gr,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(mS,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(qp,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${G()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,s){if(!e||!t)return u("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return a;let r=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:r??`deal_exec_${e}_${t}_${G()}`},c=await this.ctx.api.dealOffer.executeNode(o);return c.ok&&!c.data.CreditsConfirmation&&(c.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",c.data)),c}async recordShow(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${G()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return u("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${G()}`},s=await this.ctx.api.dealOffer.claimMilestone(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${G()}`},r=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",r.data)),r}};var Lp="Referral",Nr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Lp,e);if(t){let r={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",r),F(r)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Lp,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=si.parseReferralCode(e)?.toUpperCase();if(!t)return u("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},r=await this.ctx.api.referral.activateReferralCode(s);if(r.ok){let o=r.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID,o.QualificationPending),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return r}async claimInviteReward(e){let t=e.trim();if(!t)return u("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},r=await this.ctx.api.referral.claimInviteReward(s);if(r.ok){let o=r.data;o.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(o.RewardID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",o);}return r}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return u("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},r=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(r.ok){let o=r.data;for(let c of o.Items??[])c.Success&&c.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(c.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return r}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.checkQualification(e);return t.ok&&t.data.Qualification&&!t.data.QualificationPending&&await this.getUserState(),t}async checkQualificationIfPending(){this.ctx.data.user.state?.Referral?.QualificationPending===true&&await this.checkQualification();}};var fS={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Bp=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),gS={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},yS=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),RS={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},CS=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),nt={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},SS={Disabled:"MAILBOX_DISABLED",MessageNotFound:"MESSAGE_NOT_FOUND",MessageIDRequired:"MESSAGE_ID_REQUIRED",AlreadyClaimed:"ALREADY_CLAIMED",Expired:"EXPIRED",NoRewards:"NO_REWARDS",HasUnclaimedRewards:"HAS_UNCLAIMED_REWARDS",NotFriends:"NOT_FRIENDS",Blocked:"BLOCKED",RecipientNotFound:"RECIPIENT_NOT_FOUND",CannotGiftSelf:"CANNOT_GIFT_SELF",GiftNotFound:"GIFT_NOT_FOUND",GiftNotAllowed:"GIFT_NOT_ALLOWED",AlreadySent:"ALREADY_SENT",SendLimit:"SEND_LIMIT",NotEnoughResources:"NOT_ENOUGH_RESOURCES",AmountTooSmall:"AMOUNT_TOO_SMALL",RecipientLimit:"RECIPIENT_LIMIT",TransferDisabled:"TRANSFER_DISABLED",ResourceNotGiftable:"RESOURCE_NOT_GIFTABLE",AmountTooLarge:"AMOUNT_TOO_LARGE",AmountInvalid:"AMOUNT_INVALID",TooManyEntries:"TOO_MANY_ENTRIES",EntriesRequired:"ENTRIES_REQUIRED",FriendshipTooNew:"FRIENDSHIP_TOO_NEW",RequestIDRequired:"RELATED_ENTITY_ID_REQUIRED",CryptoForbidden:"CRYPTO_FORBIDDEN",ModuleRewardUnavailable:"MODULE_REWARD_UNAVAILABLE",Conflict:"CONFLICT"},xS=100,bS=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),Gp=zod.z.object({FeatureID:zod.z.string().nullish(),Args:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Url:zod.z.string().nullish(),Label:zod.z.string().nullish()}).passthrough(),DS=zod.z.object({Texts:zod.z.record(zod.z.string(),bS).nullish(),Category:Bp.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:Gp.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),PS=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:pe.nullish(),Cost:pe.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:p.nullish(),SenderGate:Z.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),IS=zod.z.object({Type:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxAmountPerGift:zod.z.number().nullish()}).passthrough(),vS=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(IS).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:p.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:pe.nullish(),SenderGate:Z.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),Fp=zod.z.object({Enabled:zod.z.boolean().nullish(),Capacity:zod.z.number().nullish(),RewardLetterDays:zod.z.number().nullish(),PlainLetterDays:zod.z.number().nullish(),ClaimedRetentionDays:zod.z.number().nullish(),DefaultLanguage:zod.z.string().nullish(),Templates:zod.z.record(zod.z.string(),DS).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),PS).nullish(),Transfer:vS.nullish()}).passthrough().nullish(),Integrations:zod.z.object({Leaderboard:zod.z.boolean().nullish(),CoopEvent:zod.z.boolean().nullish(),Season:zod.z.boolean().nullish(),Referral:zod.z.boolean().nullish()}).passthrough().nullish()}).passthrough(),TS=zod.z.object({MessageID:zod.z.string(),Source:yS,Category:Bp,TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:Gp.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:Q.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:p,ExpiresAt:p.nullish(),ReadAt:p.nullish(),ClaimedAt:p.nullish()}).passthrough(),AS=zod.z.object({MessageID:zod.z.string(),Module:CS,Key:zod.z.string(),TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:Q.nullish()}).passthrough(),Ia=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),Np=zod.z.object({ServerTimeUtc:p.nullish(),Messages:zod.z.array(TS).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(AS).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),_r=zod.z.object({ServerTimeUtc:p.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),va=zod.z.object({ServerTimeUtc:p.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(Ia).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),wS=zod.z.object({MessageID:zod.z.string(),Rewards:pe.nullish()}).passthrough(),Vr=zod.z.object({ServerTimeUtc:p.nullish(),Claimed:zod.z.array(wS).default([]),Failed:zod.z.array(Ia).default([]),Resources:O.nullish(),Inventory:H.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),_p=zod.z.object({ServerTimeUtc:p.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(Ia).default([]),Resources:O.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish()}).passthrough(),Vp=zod.z.object({ServerTimeUtc:p.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish(),RecipientReceives:pe.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),jp=zod.z.object({ServerTimeUtc:p.nullish(),ResetsAt:p.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:p.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish()}).passthrough().nullish()}).passthrough();var Ta="Mailbox",Aa={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},jr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Aa,{schema:_r,apply:t=>this.emitCounters(t)});}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}emitCounters(e){if(e.UnreadCount==null||e.UnclaimedCount==null)return;let t={UnreadCount:e.UnreadCount,UnclaimedCount:e.UnclaimedCount};this.ctx.cache.put(Aa,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Ta)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Ta,e);if(t)return F(t);let i=this.request();if(!i)return a;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(Ta,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return a;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(Aa,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return a;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return a;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return u("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):a}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return u("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):a}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):a}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return a;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return u("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return u("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return a;let r=await this.ctx.api.mailbox.sendGift(s);return r.ok&&(r.data.Resources&&this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",r.data)),r}async sendTransfer(e,t,i){if(!e?.trim())return u("client","RecipientUserID is required.");if(!i?.requestID?.trim())return u("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return a;let r=await this.ctx.api.mailbox.sendTransfer(s);return r.ok&&(r.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(r.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",r.data)),r}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):a}};var Wr={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},wa="idos-app",Wp=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),Allowed:zod.z.boolean(),DenyReason:zod.z.string().nullish(),Message:zod.z.string().nullish(),RetryAfterSeconds:zod.z.number().nullish(),RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),AdUnitID:zod.z.string().nullish(),Type:zod.z.string().nullish(),ExpiresAtUtc:zod.z.string().nullish(),CreditsToAward:zod.z.number().nullish(),RequiresServerSideVerification:zod.z.boolean().nullish()}),Hp=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),RequestID:zod.z.string().nullish(),Status:zod.z.string(),CreditsAwarded:zod.z.number().nullish(),RetryAfterSeconds:zod.z.number().nullish(),ExpiresAtUtc:zod.z.string().nullish(),AlreadyProcessed:zod.z.boolean().nullish(),GrantedWithoutSsv:zod.z.boolean().nullish(),Resources:O.nullish()});var kS=new Set(["CANCELLED","DECLINED","CLOSED"]),zS=45e3,MS=n=>new Promise(e=>setTimeout(e,n)),Hr=class{constructor(e){this.ctx=e;}ctx;get available(){return this.ctx.host.supports.rewardedAds}async showRewarded(e){if(!this.ctx.host.supports.rewardedAds)return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let i=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!i.ok)return {status:"unavailable",reason:i.error};let s=i.data;if(!s.Allowed)return {status:"denied",reason:s.DenyReason??void 0,retryAfterSeconds:s.RetryAfterSeconds??void 0};if(!s.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let r=null;if(s.ProviderID!==wa&&(r=this.titleProvider(s.ProviderID),!r))return {status:"unavailable",reason:"NO_WEB_ADS"};let o=await this.ctx.host.showRewardedAd({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:s.RequestID,placementID:e,adUnitID:s.AdUnitID,provider:r});return o.ok?{...await this.awaitReward(s.RequestID,o.via),requestID:s.RequestID}:{status:kS.has(o.error??"")?"cancelled":"unavailable",reason:o.error}}titleProvider(e){if(!this.ctx.host.supports.titleAds||!e)return null;let i=this.ctx.data.config.getSection("Advertising")?.Providers?.[e];if(!i||i.Enabled===false)return null;let s=this.ctx.host.getClientPlatform(),r=s===Ee.Android?i.AndroidAppID:s===Ee.Ios?i.IosAppID:i.WebAppID;return r?{id:e,kind:i.Kind??"AppLovinMax",appKey:r}:null}async awaitReward(e,t){let i=Date.now()+zS;for(;;){let s=this.ctx.authedRequest();if(!s)return {status:"pending",via:t};let r=await this.ctx.api.advertising.completeView({...s,RequestID:e});if(r.ok&&r.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:r.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((r.ok?r.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>i)return {status:"pending",via:t,reason:r.ok?void 0:r.error};await MS(o);}}};var OS={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},ES={Title:"Title",Platform:"Platform"},Kp=zod.z.object({UserID:zod.z.string(),PublicData:Le.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),$i=zod.z.object({Friends:zod.z.array(Kp).nullish()}),US=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),Ji=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:Kp.nullish(),Counters:US.nullish()}),qS={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},LS={Like:"Like",Favorite:"Favorite"},BS={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},GS={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},FS={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},NS=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),_S=zod.z.object({Id:zod.z.string(),Verb:zod.z.string().nullish(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Count:zod.z.number().nullish(),LastActors:zod.z.array(NS).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),OccurredAt:p.nullish(),OwnerImpact:O.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),Qp=zod.z.object({Items:zod.z.array(_S).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:p.nullish()}).passthrough(),Zi=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:p.nullish()}).passthrough(),VS=zod.z.object({Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),Followers:zod.z.number().nullish(),Following:zod.z.number().nullish(),Comments:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Posts:zod.z.number().nullish(),Dislikes:zod.z.number().nullish()}).passthrough(),Kt=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:VS.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),$p=zod.z.object({Items:zod.z.array(Kt).nullish()}).passthrough(),ka={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},jS=zod.z.object({UserID:zod.z.string(),PublicData:Le.nullish(),Mutual:zod.z.boolean().nullish(),Since:p.nullish()}).passthrough(),Kr=zod.z.object({Items:zod.z.array(jS).nullish(),...ka}).passthrough(),WS=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:p.nullish()}).passthrough(),Jp=zod.z.object({Items:zod.z.array(WS).nullish(),...ka}).passthrough(),Qr=zod.z.object({CommentID:zod.z.string(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),ParentCommentID:zod.z.string().nullish(),AuthorUserID:zod.z.string().nullish(),AuthorPublicData:Le.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:p.nullish(),EditedAt:p.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Zp=zod.z.object({Items:zod.z.array(Qr).nullish(),...ka,TotalCount:zod.z.number().nullish()}).passthrough(),Yp=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),Xp=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),ed=zod.z.object({CommentsEnabled:zod.z.boolean().nullish(),CommentableTypes:zod.z.array(zod.z.string()).nullish(),CommentMaxLength:zod.z.number().nullish(),CommentMaxLinks:zod.z.number().nullish()}).passthrough(),HS="FRIENDS_FROM_PLATFORM",KS={Off:"Off",Default:"Default",Always:"Always"},QS={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},td=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:zod.z.boolean().nullish()}).passthrough(),xe={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report"};var za={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},$r=class{constructor(e){this.ctx=e;e.cache.bindLoginView(za,{schema:Zi,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return a;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return u("client","TargetUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return u("client","FriendUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return a;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(za,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(za,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):a}async getEntityStates(e,t){if(!t?.length)return u("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):a}async addComment(e,t,i,s){let r=this.targetRequest(e,t);if("ok"in r)return r;if(!i?.trim())return u("client","Text is required.");r.Text=i,r.ParentCommentID=s;let o=await this.ctx.api.social.addComment(r);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return u("client","CommentID is required.");if(!t?.trim())return u("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return a;i.CommentID=e,i.Text=t;let s=await this.ctx.api.social.editComment(i);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return u("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=i.parentCommentID,this.applyPage(s,i.cursor,i.limit),this.ctx.api.social.getComments(s))}async report(e,t,i,s){let r=this.targetRequest(e,t);if("ok"in r)return r;if(!i)return u("client","ReportReason is required.");r.ReportReason=i,r.ReportComment=s;let o=await this.ctx.api.social.report(r);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,s){let r=this.targetRequest(t,i);if("ok"in r)return r;r.ReactionKind=s;let o=await this.ctx.api.social[e](r);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):a}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return u("client","EntityType is required.");if(!t)return u("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):a}};var id="TimedBoost";function $S(n){return n.length>0&&!n.includes(".")&&!n.includes("$")}var Jr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(id,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),F(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(id,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let i=e.trim();if(!$S(i))return u("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${i}_${G()}`},r=await this.ctx.api.timedBoost.activate(s);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;if(o.ActivatedBoost){let c=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,c);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return r}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var qt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},JS={Client:"Client",Server:"Server",System:"System"},ZS=zod.z.enum(["Client","Server","System"]).catch("Client"),YS=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:p.nullish(),Version:zod.z.number().nullish(),LastWriter:ZS.nullish(),ExpiresAt:p.nullish()}).passthrough(),Zr=zod.z.record(zod.z.string(),YS),sd=zod.z.object({Version:zod.z.number().nullish(),Private:Zr.nullish(),Public:Zr.nullish(),ReadOnly:Zr.nullish()}),Ma=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Zr.nullish()}),Oa=zod.z.object({ServerTimeUtc:p.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:p.nullish()}),XS=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:p.nullish()}),rd=zod.z.object({ServerTimeUtc:p.nullish(),Results:zod.z.array(XS).nullish()}),nd=zod.z.object({ServerTimeUtc:p.nullish(),DeletedCount:zod.z.number().nullish()}),od=zod.z.object({Results:zod.z.array(Ma).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),ex={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},tx=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),ix=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:tx.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Yr=zod.z.object({Keys:zod.z.record(zod.z.string(),ix).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),xt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var sx="UserCustomData";function ad(n){return n.length>0&&!n.includes(".")&&!n.includes("$")}var Xr=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(sx,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,qt.Private)}async setPublicData(e,t){return this.setData(e,t,qt.Public)}async setData(e,t,i){let s=e.trim();if(!ad(s))return u("client",'KeyID is required and must not contain "." or "$".');if(t==null)return u("client","Value is required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},c=await(i===qt.Private?this.ctx.api.userCustomData.setPrivateData(r):this.ctx.api.userCustomData.setPublicData(r));if(c.ok){let h=c.data;this.ctx.data.user.patchUserCustomDataKey(i,h.KeyID,t,h.Version??0,h.ExpiresAt),this.ctx.emitter.emit(i===qt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",h);}return c}async deleteKey(e,t){let i=e.trim();if(!ad(i))return u("client",'KeyID is required and must not contain "." or "$".');if(t!==qt.Private&&t!==qt.Public)return u("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},r=await this.ctx.api.userCustomData.deleteKey(s);return r.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),r}async batchSet(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let r=s.Bucket??qt.Private,o=e.find(c=>c.Bucket===r&&c.KeyID===s.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(r,s.KeyID,o.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return u("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var rx="TitleCustomDataDefinitions",ld=50;function nx(n){return n.length>0&&!n.includes(".")&&!n.includes("$")}function Ea(n){if(n.ExpiresAt==null)return false;let e=Date.parse(n.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function ox(n){let e={};for(let[t,i]of Object.entries(n))Ea(i)||(e[t]=i);return e}var en=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(rx,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return a;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(r=>r.trim()).filter(r=>r.length>0);if(!t.length)return u("client","At least one KeyID is required.");if(t.some(r=>!nx(r)))return u("client",'KeyID must not contain "." or "$".');if(t.length>ld)return u("client",`At most ${ld} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return a;i.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Ea(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Ea(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=ox(this.runtimeCache),e.Runtime=this.runtimeCache):e.Runtime&&(this.runtimeCache=e.Runtime),e.RuntimeVersion!=null&&(this.lastRuntimeVersion=e.RuntimeVersion),this.ctx.emitter.emit("titleCustomData:publicDataLoaded",e);}};var tn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var ax=15,lx="GameLoop",ud="BoardDefinition",sn=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(lx,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(ud,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),F(i);let s=this.ctx.authedRequest();if(!s)return a;let r=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return r.ok&&(this.ctx.data.config.patchSection(ud,r.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",r.data)),r}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return u("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return a;i.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return u("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${G()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let r=s.data,o=Fu(new Date,ax);this.ctx.data.user.patchBoardState(c=>{c.Position=r.NewPosition,c.CyclesCompleted=(c.CyclesCompleted??0)+(r.CyclesCompletedDelta??0),c.LastRollAtUtc=new Date().toISOString(),r.ActionRequired&&r.ActionData?c.Pending={Type:r.ActionRequired,TargetUserID:r.ActionData.TargetUserID,TargetPublicData:r.ActionData.PublicData,TargetBuildingStates:r.ActionData.TargetBuildingStates??void 0,TargetHasShield:r.ActionData.TargetHasShield??void 0,RollMultiplier:r.UsedMultiplier??1,ExpiresAtUtc:o}:r.SpecialModeOffer&&(c.Pending={Type:"SPECIAL",RollMultiplier:r.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:r.SpecialModeOffer.ModeID??void 0,Choices:r.SpecialModeOffer.Choices??void 0}});}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),r.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",r);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${G()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(i);if(s.ok){let r=s.data;this.ctx.data.user.clearBoardPending(),r.IsBotTarget&&r.Operation?this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs):!r.IsBotTarget&&r.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(r.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",r);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return u("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${G()}`},r=await this.ctx.api.gameLoop.boardLoopRaid(s);if(r.ok){let o=r.data;o.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(o.RaidLayout,o.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(o)),this.ctx.emitter.emit("gameLoop:boardRaided",o);}else await this.getUserBoardState();return r}async boardLoopRaidFast(e){if(!e.length)return u("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${G()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(s.ok){let r=s.data;r.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(r)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",r);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return u("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${G()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let r=s.data;r.StageComplete?this.ctx.data.user.patchBoardState(o=>{o.StageLevel=(o.StageLevel??1)+1,o.Position=0,o.Pending=null,o.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(r.BuiltIndex,o=>{r.NewLevel!=null&&(o.Level=r.NewLevel),o.IsDamaged=false,r.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",r);}return s}async boardSpecialChoose(e,t,i){if(!e)return u("client","choiceID must not be empty.");let s=this.ctx.auth.context;if(!s)return a;let r={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:i,RelatedEntityID:`special_choose_${s.userID}_${G()}`},o=await this.ctx.api.gameLoop.boardSpecialChoose(r);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;c.Mode==="Instant"||c.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(g=>{g.ChoiceID=e,g.ChosenMode=c.Mode??"Timed",g.StartedAtUtc=c.StartedAtUtc??null,g.DurationSeconds=c.DurationSeconds??null,g.AdViewsUsed=0;}),c.Operation&&this.ctx.data.user.applyResourcesWithDelta(c.Operation,c.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",c);}return o}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${G()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let r=s.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=r.AdViewsUsed??0,o.AccumulatedMultiplier=r.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",r);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${G()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(s.ok){let r=s.data;this.ctx.data.user.clearBoardPending(),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",r);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return u("client","milestoneID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var rn=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let r=e.trim();if(!r)return u("client","FunctionName is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:r,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},c=await this.ctx.api.cloudCode.execute(o);return c.ok&&this.ctx.emitter.emit("cloudCode:executed",c.data),c}};var cd=zod.z.object({ServerTimeUtc:p,SourceType:Ri,SourceID:zod.z.string(),TargetType:Ri,TargetID:zod.z.string(),SourceSpent:W,FeeAmount:W,RateApplied:Y,TargetCredited:W}),pd=zod.z.object({ServerTimeUtc:p,SourceType:Ri,SourceID:zod.z.string(),TargetType:Ri,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),dd=zod.z.object({ServerTimeUtc:p,SpendID:zod.z.string(),Resources:O.nullish()}),Yi={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},ux={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},hd=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),cx={Automatic:"Automatic",Manual:"Manual"},px=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),dx=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),hx=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),mx=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),fx=zod.z.object({TargetCurrencyType:Ri.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),md=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:px.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(fx).nullish()}).passthrough(),fd=zod.z.object({CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough(),gx=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:dx.nullish(),Recharge:hx.nullish(),Conversion:md.nullish(),Permissions:mx.nullish(),Audit:fd.nullish(),Status:hd.nullish()}).passthrough(),yx=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),Rx=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),Cx=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),Sx=zod.z.object({Mode:zod.z.string().nullish(),FundingNetworkID:zod.z.string().nullish(),PerPlayerDailyTokens:zod.z.number().nullish(),TitleDailyTokens:zod.z.number().nullish(),RefuseOverCap:zod.z.boolean().nullish()}).passthrough(),Ua=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),DisplayDecimals:zod.z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:zod.z.array(yx).nullish(),Limits:Rx.nullish(),Permissions:Cx.nullish(),Conversion:md.nullish(),Audit:fd.nullish(),Status:hd.nullish(),ServerGrantPolicy:Sx.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),xx=zod.z.object({SpendID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),PriceOptions:zod.z.record(zod.z.string(),Hs).nullish()}).passthrough(),nn=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),gx).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),Ua).nullish(),Spends:zod.z.record(zod.z.string(),xx).nullish()}).passthrough();var bx={EVM:"EVM",Solana:"Solana"},Dx=zod.z.enum(["EVM","Solana"]).catch("EVM"),Px={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},Ix=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),vx={Token:"Token",Nft:"Nft"},gd=zod.z.enum(["Token","Nft"]).catch("Token"),Tx={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},Ax=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),wx={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},kx=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),zx={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},qa=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),yd={GameTopUp:"game_topup",CommunityReward:"community_reward"};function on(n){let e=n?.trim();return e||yd.GameTopUp}var Mx={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},Rd=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),Ox=zod.z.object({ContractAddress:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),Cd=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),Ex=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:Dx.nullish(),ChainID:zod.z.number().nullish(),ChainTicker:zod.z.string().nullish(),RewardPoolAddress:zod.z.string().nullish(),VaultDepositAddress:zod.z.string().nullish(),ChainConfigVersion:zod.z.number().nullish(),RequiredConfirmations:zod.z.number().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Cd.nullish(),NftCollections:zod.z.array(Ox).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RpcUrl:zod.z.string().nullish(),GasPrice:zod.z.number().nullish(),NftBridgeAddress:zod.z.string().nullish(),SignatureEpoch:zod.z.number().nullish()}).passthrough(),Ux=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Cd.nullish()}).passthrough(),qx=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),Lx={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},Bx=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Sd=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:Bx.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),Gx=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),Fx={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Xi=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),Nx=zod.z.object({Mode:Xi.nullish(),TokenGates:zod.z.array(Sd).nullish()}).passthrough(),La=zod.z.object({SystemState:Ux.nullish(),Networks:zod.z.record(zod.z.string(),Ex).nullish(),AccountSafety:qx.nullish(),WalletLogin:Gx.nullish(),PlayAccess:Nx.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),_x=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:p.nullish(),LastUsedAt:p.nullish(),LinkType:Ix.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),xd=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:gd.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),Vx=zod.z.object({Status:Ax.nullish(),Tier:kx.nullish(),VerifiedAt:p.nullish(),ExpiresAt:p.nullish(),RejectedAt:p.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),jx=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),Wx=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:zod.z.record(zod.z.string(),jx).nullish()}).passthrough(),Hx=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),Kx=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),PerCollection:zod.z.record(zod.z.string(),Hx).nullish()}).passthrough(),Qx=zod.z.object({Tokens:Wx.nullish(),Nfts:Kx.nullish()}).passthrough(),Ba=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Qt=zod.z.object({Granted:zod.z.boolean(),Mode:Xi.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:p.nullish(),Balances:zod.z.array(Ba).nullish()}).passthrough(),$x=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:p.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:p.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(Ba).nullish()}).passthrough(),Jx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),bd=zod.z.object({Mode:Xi.nullish(),TokenGates:zod.z.array(Sd).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(Jx).nullish(),Status:Qt.nullish()}).passthrough(),Zx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:p.nullish(),LoggedInAt:p.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(Ba).nullish()}).passthrough(),Yx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:p.nullish()}).passthrough(),Xx=zod.z.object({Version:zod.z.number().nullish(),Stats:Qx.nullish(),LinkedWallets:zod.z.record(zod.z.string(),_x).nullish(),LastWalletLogin:Zx.nullish(),PlayAccess:$x.nullish(),PendingWithdrawals:zod.z.array(xd).nullish(),Kyc:Vx.nullish(),FirstActivityAt:p.nullish(),LastActivityAt:p.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(Yx).nullish()}).passthrough(),eb=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:p}).passthrough(),wi=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),eb).nullish(),PendingAdded:xd.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),tb=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough().transform(n=>n),ib=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Rd.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:qa.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:p.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:p.nullish(),RefundCheckedAt:p.nullish()}).passthrough(),sb=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Rd.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:qa.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:p.nullish()}).passthrough(),Dd=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Ga=zod.z.object({TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ContractAddress:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(Dd).nullish(),Signature:zod.z.string().nullish()}).passthrough(),Fa=zod.z.object({Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),ProgramID:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(Dd).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Pd=zod.z.object({Blockchain:La.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),Ua).nullish()}).passthrough(),Id=zod.z.object({State:Xx.nullish(),CryptoBalances:zod.z.record(zod.z.string(),tb).nullish()}).passthrough(),vd=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:wi.nullish()}).passthrough(),Td=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:O.nullish(),Inventory:H.nullish()}).passthrough(),Ad=zod.z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:p.nullish(),EvmSignature:Ga.nullish(),SolanaSignature:Fa.nullish(),StateDelta:wi.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),wd=zod.z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish(),EvmSignature:Ga.nullish(),SolanaSignature:Fa.nullish(),StateDelta:wi.nullish(),Inventory:H.nullish()}).passthrough(),kd=zod.z.object({TokenTransactions:zod.z.array(ib).nullish(),NFTTransactions:zod.z.array(sb).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Na=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:zod.z.string().nullish()}).passthrough(),zd=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:gd.nullish(),EvmSignature:Ga.nullish(),SolanaSignature:Fa.nullish()}).passthrough(),Md=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:qa.nullish(),StateDelta:wi.nullish()}).passthrough(),Ye={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",DepositToken:"DepositToken",DepositNFT:"DepositNFT",RequestTokenWithdrawal:"RequestTokenWithdrawal",RequestNFTWithdrawal:"RequestNFTWithdrawal",GetTransactionHistory:"GetTransactionHistory",RetryWithdrawal:"RetryWithdrawal",ConfirmWithdrawal:"ConfirmWithdrawal",DonateToDeveloper:"DonateToDeveloper",DonateToUsersPool:"DonateToUsersPool",GetPlayAccess:"GetPlayAccess",ConfirmPlayAccess:"ConfirmPlayAccess"};var rb="Blockchain",Od="Blockchain:Definitions",an=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Od,e);if(t)return F(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return a;let s=this.ctx.api.blockchain.getDefinitions(i).then(r=>(r.ok&&(this.ctx.data.config.patchSection(rb,r.data.Blockchain),this.ctx.data.config.patchSection(Od,r.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",r.data)),r)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,i,s,r){if(!e)return u("client","CurrencyID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!s)return u("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return a;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=s,o.Category=on(r);let c=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return c.ok&&(this.ctx.data.user.applyBlockchainStateDelta(c.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",c.data)),c}async requestNFTWithdrawal(e,t,i,s,r,o,c){if(!e)return u("client","ItemID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!s)return u("client","Amount is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.NetworkID=t,h.WalletAddress=i,h.Amount=s,h.Category=on(r),o!==void 0&&(h.Level=o),c&&(h.ItemInstanceID=c);let g=await this.ctx.api.blockchain.requestNFTWithdrawal(h);return g.ok&&(this.ctx.data.user.applyBlockchainStateDelta(g.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(g.data.Resources,g.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",g.data)),g}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return a;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return u("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return u("client","TitleTransactionID is required.");if(!t)return u("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TitleTransactionID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var nb={Head:"Head",Torso:"Torso",Legs:"Legs"},ln=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),ob={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},_a=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Ud=zod.z.object({AttackTarget:ln,DefenseTarget:ln});var ab=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),lb=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:ln.nullish(),DefenseZone:ln.nullish(),HitType:ab.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),ub=zod.z.object({MaxHp:zod.z.number().nullish(),CurrentHp:zod.z.number().nullish(),Damage:zod.z.number().nullish(),AttackSpeed:zod.z.number().nullish(),CritChance:zod.z.number().nullish(),CritMultiplier:zod.z.number().nullish(),Armor:zod.z.number().nullish(),DodgeChance:zod.z.number().nullish()}).passthrough(),cb=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(n=>n),Ed=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:ha.nullish(),BattleStrategy:zod.z.array(Ud).nullish(),UnstackableItems:zod.z.record(zod.z.string(),cb).nullish(),Stats:ub.nullish()}).passthrough(),pb=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:pe.nullish(),NetReward:pe.nullish(),BattleLog:zod.z.array(lb).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:Ed.nullish(),P2BattleProfile:Ed.nullish()}).passthrough(),qd=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:p.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(Ud).nullish(),TargetUserID:zod.z.string().nullish(),Entry:pe.nullish(),CreationCostPaid:pe.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:p.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:p.nullish(),Status:_a.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:p.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:p.nullish()}).passthrough(),Ld=zod.z.object({Status:_a,MatchID:zod.z.string(),Entry:pe.nullish(),Resources:O.nullish()}),Bd=zod.z.object({Match:qd.nullish()}),Gd=zod.z.object({MatchID:zod.z.string(),Status:_a,Resources:O.nullish()}),Fd=zod.z.object({Battle:pb.nullish(),Resources:O.nullish(),ResourcesDual:Mt.nullish()}),Va=zod.z.object({Matches:zod.z.array(qd).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),It={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var db=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var hb=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),mb=zod.z.object({HealthStatID:zod.z.string().nullish(),DamageStatID:zod.z.string().nullish(),ArmorStatID:zod.z.string().nullish(),AttackSpeedStatID:zod.z.string().nullish(),CritChanceStatID:zod.z.string().nullish(),CritDamageStatID:zod.z.string().nullish(),DodgeStatID:zod.z.string().nullish(),AllMightStatID:zod.z.string().nullish()}).passthrough(),fb=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),gb=zod.z.object({MaxRounds:zod.z.number().nullish(),BlockDamageMultiplier:zod.z.number().nullish(),MinHitDamage:zod.z.number().nullish(),DefaultCritMultiplier:zod.z.number().nullish(),MaxCritChance:zod.z.number().nullish(),MaxDodgeChance:zod.z.number().nullish(),ArmorMode:fb.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),yb=zod.z.object({Kind:hb.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:je.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),Rb=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(yb).nullish()}).passthrough(),ai=zod.z.object({Terms:zod.z.array(Rb).nullish()}).passthrough(),Cb=zod.z.object({Health:ai.nullish(),Damage:ai.nullish(),Armor:ai.nullish(),AttackSpeed:ai.nullish(),CritChance:ai.nullish(),CritDamage:ai.nullish(),Dodge:ai.nullish()}).passthrough(),Nd=zod.z.object({StatMapping:mb.nullish(),Combat:gb.nullish(),Formula:Cb.nullish()}).passthrough(),Sb=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),es=zod.z.object({Kind:db.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:ms.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),_d=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(es).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Vd=zod.z.object({PriceOptions:ae.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:Se.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),xb=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:Sb.nullish(),Entry:_d.nullish(),Creation:Vd.nullish(),Settings:Nd.nullish()}).passthrough(),bb=zod.z.object({Rules:zod.z.record(zod.z.string(),xb).nullish(),Defaults:Nd.nullish(),EntryDefaults:_d.nullish(),CreationDefaults:Vd.nullish()}).passthrough(),ja=zod.z.object({InstantBattle:bb.nullish()}).passthrough(),jd=ja;var Db={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Wa=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),Pb={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Ha=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),Ib={Burn:"Burn",Ledger:"Ledger"},vb=zod.z.enum(["Burn","Ledger"]).catch("Burn"),cn={Item:"Item",VirtualCurrency:"VirtualCurrency"},Ka=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),Tb=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:W.nullish()}).passthrough(),pn=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(es).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Qa=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:W.nullish(),Sink:vb.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),Tb).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),Ab=zod.z.object({AllowedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedItemIDs:zod.z.array(zod.z.string()).nullish(),AllowUnstackableWithState:zod.z.boolean().nullish(),AllowedCurrencyIDs:zod.z.array(zod.z.string()).nullish(),DeniedCurrencyIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),wb=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:Se.nullish(),BuyLimits:Se.nullish(),ListingFeeOptions:ae.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),kb=zod.z.object({Enabled:zod.z.boolean().nullish(),MinDurationHours:zod.z.number().nullish(),MaxDurationHours:zod.z.number().nullish(),AntiSnipeWindowSeconds:zod.z.number().nullish(),AntiSnipeExtensionSeconds:zod.z.number().nullish(),MaxAntiSnipeExtensions:zod.z.number().nullish(),MinBidStepPercent:zod.z.number().nullish(),MinBidStepAbsolute:W.nullish(),BidLimits:Se.nullish()}).passthrough(),zb=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:Se.nullish(),FillLimits:Se.nullish()}).passthrough(),Mb=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:Se.nullish()}).passthrough(),Ob=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),$a=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:Re.nullish(),PricePolicy:pn.nullish(),Commission:Qa.nullish(),Tradability:Ab.nullish(),Listings:wb.nullish(),Auctions:kb.nullish(),BuyOrders:zb.nullish(),DirectTrades:Mb.nullish(),Matching:Ob.nullish()}).passthrough(),Wd=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:W.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:p.nullish()}).passthrough(),Eb=zod.z.object({BidAxisType:Ci.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:W.nullish(),CurrentBid:W.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(Wd).nullish()}).passthrough(),un=zod.z.object({LastAt:p.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),Ub=zod.z.object({Create:un.nullish(),Buy:un.nullish(),Sell:un.nullish(),Bid:un.nullish()}).passthrough(),qb=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),Lb=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:qb.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(n=>n),Lt=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Wa.nullish(),Status:Ha.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:Le.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:Ka.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:W.nullish(),GoodsInstances:zod.z.array(Lb).nullish(),Price:pe.nullish(),Auction:Eb.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),Bb=zod.z.object({GoodsType:Ka.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(Wa,W).nullish()}).passthrough(),Hd=zod.z.object({Definitions:$a.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),Ja=zod.z.object({Offers:zod.z.array(Lt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Kd=zod.z.object({Groups:zod.z.array(Bb).nullish()}).passthrough(),Qd=zod.z.object({Offer:Lt.nullish()}).passthrough(),ht=zod.z.object({OfferID:zod.z.string().nullish(),Status:Ha.nullish(),Settlement:Mt.nullish(),Resources:O.nullish(),CommissionTaken:pe.nullish()}).passthrough(),ts=zod.z.object({OfferID:zod.z.string().nullish(),Offer:Lt.nullish(),Resources:O.nullish(),Matched:zod.z.boolean().nullish(),Settlement:ht.nullish()}).passthrough(),$d=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:W.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish()}).passthrough(),dn=zod.z.object({MyOffers:zod.z.array(Lt).nullish(),MyBids:zod.z.array(Lt).nullish(),MyBuyOrders:zod.z.array(Lt).nullish(),IncomingTrades:zod.z.array(Lt).nullish(),OutgoingTrades:zod.z.array(Lt).nullish(),Claimables:zod.z.array(Lt).nullish(),DrainedRefunds:zod.z.array(Wd).nullish(),Limits:Ub.nullish()}).passthrough(),Gb=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Wa.nullish(),FinalStatus:Ha.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:Ka.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:W.nullish(),PricePaid:pe.nullish(),CommissionTaken:pe.nullish(),CompletedAt:p.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),Jd=zod.z.object({Entries:zod.z.array(Gb).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Oe={GetDefinitions:"GetDefinitions",GetGroupedOffers:"GetGroupedOffers",GetOffersByItem:"GetOffersByItem",GetOffer:"GetOffer",GetBuyOrders:"GetBuyOrders",GetMyState:"GetMyState",GetHistory:"GetHistory",CreateListing:"CreateListing",CancelListing:"CancelListing",Buy:"Buy",MarketBuy:"MarketBuy",MarketSell:"MarketSell",CreateAuction:"CreateAuction",PlaceBid:"PlaceBid",ClaimAuction:"ClaimAuction",CreateBuyOrder:"CreateBuyOrder",CancelBuyOrder:"CancelBuyOrder",FillBuyOrder:"FillBuyOrder",CreateDirectTrade:"CreateDirectTrade",RespondDirectTrade:"RespondDirectTrade",CancelDirectTrade:"CancelDirectTrade",ClaimBack:"ClaimBack"};var Fb="Marketplace",Zd={key:"marketplace.myState",login:"MarketplaceMyState",ttlMs:6e4,dependsOn:["Marketplace"],invalidateOn:["marketplace:listingCreated","marketplace:listingCancelled","marketplace:bought","marketplace:marketBought","marketplace:marketSold","marketplace:auctionCreated","marketplace:bidPlaced","marketplace:auctionClaimed","marketplace:buyOrderCreated","marketplace:buyOrderCancelled","marketplace:buyOrderFilled","marketplace:directTradeCreated","marketplace:directTradeResponded","marketplace:directTradeCancelled","marketplace:claimedBack"]},hn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Zd,{schema:dn,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(Fb,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,s=20){if(!e)return u("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return a;r.ItemID=e,r.OfferTypeFilter=t,r.ContinuationToken=i,r.PageSize=s;let o=await this.ctx.api.marketplace.getOffersByItem(r);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let s=this.ctx.authedRequest();if(!s)return a;s.ItemID=e,s.ContinuationToken=t,s.PageSize=i;let r=await this.ctx.api.marketplace.getBuyOrders(s);return r.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",r.data),r}getMyState(e,t){return this.ctx.cache.read(Zd,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let s=this.ctx.authedRequest();if(!s)return a;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let r=await this.ctx.api.marketplace.getHistory(s);return r.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",r.data),r}async createListing(e,t,i,s,r,o,c){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!s)return u("client","PriceBundle is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.PriceBundle=s,h.DurationHours=r,h.ItemInstanceIDs=o,h.SelectedOptionID=c;let g=await this.ctx.api.marketplace.createListing(h);return this.applyCreateOfferResult(g,"marketplace:listingCreated"),g}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return a;let r=this.applyGoodsSelector(s,i);if(r)return r;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return a;let r=this.applyGoodsSelector(s,i);if(r)return r;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,s,r,o,c={}){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.BidAxisType=s,h.BidCurrencyID=c.bidCurrencyID,h.BidCatalogID=c.bidCatalogID,h.BidItemID=c.bidItemID,h.StartingBid=r,h.DurationHours=o,h.ItemInstanceIDs=c.itemInstanceIDs,h.SelectedOptionID=c.selectedOptionID;let g=await this.ctx.api.marketplace.createAuction(h);return this.applyCreateOfferResult(g,"marketplace:auctionCreated"),g}async placeBid(e,t){if(!e)return u("client","OfferID is required.");if(!t||t<=0)return u("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,s,r){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!s)return u("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return a;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=s,o.DurationHours=r;let c=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(c,"marketplace:buyOrderCreated"),c}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,s,r){if(!e)return u("client","TargetUserID is required.");if(!t)return u("client","CatalogID is required.");if(!i)return u("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return a;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=s,o.RequestedBundle=r;let c=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(c,"marketplace:directTradeCreated"),c}async respondDirectTrade(e,t){if(!e)return u("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(i);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return u("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.OfferID=e;let r=await t(s);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,r.data)),r}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=cn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=cn.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):u("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var mn=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return u("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let s=await this.ctx.api.multiplayer.createRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.RoomID=e,s.TargetUserID=t,s.Ban=i;let r=await this.ctx.api.multiplayer.kickMember(s);return r.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",r.data),r}async unbanMember(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return a;i.Page=e,i.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(i);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,i,s){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");if(!i)return u("client","SignalKind is required.");let r=this.ctx.authedRequest();if(!r)return a;r.RoomID=e,r.TargetUserID=t,r.SignalKind=i,r.Payload=s;let o=await this.ctx.api.multiplayer.sendSignal(r);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(i);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,i){if(!e)return u("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.RoomID=e,s.Ready=t,s.MemberState=i;let r=await this.ctx.api.multiplayer.setMemberState(s);return r.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",r.data),r}};var Yd=" (if the network is fine, the storage bucket has no CORS rule for this origin)",fn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.ParentContentID=e.parentContentID,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):a}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return u("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):a}async getCreatorProfile(e,t,i){if(!e)return u("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):a}async publish(e){if(!e.files||e.files.length===0)return u("client","At least one file is required.");let t=new Map,i=e.files.map((h,g)=>{if("sourceAssetUrl"in h)return {Role:h.role,ContentType:h.contentType,SourceAssetUrl:h.sourceAssetUrl};let V=Xd(h.data,h.contentType);return t.set(g,V),{Role:h.role,ContentType:h.contentType,Size:V.size}}),s=e.thumbnail?Xd(e.thumbnail.data,e.thumbnail.contentType):null,r=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!r.ok)return r;let o=r.data.Uploads??[];for(let h=0;h<o.length;h++){let g=o[h];if(!g||g.ServerCopy||!g.Url)continue;let V=t.get(h);if(!V)return u("client",`No bytes for file #${h+1}.`);let oe=await this.putBytes(g.Url,V,g.ContentType??V.type);if(!oe.ok)return oe}let c=r.data.ThumbnailUpload;if(c?.Url&&s){let h=await this.putBytes(c.Url,s,c.ContentType??s.type);if(!h.ok)return h}return this.ctx.credits.pay(h=>this.publishUploaded({CreditsConfirmationID:h,ContentID:r.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID}),e.credits)}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):a}async publishUploaded(e){if(!e.ContentID)return u("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return a;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&!i.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let s=await this.ctx.api.workshop.updateContent(i);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getMyContent(s)):a}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let s=await this.ctx.api.workshop.acquire(i);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let s of t.data.Files??[])if(s.Url)try{let r=await this.ctx.fetchImpl(s.Url);if(!r.ok)return u("connection",`Download failed (HTTP ${r.status}).`);i.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await r.arrayBuffer()});}catch(r){return u("connection",`Download failed: ${r instanceof Error?r.message:String(r)}${Yd}`)}return F({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):a}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):a}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?F(!0):u("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return u("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${Yd}`)}}contentRequest(e){if(!e)return u("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):a}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function Xd(n,e){return n instanceof Blob?n:typeof n=="string"?new Blob([new TextEncoder().encode(n)],{type:e}):n instanceof Uint8Array?new Blob([n.slice().buffer],{type:e}):new Blob([n],{type:e})}var Nb={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},_b=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Vb={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},eh=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),jb={Everyone:"Everyone",Owner:"Owner",Server:"Server"},th=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),Wb={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},Hb=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),Kb={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},Qb=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),$b={Count:"Count",Sum:"Sum"},Jb=zod.z.enum(["Count","Sum"]).catch("Count"),Zb={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},Yb=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),Xb={Strict:"Strict",Loose:"Loose"},eD=zod.z.enum(["Strict","Loose"]).catch("Strict"),tD=zod.z.object({Kind:Qb,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),iD=zod.z.object({Type:eh,ItemType:eh.nullish(),Ref:tD.nullish(),Required:zod.z.boolean().optional(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),MaxItems:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish(),Unique:zod.z.boolean().optional(),UniqueIgnoreCase:zod.z.boolean().optional(),Indexed:zod.z.boolean().optional(),Visibility:th.optional(),ClientWritable:zod.z.boolean().nullish(),Immutable:zod.z.boolean().optional(),Description:zod.z.string().nullish(),AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxFileBytes:zod.z.number().nullish()}),sD=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),gn=zod.z.object({Mode:Hb,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),rD=zod.z.object({Read:zod.z.array(gn).nullish(),Create:zod.z.array(gn).nullish(),Update:zod.z.array(gn).nullish(),Delete:zod.z.array(gn).nullish()}),Za=zod.z.object({Cost:pe.nullish(),Grant:pe.nullish()}),nD=zod.z.object({ID:zod.z.string(),SortKey:zod.z.string(),PartitionField:zod.z.string().nullish(),PageSize:zod.z.number().optional(),MaxItems:zod.z.number().optional(),PublishItems:zod.z.boolean().optional()}),oD=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Namespace:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Enabled:zod.z.boolean().nullish(),Kind:_b,Mode:eD.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),iD).nullish(),SortKeys:zod.z.array(sD).nullish(),Access:rD.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:Yb.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:Jb,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:th.optional()})).nullish(),Economy:zod.z.object({OnCreate:Za.nullish(),OnUpdate:Za.nullish(),OnDelete:Za.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:zod.z.array(nD).nullish(),AnonymousSearch:zod.z.boolean().nullish(),Integrations:zod.z.object({QuestMetricOnCreate:zod.z.string().nullish(),QuestMetricOnUpdate:zod.z.string().nullish(),QuestMetricOnDelete:zod.z.string().nullish(),AnalyticsEventOnCreate:zod.z.string().nullish(),AnalyticsEventOnUpdate:zod.z.string().nullish(),AnalyticsEventOnDelete:zod.z.string().nullish(),TriggerOnCreate:zod.z.string().nullish(),TriggerOnUpdate:zod.z.string().nullish(),TriggerOnDelete:zod.z.string().nullish()}).nullish(),Moderation:zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish()}).nullish()}),ih=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),oD).default({})}),aD=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),sh=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),ki=zod.z.object({Collection:zod.z.string(),ItemID:zod.z.string(),OwnerUserID:zod.z.string().nullish(),Data:zod.z.record(zod.z.string(),zod.z.unknown()).default({}),Version:zod.z.number(),CreatedAt:zod.z.string(),UpdatedAt:zod.z.string(),ExpireAt:zod.z.string().nullish(),Expanded:zod.z.record(zod.z.string(),zod.z.unknown()).nullish(),Files:zod.z.record(zod.z.string(),aD).nullish()}),Ya=zod.z.object({Item:ki}),rh=zod.z.object({Items:zod.z.array(ki).default([]),Missing:zod.z.array(zod.z.string()).default([])}),Xa=zod.z.object({Items:zod.z.array(ki).default([]),NextCursor:zod.z.string().nullish()}),nh=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),el=zod.z.object({Item:ki,AlreadyExists:zod.z.boolean().optional(),Economy:O.nullish()}),oh=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:O.nullish()}),ah=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),lh=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:ki.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),uh=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),ch=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),ph=zod.z.object({Version:zod.z.string(),Collection:zod.z.string(),View:zod.z.string(),SortKey:zod.z.string().nullish(),PageSize:zod.z.number(),UpdatedAt:zod.z.string(),BaseUrl:zod.z.string(),Partitions:zod.z.record(zod.z.string(),zod.z.object({Segment:zod.z.string(),Pages:zod.z.number(),Total:zod.z.number()})).default({})}),dh=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(ki).default([])}),lD={GetDefinitions:"GetDefinitions",Get:"Get",GetMany:"GetMany",Query:"Query",Count:"Count",Create:"Create",Update:"Update",Delete:"Delete",Batch:"Batch",GetCounter:"GetCounter",GetMyRoles:"GetMyRoles",BeginFileUpload:"BeginFileUpload"};var uD=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,fh=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,il=100,hh=25,mh=100;function cD(n,e,t){return {Field:n,Op:e,Value:t}}var yn=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(a)}get(e,t,i={}){let s=ot(e)??is(t);return s?Promise.resolve(s):this.call(r=>this.ctx.api.dataCollections.get({...r,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let s=ot(e);if(s)return Promise.resolve(s);let r=[...new Set(t.filter(o=>fh.test(o)))];return r.length?r.length>mh?Promise.resolve(u("client",`At most ${mh} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:r,Expand:i.expand})):Promise.resolve(u("client","At least one valid item id is required."))}query(e,t={},i={}){let s=ot(e)??tl(t);return s?Promise.resolve(s):this.call(r=>this.ctx.api.dataCollections.query({...r,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),r=[],o=t.Cursor;for(;;){let c=await this.query(e,{...t,Cursor:o,Limit:t.Limit??il},i);if(!c.ok)return c;if(r.push(...c.data.Items),o=c.data.NextCursor??void 0,!o||r.length>=s)return F(r.slice(0,s))}}count(e,t={}){let i=ot(e)??tl(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,i={}){let s=ot(e)??(i.itemID?is(i.itemID):null);return s?Promise.resolve(s):this.call(r=>this.ctx.api.dataCollections.create({...r,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,s={}){let r=ot(e)??is(t);return r?Promise.resolve(r):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=ot(e)??is(t);return s?Promise.resolve(s):this.call(r=>this.ctx.api.dataCollections.delete({...r,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(u("client","Operations are empty."));if(e.length>hh)return Promise.resolve(u("client",`At most ${hh} operations per batch.`));let t=e.map(i=>ot(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let s=ot(e);return s?Promise.resolve(s):this.call(r=>this.ctx.api.dataCollections.getCounter({...r,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,s){let r=ot(e);return r?Promise.resolve(r):t?s>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(u("client","File size must be positive.")):Promise.resolve(u("client","Field is required."))}async uploadFile(e,t,i,s={}){let r=s.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,r,i.size);if(!o.ok)return o;let c=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||r);return c.ok?o:c}async getPublicViews(e){let t=ot(e);if(t)return t;let i=this.publicViews.get(e);if(i)return F(i);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,i={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let r=s.data.Views[t];if(!r)return u("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(r,ph);if(!o.ok)return o;let c=o.data.Partitions[i.partition??""],h=Math.max(1,i.page??1);if(!c||h>c.Pages)return F({pointer:o.data,page:{Page:h,HasMore:false,Items:[]}});let g=await this.fetchJson(`${o.data.BaseUrl}${c.Segment}/page-${h}.json`,dh);return g.ok?F({pointer:o.data,page:g.data}):g}getPublic(e,t){let i=ot(e)??is(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=ot(e)??tl(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(a)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?F(!0):u("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return u("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return u("connection","Internet Connection Error")}if(!i.ok)return u("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return u("server","CDN answer is not JSON.")}let r=t.safeParse(s);return r.success?F(r.data):u("server","CDN answer has an unexpected shape.")}};function ot(n){return uD.test(n??"")?null:u("client",`Collection id '${n}' is invalid (letters, digits, '_', '-', ':').`)}function is(n){return fh.test(n??"")?null:u("client",`Item id '${n}' is invalid.`)}function tl(n){return n.Limit!=null&&(n.Limit<1||n.Limit>il)?u("client",`Limit must be 1..${il}.`):(n.Where?.length??0)>8?u("client","At most 8 filters per query."):null}var sl={Open:"Open",Declared:"Declared"},pD=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),dD=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),gh=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),pD).nullish(),Dimensions:zod.z.array(dD).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),$t={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},vt={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Rn=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,hD={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},mD=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),yh=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(mD).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),rl={LogEvents:"LogEvents"};function Rh(n,e=0){let t=n??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let c=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:c==="iPad"?"tablet":"phone",deviceModel:c}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let c=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:c&&c!=="K"&&c!=="wv"?c:void 0}}let r=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(r)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(r[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let o=/\bWindows NT (\d+\.\d+)/.exec(t);return o?{osName:"Windows",osVersion:o[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function Ch(n){let e=typeof navigator>"u"?void 0:navigator,t=Rh(e?.userAgent??"",e?.maxTouchPoints??0),i={};n.appVersion&&(i.AppVersion=n.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let s=n.locale||e?.language;return s&&(i.Language=s),i}var fD=25,gD=3e4,Sh=1800*1e3,xh=500,yD=5,RD=1e3,CD=3600*1e3,bh="idos_analytics_queue",nl="idos_analytics_pending",ol="idos_analytics_opt_out",Dh="idos_analytics_first_open",Ph="idos_analytics_last_activity",Ih="idos_analytics_last_context",vh="idos_analytics_owner",Cn=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;stopVisibility=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!Rn.test(e)?u("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):SD(e)?u("client",`Event name "${e}" uses a reserved prefix (${vt.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return u("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue($t.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return F(null);if(this.config()?.Enabled===false)return this.clear(),F(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return F(null);this.pending={BatchID:G(),Events:this.queue.splice(0,vt.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=yD)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(ol);return}this.write(ol,"1"),this.clear();}get isEnabled(){return this.read(ol)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(vh);e&&t&&t!==e&&this.clear(),e&&this.write(vh,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},gD),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide),this.beginAutomatic(),this.flush();}async stop(){this.started&&(this.started=false,this.automaticDone=false,this.timer&&clearInterval(this.timer),this.drainTimer&&clearTimeout(this.drainTimer),this.timer=null,this.drainTimer=null,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null,this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),await this.flush());}beginAutomatic(){if(this.automaticDone||!this.started)return;if(this.config()?.Enabled!==true){this.stopWaitingForConfig??=this.ctx.emitter.on("title:publicConfigurationReceived",()=>this.beginAutomatic());return}this.automaticDone=true,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null;let e=Number(this.read(Ph)??"0");this.read(Dh)||(this.write(Dh,new Date().toISOString()),this.enqueue($t.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Ih);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue($t.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue($t.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Ih,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Sh)&&this.enqueue($t.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=e=>{if(!e){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=Sh&&this.enqueue($t.SessionStart,void 0,void 0,true),this.hiddenAt=null;};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,s){if(!this.isEnabled||this.disabledByServer)return F(null);let r=this.config();if(r?.Enabled===false)return F(null);if(s&&r?.AutomaticEvents===false)return F(null);if(r?.Events?.[e]?.Blocked)return u("client",`Event "${e}" is blocked by the title.`);if(!s&&r?.EventNaming?.toLowerCase()===sl.Declared.toLowerCase()&&!r.Events?.[e])return u("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return u("client","value must be a finite number.");let o=xD(t);if(o.error)return u("client",o.error);this.restore();let c={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(c.Params=o.params),i!==void 0&&(c.Value=i),this.queue.push(c),this.queue.length>xh&&this.queue.splice(0,this.queue.length-xh),this.touch(),this.persist(),this.started&&this.queue.length>=fD&&this.flush(),F(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},RD));}dropStale(){let e=Date.now()-(vt.maxEventAgeMs-CD);this.queue=this.queue.filter(t=>{let i=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(i)||i>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=Ch({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(bh);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(nl);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(bh,this.queue),this.pending?this.writeJson(nl,this.pending):this.remove(nl);}touch(){this.write(Ph,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.host.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.host.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.host.storage.remove(this.key(e));}catch{}}readJson(e){let t=this.read(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}writeJson(e,t){this.write(e,JSON.stringify(t));}};function SD(n){let e=n.toLowerCase();return vt.reservedPrefixes.some(t=>e.startsWith(t))}function xD(n){if(!n)return {};let e=Object.keys(n);if(e.length===0)return {};if(e.length>vt.maxParams)return {error:`Too many parameters: ${e.length}, max ${vt.maxParams}.`};let t={};for(let i of e){if(!Rn.test(i))return {error:`Invalid parameter name "${i}".`};let s=n[i];typeof s=="string"?t[i]=s.length>vt.maxStringValueLength?s.slice(0,vt.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var bD="idos_experiments",Sn=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let r=Number(s);return s.trim()!==""&&Number.isFinite(r)?r:i}if(typeof i=="boolean"){let r=s.trim().toLowerCase();return r==="true"||r==="1"?true:r==="false"||r==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,r]of t){let o=this.views.get(s);(!o||o.VariantID!==r.VariantID||o.Status!==r.Status)&&i.push(r);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.host.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.host.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${bD}:${this.ctx.settings.titleID}`}};function Jt(n,e,t,i){let r=`api/v2/${n&&n.length>0?n:"0"}/Client/${e}/${t}`;return i==null?r:`${r}/${i}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Jt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,s){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...s,ticket:t.ClientSessionTicket})}};var xn=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(rl.LogEvents,e,yh,{silent:true})}};var DD=zod.z.object({VariantID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Weight:zod.z.number().nullish(),IsControl:zod.z.boolean().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),PD={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},ID=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),vD=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:Re.nullish(),Gate:Z.nullish(),Variants:zod.z.array(DD).nullish(),Salt:zod.z.string().nullish(),LayerID:zod.z.string().nullish(),StickyAssignment:zod.z.boolean().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Goals:zod.z.array(ID).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),Th=zod.z.object({Experiments:zod.z.record(zod.z.string(),vD).nullish()}).passthrough(),TD={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},AD=zod.z.object({ExperimentID:zod.z.string().nullish(),VariantID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ah=zod.z.object({Experiments:zod.z.array(AD).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),al={GetExperiments:"GetExperiments"};var bn=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(al.GetExperiments,e,Ah)}};var wD={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},wh=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),kD=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),kh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),kD).nullish(),MissingKeyMode:wh.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),zD=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),zh=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:zD.nullish()}).passthrough(),Dn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},MD=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),Mh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:wh.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(MD).nullish()}).passthrough(),Oh=zod.z.object({RequestedLocale:zod.z.string().nullish(),Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),NotModified:zod.z.boolean().nullish(),Entries:zod.z.record(zod.z.string(),zod.z.string()).nullish(),FallbackLocale:zod.z.string().nullish(),FallbackVersion:zod.z.number().nullish()}).passthrough();var ss=zod.z.object({TitleConfigVersion:zod.z.string().nullish(),TitleConfigUrl:zod.z.string().nullish(),User:zod.z.unknown().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish(),Localization:zh.nullish(),Views:zod.z.array(zod.z.object({Name:zod.z.string(),Key:zod.z.string().nullish(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(n=>n),Eh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(n=>n),Uh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),User:zod.z.unknown().nullish()}).passthrough().transform(n=>n),qh=zod.z.object({}).passthrough().transform(n=>n),Lh=zod.z.object({}).passthrough().transform(n=>n),Bh=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:p.nullish(),LastActiveAt:p.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),Gh=zod.z.object({Username:zod.z.string()}),mt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Fh=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:p.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:p,PlayAccess:Qt.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:p.nullish(),ClientState:ss.nullish()}),Nh=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:p,RefreshToken:zod.z.string(),RefreshTokenExpiration:p.nullish(),PlayAccess:Qt.nullish()}),OD=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),_h=zod.z.object({Google:zod.z.object({Enabled:zod.z.boolean().nullish(),WebClientID:zod.z.string().nullish(),PlatformFallback:zod.z.boolean().nullish(),AndroidClientID:zod.z.string().nullish(),IosClientID:zod.z.string().nullish(),DesktopClientID:zod.z.string().nullish()}).passthrough().nullish(),Apple:zod.z.object({Enabled:zod.z.boolean().nullish(),BundleID:zod.z.string().nullish(),ServiceID:zod.z.string().nullish()}).passthrough().nullish(),PlayAccessMode:Xi.nullish(),WalletLoginNetworks:zod.z.array(zod.z.object({NetworkID:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:zod.z.boolean().nullish(),NativeSso:OD.nullish()}).passthrough(),Vh=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:p.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:Qt.nullish()}).passthrough(),jh=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:p.nullish(),PlayAccess:Qt.nullish()}).passthrough(),Wh=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Fe=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:p.nullish()}),Hh=zod.z.object({Message:zod.z.string(),ExpiresAt:p}),Ge={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",ResolvePlatformGameSession:"ResolvePlatformGameSession",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var Pn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Jt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,Fh,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ge.RefreshSession),e,Nh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ge.GetAuthOptions),e,_h,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Jt(this.ctx.settings.titleID,"Authentication",Ge.LinkWallet,e.UserID??""),e,Vh,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Jt(this.ctx.settings.titleID,"Authentication",Ge.UnlinkWallet,e.UserID??""),e,jh,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ge.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ge.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ge.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ge.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ge.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ge.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(Ge.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ge.RegisterWithEmail),e,Wh,{ticket:null})}confirmEmailRegistration(e){return this.login(Ge.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ge.ResendVerificationCode),e,Fe,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ge.RequestWalletChallenge),e,Hh,{ticket:null})}loginWithWallet(e){return this.login(Ge.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ge.ForgotPassword),e,Fe,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ge.ResetPassword),e,Fe,{ticket:null})}};var In=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(mt.GetClientState,e,ss)}getClientStateExcept(e){return this.send(mt.GetClientStateExcept,e,ss)}getStateVersions(e){return this.send(mt.GetStateVersions,e,Eh)}getUserState(e){return this.send(mt.GetUserState,e,Uh)}getInventory(e){return this.send(mt.GetInventory,e,qh)}getEventTokens(e){return this.send(mt.GetEventTokens,e,Lh)}getUsageTime(e){return this.send(mt.GetUsageTime,e,Bh)}addUsageTime(e){return this.send(mt.AddUsageTime,e,Fe,{silent:true})}deleteUserAccount(e){return this.send(mt.DeleteUserAccount,e,Fe)}changeUsername(e){return this.send(mt.ChangeUsername,e,Gh)}};var vn=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(Yi.Convert,e,cd)}spend(e){return this.send(Yi.Spend,e,dd)}cryptoConvert(e){return this.send(Yi.CryptoConvert,e,pd)}};var ED=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),ll=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:O.nullish(),FodderConsumed:zod.z.array(ED).nullish()}),Kh=zod.z.array(we(ll)),Tn={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},UD={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},qD=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),LD={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},BD=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),GD=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),FD=zod.z.object({Networks:zod.z.record(zod.z.string(),GD).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),ND=zod.z.object({FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),_D=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),UseRequirements:zod.z.record(zod.z.string(),zod.z.number()).nullish(),AllowedCharacterIDs:zod.z.array(zod.z.string()).nullish(),AllowedSlotIDs:zod.z.array(zod.z.string()).nullish(),IdleRateBonus:zod.z.number().nullish()}).passthrough(),VD=zod.z.object({ValuationMode:qD.nullish(),WeightCurve:je.nullish(),Selection:BD.nullish()}).passthrough(),jD=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:ae.nullish(),CostCurve:je.nullish(),FlatBonusCurve:je.nullish(),PercentBonusCurve:je.nullish(),PowerCurve:je.nullish(),Fodder:VD.nullish()}).passthrough(),WD=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),HD=zod.z.object({ItemID:zod.z.string(),CatalogID:zod.z.string(),ItemClass:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsStackable:zod.z.boolean().nullish(),IsTradable:zod.z.boolean().nullish(),Weight:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),NFT:FD.nullish(),Stats:ND.nullish(),Equipment:_D.nullish(),Upgrade:jD.nullish(),Metadata:WD.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),KD=zod.z.object({Items:zod.z.record(zod.z.string(),HD).nullish()}).passthrough(),An=zod.z.object({Catalogs:zod.z.record(zod.z.string(),KD).nullish()}).passthrough();function Ie(n){return zod.z.unknown().transform((e,t)=>{let i=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(i!=null){let r=fe.safeParse(i);return r.success?{...e,CreditsConfirmation:r.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${r.error.message}`}),zod.z.NEVER)}let s=n.safeParse(e);return s.success?s.data:(t.addIssue({code:"custom",message:s.error.message}),zod.z.NEVER)})}var wn=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(Tn.UpgradeLevel,e,Ie(ll))}upgradeLevelsBatch(e){return this.send(Tn.UpgradeLevelsBatch,e,Kh)}};var kn=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(Et.Purchase,e,ia)}purchaseBatch(e){return this.send(Et.PurchaseBatch,e,Ku)}getDefinitions(e){return this.send(Et.GetDefinitions,e,Qs)}getUserState(e){return this.send(Et.GetUserState,e,Qu)}getStorefront(e){return this.send(Et.GetStorefront,e,$s)}getCreditsConfirmation(e){return this.send(Et.GetCreditsConfirmation,e,fe)}getCreditsBalance(e){return this.send(Et.GetCreditsBalance,e,Hu)}};var QD={Apple:"Apple",Google:"Google"},zn=zod.z.object({PremiumID:zod.z.string().nullish(),PurchaseDate:zod.z.string().nullish(),ExpirationDate:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),IsAutoRenewEnabled:zod.z.boolean().nullish()}).passthrough(),Mn=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),zn).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(n=>n),$D=zod.z.object({PremiumID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Tier:zod.z.number().nullish(),DurationDays:zod.z.number().nullish(),TrialDurationDays:zod.z.number().nullish(),PriceOptions:ae.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),cl=zod.z.object({Definitions:zod.z.record(zod.z.string(),$D).nullish()}).passthrough(),Qh=zod.z.object({Premium:cl.nullish()}),$h=zod.z.object({ServerTimeUtc:p.nullish(),Premium:Mn.nullish()}),On=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),Premium:Mn.nullish(),Subscription:zn.nullish(),Resources:O.nullish()}),li={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var JD={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},ZD=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Jh=zod.z.object({StartUtc:p.nullish(),EndUtc:p.nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),pl=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),YD=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:Q.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),XD=zod.z.object({Rewards:K.nullish(),Rules:K.nullish(),Refund:K.nullish()}).passthrough(),eP=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:ZD.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:Q.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:Jh.nullish(),Refund:pl.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:YD.nullish(),Presets:XD.nullish()}).passthrough(),tP=zod.z.object({StoreID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),PackageName:zod.z.string().nullish(),VerificationMode:zod.z.string().nullish(),PlayPublicKey:zod.z.string().nullish(),RequireCertificateChain:zod.z.boolean().nullish(),SecretName:zod.z.string().nullish(),IssuerID:zod.z.string().nullish(),KeyID:zod.z.string().nullish(),AcknowledgePurchases:zod.z.boolean().nullish(),NotificationPackageName:zod.z.string().nullish()}).passthrough(),iP=zod.z.object({Rewards:Q.nullish()}).passthrough(),sP=zod.z.object({Rules:Jh.nullish()}).passthrough(),rP=zod.z.object({Refund:pl.nullish()}).passthrough(),nP=zod.z.object({Rewards:zod.z.record(zod.z.string(),iP).nullish(),Rules:zod.z.record(zod.z.string(),sP).nullish(),Refund:zod.z.record(zod.z.string(),rP).nullish()}).passthrough(),oP=zod.z.object({MaxPurchaseAgeDays:zod.z.number().nullish(),AllowSandbox:zod.z.boolean().nullish(),RequirePackageMatch:zod.z.boolean().nullish(),MaxReceiptsPerBatch:zod.z.number().nullish(),RefundCheckHorizonDays:zod.z.number().nullish(),RejectCrossUserReceipts:zod.z.boolean().nullish()}).passthrough(),aP=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),eP).nullish(),Stores:zod.z.record(zod.z.string(),tP).nullish(),Presets:nP.nullish(),Validation:oP.nullish(),Refund:pl.nullish()}).passthrough(),Zh=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:p.nullish(),LastPurchasedAt:p.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Yh=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:p.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:p.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:p.nullish()}).passthrough(),lP=zod.z.object({Products:zod.z.record(zod.z.string(),Zh).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Yh).nullish(),LastRefundCheckAt:p.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:p.nullish(),LastPurchaseAt:p.nullish()}).passthrough(),uP=zod.z.object({ProductID:zod.z.string(),Available:zod.z.boolean(),Owned:zod.z.boolean(),Blocked:zod.z.boolean(),Reason:zod.z.string().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Xh=zod.z.object({ServerTimeUtc:p,Purchase:aP.nullish(),Availability:zod.z.array(uP).nullish()}),em=zod.z.object({ServerTimeUtc:p,Purchase:lP.nullish()}),cP={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},pP=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),dl=zod.z.object({ServerTimeUtc:p,Store:hs.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:pP.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:O.nullish(),Inventory:H.nullish(),ProductState:Zh.nullish(),Premium:Mn.nullish(),Subscription:zn.nullish(),SubscriptionMirror:Yh.nullish()}).passthrough(),tm=zod.z.object({ServerTimeUtc:p,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:p.nullish()}).passthrough(),im=bt(dl),ui={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var En=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(ui.GetDefinitions,e,Xh)}getUserState(e){return this.send(ui.GetUserState,e,em)}validatePurchase(e){return this.send(ui.ValidatePurchase,e,dl)}validatePurchasesBatch(e){return this.send(ui.ValidatePurchasesBatch,e,im)}createTelegramInvoice(e){return this.send(ui.CreateTelegramInvoice,e,tm)}};var dP=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),sm=zod.z.object({Reward:Q.nullish(),Weight:zod.z.number().nullish(),AmountRange:dP.nullish()}).passthrough(),zi=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(sm).nullish()}).passthrough(),Mi=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(sm).nullish()}).passthrough(),hP=zod.z.object({RewardSlots:zod.z.array(zi).nullish()}).passthrough(),mP=zod.z.object({PityRules:zod.z.array(Mi).nullish()}).passthrough(),Un=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),hP).nullish(),PityPresets:zod.z.record(zod.z.string(),mP).nullish()}).passthrough();var fP=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),rm=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:H.nullish(),Results:zod.z.array(O).nullish(),TriggeredPity:zod.z.array(fP).nullish()}),gP=zod.z.object({RewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),yP=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:W.nullish()}).passthrough(),RP=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ae.nullish(),RewardSlots:zod.z.array(zi).nullish(),PityRules:zod.z.array(Mi).nullish(),Presets:gP.nullish(),RewardMultiplier:Ss.nullish(),SupplyLimits:zod.z.array(yP).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),CP=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),hl=zod.z.object({Definitions:zod.z.record(zod.z.string(),RP).nullish(),RewardPools:Un.nullish(),Settings:CP.nullish()}).passthrough(),nm=zod.z.object({LootboxDefinitions:hl.nullish()}),qn={GetDefinitions:"GetDefinitions",Open:"Open"};var Ln=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(qn.GetDefinitions,e,nm)}open(e){return this.send(qn.Open,e,Ie(rm))}};var SP=zod.z.object({}).passthrough().transform(n=>n),xP=zod.z.object({}).passthrough().transform(n=>n),bP=zod.z.object({}).passthrough().transform(n=>n),DP=zod.z.object({}).passthrough().transform(n=>n),PP=zod.z.object({}).passthrough().transform(n=>n),IP=zod.z.object({}).passthrough().transform(n=>n),om=zod.z.object({ServerTimeUtc:p,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:SP,Resources:O.nullish(),Inventory:H.nullish()}),am=zod.z.object({ServerTimeUtc:p,AccrualID:zod.z.string(),AccruedSeconds:W.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:xP,Resources:O.nullish(),Inventory:H.nullish()}),lm=zod.z.object({ServerTimeUtc:p,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:bP,Resources:O.nullish(),Inventory:H.nullish()}),um=zod.z.object({ServerTimeUtc:p,ClaimID:zod.z.string(),ClaimState:DP,Resources:O.nullish(),Inventory:H.nullish()}),vP={None:"None",Ad:"Ad",Vip:"Vip"},cm=zod.z.object({ServerTimeUtc:p,WindowID:zod.z.string(),Boost:zod.z.string().nullish(),BaseAmount:W.nullish(),Multiplier:zod.z.number().nullish(),Granted:W.nullish(),WindowState:PP,Resources:O.nullish(),Inventory:H.nullish()}),pm=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:W.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),TP=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),AP=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:Q.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rs=zod.z.object({Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),ml=zod.z.object({Availability:K.nullish()}).passthrough(),wP=zod.z.object({Availability:zod.z.record(zod.z.string(),rs).nullish()}).passthrough(),kP=zod.z.object({CalendarID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Days:zod.z.array(AP).nullish(),IsLooping:zod.z.boolean().nullish(),MissBehavior:zod.z.string().nullish(),ResetByDays:zod.z.number().nullish(),MissThresholdMultiplier:zod.z.number().nullish(),ClaimMode:zod.z.string().nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),Availability:rs.nullish(),Presets:ml.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),zP=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),MP=zod.z.object({BaseRatePerSecond:zod.z.number().nullish(),PowerCoefficient:zod.z.number().nullish(),BoardRankCoefficient:zod.z.number().nullish(),EquipmentBonusEnabled:zod.z.boolean().nullish(),EquipmentCharacterID:zod.z.string().nullish(),PremiumMultipliers:zod.z.array(zP).nullish()}).passthrough(),OP=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:rs.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),EP=zod.z.object({AccrualID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rate:MP.nullish(),Rewards:Q.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:OP.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),UP=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:Q.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),qP=zod.z.object({ComebackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(UP).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:rs.nullish(),Presets:ml.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),LP=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxClaimsPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish(),TotalClaimLimit:zod.z.number().nullish()}).passthrough(),BP=zod.z.object({ClaimID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Mode:zod.z.string().nullish(),Rewards:Q.nullish(),PremiumLimitOverrides:zod.z.array(LP).nullish(),Availability:rs.nullish(),Presets:ml.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),GP=zod.z.object({CurrencyID:zod.z.string().nullish(),MaxBaseAmount:zod.z.number().nullish(),AdPlacementID:zod.z.string().nullish(),AdMultiplier:zod.z.number().nullish(),VipMultiplier:zod.z.number().nullish(),VipPremiumID:zod.z.string().nullish(),Limits:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),fl=zod.z.object({TierRewards:TP.nullish(),MilestoneRewardMultiplier:Ss.nullish(),DailyCalendars:zod.z.record(zod.z.string(),kP).nullish(),IdleAccruals:zod.z.record(zod.z.string(),EP).nullish(),Comebacks:zod.z.record(zod.z.string(),qP).nullish(),Claims:zod.z.record(zod.z.string(),BP).nullish(),Windows:zod.z.record(zod.z.string(),GP).nullish(),Presets:wP.nullish()}).passthrough(),dm=zod.z.object({RewardDefinitions:fl.nullish()}),hm=zod.z.object({Rewards:IP.nullish()}),Tt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var Bn=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Tt.GetRewardDefinitions,e,dm)}getUserRewardsState(e){return this.send(Tt.GetUserRewardsState,e,hm)}getMilestoneRewardMultiplier(e){return this.send(Tt.GetMilestoneRewardMultiplier,e,pm)}claimDailyReward(e){return this.send(Tt.ClaimDailyReward,e,om)}collectIdleAccrual(e){return this.send(Tt.CollectIdleAccrual,e,am)}claimComebackReward(e){return this.send(Tt.ClaimComebackReward,e,lm)}claimReward(e){return this.send(Tt.ClaimReward,e,um)}claimRewardWindow(e){return this.send(Tt.ClaimRewardWindow,e,cm)}};var Gn=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(ct.GetTutorialDefinitions,e,Au)}getUserTutorialState(e){return this.send(ct.GetUserTutorialState,e,Ds)}startFlow(e){return this.send(ct.StartFlow,e,Nt)}reportStepShown(e){return this.send(ct.ReportStepShown,e,Nt)}completeStep(e){return this.send(ct.CompleteStep,e,Nt)}completeStepsBatch(e){return this.send(ct.CompleteStepsBatch,e,zu)}skipStep(e){return this.send(ct.SkipStep,e,Nt)}skipFlow(e){return this.send(ct.SkipFlow,e,Nt)}claimFlowReward(e){return this.send(ct.ClaimFlowReward,e,ku)}resetFlow(e){return this.send(ct.ResetFlow,e,Nt)}};var FP={Open:"Open",Application:"Application"},NP=zod.z.enum(["Open","Application"]).catch("Open"),_P={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},mm=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),VP={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},gl=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),jP={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var ci={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},WP=zod.z.object({CampaignID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IsRunning:zod.z.boolean().nullish()}).passthrough(),fm=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:NP.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:mm.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(WP).nullish()}).passthrough(),HP=zod.z.object({Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),CountedMetrics:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ReachedMilestones:zod.z.array(zod.z.string()).nullish(),CappedBySubmissionLimit:zod.z.boolean().nullish(),CappedByCreatorLimit:zod.z.boolean().nullish(),NotPaidAsCopy:zod.z.boolean().nullish()}).passthrough(),KP=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:gl.nullish(),CurrencyID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),Granted:zod.z.number().nullish(),Paid:zod.z.number().nullish(),Overpaid:zod.z.number().nullish(),Claimable:zod.z.number().nullish(),BySubmission:zod.z.record(zod.z.string(),HP).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),QP=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:gl.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),gm=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(KP).nullish(),Payouts:zod.z.array(QP).nullish()}).passthrough(),ym=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:gl.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),$P=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),JP=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),Signature:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array($P).nullish()}).passthrough(),ZP=zod.z.object({Kind:zod.z.string().nullish(),Target:zod.z.string().nullish(),Required:zod.z.number().nullish(),Actual:zod.z.number().nullish(),Passed:zod.z.boolean().nullish()}).passthrough(),Rm=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:mm.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(ZP).nullish()}).passthrough(),YP=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),XP=zod.z.object({ProgramID:zod.z.string().nullish(),Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(YP).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Cm=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:zod.z.number().nullish(),NetAmountNative:zod.z.number().nullish(),BurnAmountNative:zod.z.number().nullish(),AmountUsd:zod.z.number().nullish(),ExpiresAt:zod.z.string().nullish(),EvmSignature:JP.nullish(),SolanaSignature:XP.nullish(),StateDelta:wi.nullish()}).passthrough();var Fn=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(ci.GetCommunityMarketingState,e,fm)}getEarnings(e){return this.send(ci.GetEarnings,e,gm)}claim(e){return this.send(ci.Claim,e,ym)}checkJoinEligibility(e){return this.send(ci.CheckJoinEligibility,e,Rm)}withdrawCryptoReward(e){return this.send(ci.WithdrawCryptoReward,e,Cm)}};var Nn=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(Je.GetChatDefinitions,e,cc)}getChannels(e){return this.send(Je.GetChannels,e,ar)}poll(e){return this.send(Je.Poll,e,pc)}getHistory(e){return this.send(Je.GetHistory,e,dc)}getConversations(e){return this.send(Je.GetConversations,e,fc)}sendMessage(e){return this.send(Je.SendMessage,e,hc)}openDirectChannel(e){return this.send(Je.OpenDirectChannel,e,mc)}markRead(e){return this.send(Je.MarkRead,e,Ti)}joinChannel(e){return this.send(Je.JoinChannel,e,Ti)}leaveChannel(e){return this.send(Je.LeaveChannel,e,Ti)}reportMessage(e){return this.send(Je.ReportMessage,e,gc)}ignoreUser(e){return this.send(Je.IgnoreUser,e,Ti)}unignoreUser(e){return this.send(Je.UnignoreUser,e,Ti)}};var _n=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(Ai.GetPushConfig,e,Cc)}subscribePush(e){return this.send(Ai.SubscribePush,e,na)}unsubscribePush(e){return this.send(Ai.UnsubscribePush,e,Fe)}getPushSubscriptions(e){return this.send(Ai.GetPushSubscriptions,e,Sc)}};var Vn=class extends B{constructor(e){super(e,"Localization");}send(e,t,i,s){let r=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${r}:${t.Locale}`:r,...s})}getLocalizationManifest(e){return this.send(Dn.GetLocalizationManifest,e,Mh)}getLocalizationTable(e){return this.send(Dn.GetLocalizationTable,e,Oh)}};var jn=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(Rt.GetQuestDefinitions,e,bs)}getUserQuestState(e){return this.send(Rt.GetUserQuestState,e,gu)}refreshQuestCycles(e){return this.send(Rt.RefreshQuestCycles,e,Fe)}claimQuestReward(e){return this.send(Rt.ClaimQuestReward,e,jo)}claimQuestRewardsBatch(e){return this.send(Rt.ClaimQuestRewardsBatch,e,Cu)}claimMilestoneReward(e){return this.send(Rt.ClaimMilestoneReward,e,Wo)}claimMilestoneRewardsBatch(e){return this.send(Rt.ClaimMilestoneRewardsBatch,e,Su)}claimGroupCompletionReward(e){return this.send(Rt.ClaimGroupCompletionReward,e,yu)}addQuestProgress(e){return this.send(Rt.AddQuestProgress,e,Ru)}};var Wn=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(dt.GetActiveEvents,e,mr)}getDefinitions(e){return this.send(dt.GetDefinitions,e,hr)}getUserLteState(e){return this.send(dt.GetUserLteState,e,Pc)}grantTokens(e){return this.send(dt.GrantTokens,e,O)}spendTokens(e){return this.send(dt.SpendTokens,e,la)}claimMilestone(e){return this.send(dt.ClaimMilestone,e,ua)}claimMilestonesBatch(e){return this.send(dt.ClaimMilestonesBatch,e,ca)}claimAllMilestones(e){return this.send(dt.ClaimAllMilestones,e,ca)}spendTokensBatch(e){return this.send(dt.SpendTokensBatch,e,Ic)}grantTokensBatch(e){return this.send(dt.GrantTokensBatch,e,vc)}};var Hn=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(We.GetDefinitions,e,xr)}getLeaderboard(e){return this.send(We.GetLeaderboard,e,Ki)}getMyProgress(e){return this.send(We.GetMyProgress,e,gr)}submitScore(e){return this.send(We.SubmitScore,e,yr)}submitScoreFromSource(e){return this.send(We.SubmitScoreFromSource,e,yr)}claimCycleReward(e){return this.send(We.ClaimCycleReward,e,Rr)}claimMilestone(e){return this.send(We.ClaimMilestone,e,Cr)}getFriendsLeaderboard(e){return this.send(We.GetFriendsLeaderboard,e,Ki)}getLeaderboardsBatch(e){return this.send(We.GetLeaderboardsBatch,e,wc)}getProgressBatch(e){return this.send(We.GetProgressBatch,e,Sr)}claimCycleRewardsBatch(e){return this.send(We.ClaimCycleRewardsBatch,e,kc)}claimMilestonesBatch(e){return this.send(We.ClaimMilestonesBatch,e,zc)}submitScoresBatch(e){return this.send(We.SubmitScoresBatch,e,Mc)}claimAllRewardsBatch(e){return this.send(We.ClaimAllRewardsBatch,e,Oc)}getOverviewBatch(e){return this.send(We.GetOverviewBatch,e,Ec)}};var Kn=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(jt.GetDefinitions,e,Pr)}getActiveSeason(e){return this.send(jt.GetActiveSeason,e,Dr)}getUserState(e){return this.send(jt.GetUserState,e,pa)}grantStatusTokens(e){return this.send(jt.GrantStatusTokens,e,Bc)}claimTierReward(e){return this.send(jt.ClaimTierReward,e,da)}claimTierRewardsBatch(e){return this.send(jt.ClaimTierRewardsBatch,e,Gc)}};var Qn=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(li.GetDefinitions,e,Qh)}getUserState(e){return this.send(li.GetUserState,e,$h)}activateTrial(e){return this.send(li.ActivateTrial,e,On)}purchaseItemOrCurrency(e){return this.send(li.PurchaseWithResources,e,Ie(On))}purchaseRealMoney(e){return this.send(li.PurchaseRealMoney,e,On)}};var $n=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(He.GetCharacterDefinitions,e,Ar)}getUserCharacters(e){return this.send(He.GetUserCharacters,e,Wc)}unlockCharacter(e){return this.send(He.UnlockCharacter,e,Ie(ga))}upgradeStatLevel(e){return this.send(He.UpgradeStatLevel,e,Ie(ma))}upgradeCharacterLevel(e){return this.send(He.UpgradeCharacterLevel,e,Ie(fa))}equipItems(e){return this.send(He.EquipItems,e,Hc)}unequipItems(e){return this.send(He.UnequipItems,e,Kc)}unequipAllCharacters(e){return this.send(He.UnequipAllCharacters,e,Qc)}unlockCharactersBatch(e){return this.send(He.UnlockCharactersBatch,e,Xc)}upgradeCharacterLevelsBatch(e){return this.send(He.UpgradeCharacterLevelsBatch,e,ep)}upgradeStatLevelsBatch(e){return this.send(He.UpgradeStatLevelsBatch,e,tp)}unlockSkin(e){return this.send(He.UnlockSkin,e,Ie($c))}equipSkin(e){return this.send(He.EquipSkin,e,Jc)}unequipSkin(e){return this.send(He.UnequipSkin,e,Zc)}getCharacterSkins(e){return this.send(He.GetCharacterSkins,e,Yc)}};var Jn=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(It.CreateMatch,e,Ld)}updateMatch(e){return this.send(It.UpdateMatch,e,Bd)}cancelMatch(e){return this.send(It.CancelMatch,e,Gd)}instantBattle(e){return this.send(It.InstantBattle,e,Fd)}saveStrategy(e){return this.send(It.SaveStrategy,e,Fe)}getMyMatches(e){return this.send(It.GetMyMatches,e,Va)}getAvailableMatches(e){return this.send(It.GetAvailableMatches,e,Va)}getDefinitions(e){return this.send(It.GetDefinitions,e,jd)}};var eI={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Sm=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),tI={None:"None",Min:"Min",Average:"Average",Max:"Max"},iI=zod.z.enum(["None","Min","Average","Max"]).catch("None"),sI={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},rI=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),nI={Clamp:"Clamp",Reject:"Reject"},oI=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),aI=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),lI=zod.z.object({Index:zod.z.number().nullish(),BurnedItemIDs:zod.z.array(zod.z.string()).nullish(),RolledCollectionID:zod.z.string().nullish(),UsedCollections:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Output:No.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(aI).nullish()}),xm=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,Type:Sm.nullish(),CraftID:zod.z.string(),CraftedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),InputRarity:zod.z.string().nullish(),OutputRarity:zod.z.string().nullish(),Resources:O.nullish(),Inventory:H.nullish(),Results:zod.z.array(lI).nullish()}),uI=zod.z.object({CraftID:zod.z.string().nullish(),Type:Sm.nullish(),CatalogID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),InputRarityID:zod.z.string().nullish(),OutputRarityID:zod.z.string().nullish(),RequiredItemCount:zod.z.number().nullish(),PriceOptions:ae.nullish(),OutputLevelMode:iI.nullish(),InputSelection:rI.nullish(),OutputLevelOverflow:oI.nullish()}).passthrough(),yl=zod.z.object({Definitions:zod.z.record(zod.z.string(),uI).nullish()}).passthrough(),bm=zod.z.object({ServerTimeUtc:p.nullish(),CraftDefinitions:yl.nullish()}),Zn={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Yn=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Zn.GetDefinitions,e,bm)}craft(e){return this.send(Zn.Craft,e,Ie(xm))}};var cI=2e5,Xn=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,Ie(Mr),{timeoutMs:cI,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Mr,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Be.GetDefinitions,e,dp)}generateText(e){return this.generate(Be.GenerateText,e)}getText(e){return this.readGeneration(Be.GetText,e)}generateImage(e){return this.generate(Be.GenerateImage,e)}editImage(e){return this.generate(Be.EditImage,e)}getImage(e){return this.readGeneration(Be.GetImage,e)}generateVideo(e){return this.generate(Be.GenerateVideo,e)}getVideo(e){return this.readGeneration(Be.GetVideo,e)}generateAudio(e){return this.generate(Be.GenerateAudio,e)}getAudio(e){return this.readGeneration(Be.GetAudio,e)}generateMusic(e){return this.generate(Be.GenerateMusic,e)}getMusic(e){return this.readGeneration(Be.GetMusic,e)}generateFromTemplate(e){return this.generate(Be.GenerateFromTemplate,e)}estimateTemplatePrice(e){return this.send(Be.EstimateTemplatePrice,e,pp,{throttleKey:`AI:EstimateTemplatePrice:${e.FeatureKey??""}:${JSON.stringify(e.Params??{})}`})}generateThreeD(e){return this.generate(Be.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Be.GetThreeD,e)}listGenerations(e){return this.send(Be.ListGenerations,e,up)}getGeneration(e){return this.readGeneration(Be.GetGeneration,e)}};var pI={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},dI=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),Dm=zod.z.object({}).passthrough().transform(n=>n),Oi=zod.z.object({CollectibleID:zod.z.string(),Rarity:zod.z.number().nullish(),IsSpecial:zod.z.boolean().nullish(),IsDuplicate:zod.z.boolean().nullish(),CollectionCurrencyConverted:zod.z.number().nullish()}),Pm=zod.z.object({GrantedCollectibles:zod.z.array(Oi).nullish(),DuplicateCollectibles:zod.z.array(Oi).nullish(),CollectionCurrencyEarned:W.nullish()}),Im=zod.z.object({CreditsConfirmation:fe.nullish(),OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(Pm).nullish(),GrantedCollectibles:zod.z.array(Oi).nullish(),DuplicateCollectibles:zod.z.array(Oi).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:H.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),vm=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(Pm).nullish(),GrantedCollectibles:zod.z.array(Oi).nullish(),DuplicateCollectibles:zod.z.array(Oi).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),Resources:O.nullish(),Inventory:H.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Tm=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:H.nullish()}),Rl=zod.z.object({SetID:zod.z.string(),Resources:O.nullish(),Inventory:H.nullish()}),Am=zod.z.array(we(Rl)),wm=zod.z.object({Resources:O.nullish(),Inventory:H.nullish()}),hI=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:Le.nullish(),OfferedCollectibleID:zod.z.string().nullish(),OfferedCollectibleIsSpecial:zod.z.boolean().nullish(),ReceiverUserID:zod.z.string().nullish(),RequestedCollectibleID:zod.z.string().nullish(),RequestedCollectibleIsSpecial:zod.z.boolean().nullish(),Status:dI.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RespondedAtUtc:p.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),km=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:p.nullish(),Resources:O.nullish()}),zm=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),Mm=zod.z.object({OfferID:zod.z.string(),ReceivedCollectibleID:zod.z.string().nullish(),ReceivedIsSpecial:zod.z.boolean().nullish(),SentCollectibleID:zod.z.string().nullish(),SentCollectibleIsSpecial:zod.z.boolean().nullish(),Transfer:zod.z.unknown().nullish()}),Om=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),Cl=zod.z.object({Offers:zod.z.array(hI).nullish()}),mI=zod.z.object({CollectibleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rarity:zod.z.number().nullish(),HasSpecialVersion:zod.z.boolean().nullish(),SortOrder:zod.z.number().nullish()}).passthrough(),fI=zod.z.object({SetID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SortOrder:zod.z.number().nullish(),Collectibles:zod.z.array(mI).nullish(),SetCompletionReward:Q.nullish()}).passthrough(),gI=zod.z.object({CollectionID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SeasonChainID:zod.z.string().nullish(),Sets:zod.z.array(fI).nullish(),GrandPrize:Q.nullish()}).passthrough(),Em=zod.z.object({BonusRewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),yI=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:ae.nullish(),BonusRewardSlots:zod.z.array(zi).nullish(),PityRules:zod.z.array(Mi).nullish(),Presets:Em.nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectibleCount:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),GuaranteeMaxRarity:zod.z.boolean().nullish(),RarityWeights:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ColorTier:zod.z.number().nullish()}).passthrough(),RI=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),CI=zod.z.object({CollectionChestID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectionCurrencyCost:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),MinCollectibleCount:zod.z.number().nullish(),MaxCollectibleCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),BonusRewardSlots:zod.z.array(zi).nullish(),PityRules:zod.z.array(Mi).nullish(),Presets:Em.nullish(),Tier:zod.z.number().nullish()}).passthrough(),SI=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),xI=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),eo=zod.z.object({Collections:zod.z.record(zod.z.string(),gI).nullish(),PackTypes:zod.z.record(zod.z.string(),yI).nullish(),CollectionChests:zod.z.array(CI).nullish(),DuplicateConversions:zod.z.array(RI).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(SI).nullish(),RewardPools:Un.nullish(),Settings:xI.nullish()}).passthrough(),Ke={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var to=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ke.GetDefinitions,e,eo)}getUserState(e){return this.send(Ke.GetUserState,e,Dm)}openPack(e){return this.send(Ke.OpenPack,e,Ie(Im))}openCollectionChest(e){return this.send(Ke.OpenCollectionChest,e,vm)}useCollectibleJoker(e){return this.send(Ke.UseCollectibleJoker,e,Tm)}claimSetReward(e){return this.send(Ke.ClaimSetReward,e,Rl)}claimSetRewardsBatch(e){return this.send(Ke.ClaimSetRewardsBatch,e,Am)}claimGrandPrize(e){return this.send(Ke.ClaimGrandPrize,e,wm)}sendTradeOffer(e){return this.send(Ke.SendTradeOffer,e,km)}cancelTradeOffer(e){return this.send(Ke.CancelTradeOffer,e,zm)}acceptTradeOffer(e){return this.send(Ke.AcceptTradeOffer,e,Mm)}declineTradeOffer(e){return this.send(Ke.DeclineTradeOffer,e,Om)}getMyTradeOffers(e){return this.send(Ke.GetMyTradeOffers,e,Cl)}getIncomingTradeOffers(e){return this.send(Ke.GetIncomingTradeOffers,e,Cl)}};var io=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(St.GetDefinitions,e,qr)}getActiveEvent(e){return this.send(St.GetActiveEvent,e,fp)}getUserState(e){return this.send(St.GetUserState,e,Ur)}getGroupState(e){return this.send(St.GetGroupState,e,ba)}joinOrCreateGroup(e){return this.send(St.JoinOrCreateGroup,e,ba)}spin(e){return this.send(St.Spin,e,Ie(yp))}claimObjectReward(e){return this.send(St.ClaimObjectReward,e,Da)}claimGrandPrize(e){return this.send(St.ClaimGrandPrize,e,Da)}leaveGroup(e){return this.send(St.LeaveGroup,e,Rp)}};var so=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(Pt.GetDefinition,e,wp)}getUserState(e){return this.send(Pt.GetUserState,e,kp)}getActiveDeals(e){return this.send(Pt.GetActiveDeals,e,Gr)}dismissDeal(e){return this.send(Pt.DismissDeal,e,Mp)}executeNode(e){return this.send(Pt.ExecuteNode,e,Ie(zp))}recordShow(e){return this.send(Pt.RecordShow,e,Op)}claimMilestone(e){return this.send(Pt.ClaimMilestone,e,Ep)}claimMilestonesBatch(e){return this.send(Pt.ClaimMilestonesBatch,e,Up)}};var bI=zod.z.object({}).passthrough().transform(n=>n),DI=zod.z.object({FeatureKey:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Rate:zod.z.number().nullish(),Basis:zod.z.string().nullish(),SourceCurrencyID:zod.z.string().nullish(),TargetCurrencyID:zod.z.string().nullish(),MinSourceAmount:zod.z.number().nullish(),MaxRewardPerOperation:zod.z.number().nullish(),Limits:Se.nullish()}).passthrough(),Sl=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:Q.nullish(),InviteRewards:zod.z.record(zod.z.string(),_e).nullish(),SpendRewards:zod.z.array(DI).nullish(),Qualification:zod.z.object({}).passthrough().transform(n=>n).nullish()}).passthrough(),xl=zod.z.object({Pending:zod.z.boolean().nullish(),Qualified:zod.z.boolean().nullish(),Groups:zod.z.array(zod.z.object({GroupID:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Conditions:zod.z.array(zod.z.object({Type:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Current:zod.z.number().nullish(),Required:zod.z.number().nullish()}).passthrough()).nullish()}).passthrough()).nullish()}).passthrough(),Um=zod.z.object({ReferralDefinitions:Sl.nullish()}).passthrough(),qm=zod.z.object({Referral:bI.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:xl.nullish()}).passthrough(),Lm=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:xl.nullish()}).passthrough(),Bm=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:H.nullish(),QualificationPending:zod.z.boolean().nullish(),Qualification:xl.nullish()}).passthrough(),bl=zod.z.object({RewardID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:H.nullish()}).passthrough(),Gm=bt(bl),Zt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var ro=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Zt.GetDefinitions,e,Um)}getUserState(e){return this.send(Zt.GetUserState,e,qm)}activateReferralCode(e){return this.send(Zt.ActivateReferralCode,e,Bm)}claimInviteReward(e){return this.send(Zt.ClaimInviteReward,e,bl)}claimInviteRewardsBatch(e){return this.send(Zt.ClaimInviteRewardsBatch,e,Gm)}checkQualification(e){return this.send(Zt.CheckQualification,e,Lm)}};var no=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(nt.GetDefinitions,e,Fp)}getMessages(e){return this.send(nt.GetMessages,e,Np)}getUnreadCount(e){return this.send(nt.GetUnreadCount,e,_r)}readMessages(e){return this.send(nt.ReadMessages,e,va)}claimReward(e){return this.send(nt.ClaimReward,e,Vr)}claimRewardsBatch(e){return this.send(nt.ClaimRewardsBatch,e,Vr)}claimAll(e){return this.send(nt.ClaimAll,e,Vr)}deleteMessages(e){return this.send(nt.DeleteMessages,e,va)}sendGift(e){return this.send(nt.SendGift,e,_p)}sendTransfer(e){return this.send(nt.SendTransfer,e,Vp)}getGiftStatus(e){return this.send(nt.GetGiftStatus,e,jp)}};var oo=class extends B{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Wr.RequestAdPermit,e,Wp)}completeView(e){return this.send(Wr.CompleteView,e,Hp)}};var ao=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(xe.GetFriendsList,e,$i)}getIncomingRequests(e){return this.send(xe.GetIncomingRequests,e,$i)}getOutgoingRequests(e){return this.send(xe.GetOutgoingRequests,e,$i)}getRecommendedFriends(e){return this.send(xe.GetRecommendedFriends,e,$i)}sendFriendRequest(e){return this.send(xe.SendFriendRequest,e,Ji)}acceptFriendRequest(e){return this.send(xe.AcceptFriendRequest,e,Ji)}declineFriendRequest(e){return this.send(xe.DeclineFriendRequest,e,Ji)}removeFriend(e){return this.send(xe.RemoveFriend,e,Ji)}getInbox(e){return this.send(xe.GetInbox,e,Qp)}markInboxSeen(e){return this.send(xe.MarkInboxSeen,e,Zi)}getInboxUnread(e){return this.send(xe.GetInboxUnread,e,Zi)}follow(e){return this.send(xe.Follow,e,Kt)}unfollow(e){return this.send(xe.Unfollow,e,Kt)}getFollowers(e){return this.send(xe.GetFollowers,e,Kr)}getFollowing(e){return this.send(xe.GetFollowing,e,Kr)}block(e){return this.send(xe.Block,e,Kt)}unblock(e){return this.send(xe.Unblock,e,Kt)}getBlocked(e){return this.send(xe.GetBlocked,e,Kr)}react(e){return this.send(xe.React,e,Kt)}unreact(e){return this.send(xe.Unreact,e,Kt)}getMyReactions(e){return this.send(xe.GetMyReactions,e,Jp)}getEntityStates(e){return this.send(xe.GetEntityStates,e,$p)}addComment(e){return this.send(xe.AddComment,e,Qr)}editComment(e){return this.send(xe.EditComment,e,Qr)}deleteComment(e){return this.send(xe.DeleteComment,e,Yp)}getComments(e){return this.send(xe.GetComments,e,Zp)}report(e){return this.send(xe.Report,e,Xp)}};var PI={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var pi=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),II=zod.z.object({BoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ae.nullish(),Effect:pi.nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),lo=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),Dl=zod.z.object({Availability:K.nullish(),Effects:K.nullish()}).passthrough(),vI=zod.z.object({ScheduledBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Effects:zod.z.array(pi).nullish(),Availability:lo.nullish(),Presets:Dl.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),TI=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(pi).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),AI=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Phases:zod.z.array(TI).nullish(),Availability:lo.nullish(),Presets:Dl.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),wI=zod.z.object({TriggeredBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Sources:zod.z.array(ut).nullish(),Effects:zod.z.array(pi).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:lo.nullish(),Presets:Dl.nullish()}).passthrough(),kI=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),zI=zod.z.object({Effects:zod.z.array(pi).nullish()}).passthrough(),MI=zod.z.object({Availability:zod.z.record(zod.z.string(),lo).nullish(),Effects:zod.z.record(zod.z.string(),zI).nullish()}).passthrough(),OI=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),kI).nullish()}).passthrough(),uo=zod.z.object({Definitions:zod.z.record(zod.z.string(),II).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),vI).nullish(),BoostChains:zod.z.record(zod.z.string(),AI).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),wI).nullish(),Settings:OI.nullish(),Presets:MI.nullish()}).passthrough(),Fm=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:pi.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:p.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:p.nullish()}).passthrough();var Nm=zod.z.object({ServerTimeUtc:p.nullish(),Active:zod.z.record(zod.z.string(),Fm).nullish()}),_m=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:Fm.nullish(),Resources:O.nullish()}),EI={Scheduled:"Scheduled",Chain:"Chain"},UI=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),Effects:zod.z.array(pi).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Vm=zod.z.object({ServerTimeUtc:p.nullish(),Windows:zod.z.array(UI).nullish()}),di={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var co=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(di.GetDefinitions,e,uo)}getActive(e){return this.send(di.GetActive,e,Nm)}getActiveWindows(e){return this.send(di.GetActiveWindows,e,Vm)}activate(e){return this.send(di.Activate,e,Ie(_m))}cleanupExpired(e){return this.send(di.CleanupExpired,e,Fe)}};var po=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(xt.GetUserCustomDataDefinitions,e,Yr)}getMyUserCustomData(e){return this.send(xt.GetMyUserCustomData,e,sd)}getPublicUserCustomDataOf(e){return this.send(xt.GetPublicUserCustomDataOf,e,Ma)}setPrivateData(e){return this.send(xt.SetPrivateData,e,Oa)}setPublicData(e){return this.send(xt.SetPublicData,e,Oa)}deleteKey(e){return this.send(xt.DeleteKey,e,Fe)}batchSet(e){return this.send(xt.BatchSet,e,rd)}batchDelete(e){return this.send(xt.BatchDelete,e,nd)}batchGetPublicUserCustomDataOf(e){return this.send(xt.BatchGetPublicUserCustomDataOf,e,od)}};var qI={Static:"Static",Runtime:"Runtime"},LI={Public:"Public",Private:"Private"},BI=zod.z.enum(["Client","Server","System"]).catch("Client"),GI=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),FI=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:p.nullish(),Version:zod.z.number().nullish(),LastWriter:BI.nullish(),ExpiresAt:p.nullish()}).passthrough(),jm=zod.z.record(zod.z.string(),FI),Pl=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:jm.nullish(),Runtime:jm.nullish(),NotModified:zod.z.boolean().nullish()}),NI=zod.z.object({KeyID:zod.z.string(),Scope:zod.z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:zod.z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:GI.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),ho=zod.z.object({Keys:zod.z.record(zod.z.string(),NI).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),ns={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var mo=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(ns.GetTitleCustomDataDefinitions,e,ho)}getPublicTitleData(e){return this.send(ns.GetPublicTitleData,e,Pl)}getPublicTitleDataKeys(e){return this.send(ns.GetPublicTitleDataKeys,e,Pl)}};var Wm=zod.z.object({Theme:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Radius:zod.z.number().nullish(),ButtonRadius:zod.z.number().nullish(),Outline:zod.z.number().nullish(),Background:zod.z.string().nullish(),MotionSpeed:zod.z.number().nullish(),MotionIntensity:zod.z.number().nullish(),Particles:zod.z.boolean().nullish(),SoundSet:zod.z.string().nullish()}).passthrough();var _I={Fast:"Fast",Sequential:"Sequential"},VI={Instant:"Instant",Timed:"Timed"};var jI={Hit:"Hit",Blocked:"Blocked"},WI=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),HI=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:Q.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Q.nullish()}).passthrough();var KI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Q.nullish()}).passthrough(),QI=zod.z.object({Reward:Q.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough();zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(KI).nullish(),Rate:QI.nullish()}).passthrough();zod.z.object({PlayedCount:zod.z.number().nullish(),RewardsClaimedCount:zod.z.number().nullish(),InstantClaimsCount:zod.z.number().nullish(),EarlyClaimsCount:zod.z.number().nullish(),LateClaimsCount:zod.z.number().nullish(),AdViewsTotal:zod.z.number().nullish(),StatRewardClaimsCount:zod.z.number().nullish(),StatReportsClampedCount:zod.z.number().nullish(),StatReportsUnknownMetricCount:zod.z.number().nullish()}).passthrough();var Hm=zod.z.object({}).passthrough().transform(n=>n),Km=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Qe=zod.z.object({Operation:O.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),$I=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),JI=zod.z.object({ShieldChance:zod.z.number().nullish(),DamagedBuildingChance:zod.z.number().nullish(),RankMultiplierMin:zod.z.number().nullish(),RankMultiplierMax:zod.z.number().nullish(),RankOffsetMin:zod.z.number().nullish(),RankOffsetMax:zod.z.number().nullish(),StageLevelSpread:zod.z.number().nullish()}).passthrough(),ZI=zod.z.object({CostMatrixTemplatesByID:zod.z.record(zod.z.string(),zod.z.array(zod.z.array(zod.z.number()))).nullish(),PerBoardGrowth:zod.z.number().nullish(),VisualTemplateCycle:zod.z.array(zod.z.string()).nullish(),EconomyScaledResources:pe.nullish(),ScaleRaidStealWithEconomy:zod.z.boolean().nullish(),ScaleAttackRewardWithEconomy:zod.z.boolean().nullish(),AttackValueFromCostMatrix:zod.z.boolean().nullish(),AttackBlockedRewardFactor:zod.z.number().nullish(),ScaleVictimLossWithEconomy:zod.z.boolean().nullish(),ScaleVictimLossWithTier:zod.z.boolean().nullish(),SynthesizedBuildingSlots:zod.z.number().nullish(),SynthesizedBuildingMaxLevel:zod.z.number().nullish(),DifficultyGrowthPerBoard:zod.z.number().nullish()}).passthrough(),YI=zod.z.object({CostMatrix:zod.z.array(zod.z.array(zod.z.number())).nullish(),PerBoardGrowth:zod.z.number().nullish(),EconomyScale:zod.z.number().nullish(),ScaledResources:pe.nullish()}).passthrough(),Qm=zod.z.object({SlotIndex:zod.z.number().nullish(),Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxLevel:zod.z.number().nullish(),MaxLevelReward:Q.nullish()}).passthrough(),XI=zod.z.object({Index:zod.z.number().nullish(),Type:zod.z.string().nullish(),CustomTypeID:zod.z.string().nullish(),RandomActionAttackWeight:zod.z.number().nullish(),RandomActionRaidWeight:zod.z.number().nullish(),ChanceTableID:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ev=zod.z.object({Tiles:zod.z.record(zod.z.string(),XI).nullish()}).passthrough(),tv=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Qe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),iv=zod.z.object({Weight:zod.z.number().nullish(),Tag:zod.z.string().nullish(),MinBonusCells:zod.z.number().nullish(),MaxBonusCells:zod.z.number().nullish(),BonusPool:zod.z.array(tv).nullish(),GuaranteedBonus:Qe.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),sv=zod.z.object({Variants:zod.z.array(iv).nullish()}).passthrough(),rv=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:Qe.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),nv=zod.z.object({Outcomes:zod.z.array(rv).nullish()}).passthrough(),$m=zod.z.object({PerAdMultiplierRange:Km.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),ov=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Qe.nullish()}).passthrough(),av=zod.z.object({Tiers:zod.z.array(ov).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Qe.nullish()}).passthrough(),lv=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Qe.nullish()}).passthrough(),uv=zod.z.object({Reward:Qe.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),cv=zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(lv).nullish(),Rate:uv.nullish()}).passthrough(),Jm=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),cv).nullish()}).passthrough(),pv=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ae.nullish(),Multipliers:$m.nullish(),Gradation:av.nullish(),RunStats:Jm.nullish()}).passthrough(),dv=zod.z.object({Choices:zod.z.array(pv).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),hv=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Qe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),mv=zod.z.object({OnPassStart:Qe.nullish(),OnTileLanding:zod.z.record(zod.z.string(),Qe).nullish(),OnAttack:zod.z.record(zod.z.string(),Qe).nullish(),OnRaid:zod.z.record(zod.z.string(),Qe).nullish(),OnBuild:Qe.nullish(),OnStageComplete:Qe.nullish(),OnAttackBonusDrops:zod.z.array(hv).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),nv).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),dv).nullish()}).passthrough(),Zm=zod.z.object({BaseAttackReward:Q.nullish(),BaseRaidReward:Q.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Qm).nullish(),HeistGridBonusConfig:sv.nullish(),StageOperations:mv.nullish(),TileLandingMultiplier:Km.nullish(),EconomyOverride:YI.nullish()}).passthrough(),fv=zod.z.object({Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BoardTemplateID:zod.z.string().nullish(),Buildings:zod.z.array(Qm).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:Zm.nullish()}).passthrough(),gv=zod.z.object({AttackCooldownSeconds:zod.z.number().nullish(),RaidCooldownSeconds:zod.z.number().nullish(),MaxRecentTargets:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),LiveOpponentPoolSize:zod.z.number().nullish(),LiveOpponentPoolCacheSeconds:zod.z.number().nullish(),MaxLiveCandidateReads:zod.z.number().nullish(),VictimImmunitySeconds:zod.z.number().nullish()}).passthrough(),yv=zod.z.object({Enabled:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),MaxPerCatchUp:zod.z.number().nullish(),Chance:zod.z.number().nullish(),AttackWeight:zod.z.number().nullish(),RaidWeight:zod.z.number().nullish(),MinBoardStageLevel:zod.z.number().nullish(),RaidLossMultiplier:zod.z.number().nullish()}).passthrough(),fo=zod.z.object({RollCurrencyID:zod.z.string().nullish(),ShieldCurrencyID:zod.z.string().nullish(),RaidMode:zod.z.string().nullish(),AllowedRollMultipliers:zod.z.array(zod.z.number()).nullish(),BoardTemplatesByID:zod.z.record(zod.z.string(),ev).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),Zm).nullish(),StagesByLevel:zod.z.record(zod.z.string(),fv).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:ZI.nullish(),Dice:$I.nullish(),Bots:JI.nullish(),Targeting:gv.nullish(),BotRaids:yv.nullish()}).passthrough(),Rv=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:p.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),GrandPrize:Q.nullish()}).passthrough(),go=zod.z.object({Board:fo.nullish(),CommunityChest:Rv.nullish()}).passthrough(),Ym=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),pe).nullish()}).passthrough(),Cv=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:Le.nullish(),TargetBuildingStates:zod.z.array(WI).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:Ym.nullish()}).passthrough(),Sv=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ae.nullish(),Multipliers:$m.nullish(),RunStats:Jm.nullish()}).passthrough(),xv=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(Sv).nullish()}).passthrough(),bv=zod.z.object({GroupID:zod.z.string().nullish(),Delta:W.nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),Xm=zod.z.object({UsedMultiplier:zod.z.number().nullish(),Steps:zod.z.number().nullish(),DiceValues:zod.z.array(zod.z.number()).nullish(),OldPosition:zod.z.number().nullish(),NewPosition:zod.z.number(),CyclesCompletedDelta:W.nullish(),LandedTileType:zod.z.string().nullish(),Operation:O.nullish(),Inventory:H.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:Cv.nullish(),SpecialModeOffer:xv.nullish(),CommunityChestContribution:bv.nullish()}).passthrough(),ef=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:O.nullish(),Inventory:H.nullish(),DualResult:Mt.nullish()}).passthrough(),Il=zod.z.object({Status:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),FoundSymbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),FoundBonus:Q.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(HI).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:H.nullish(),DualResult:Mt.nullish(),RaidRewardPreview:Ym.nullish()}).passthrough(),tf=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:H.nullish()}).passthrough(),sf=zod.z.object({CreditsConfirmation:fe.nullish(),Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:O.nullish(),Inventory:H.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish()}).passthrough(),rf=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),Dv=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),nf=zod.z.object({FinalMultiplier:zod.z.number().nullish(),AdViewsUsed:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),IsEarlyClaim:zod.z.boolean().nullish(),ReachedTierIndex:zod.z.number().nullish(),Operation:O.nullish(),Inventory:H.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(Dv).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:Q.nullish()}).passthrough(),Pv={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},of=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),Iv={Active:"Active",Left:"Left",Replaced:"Replaced"},vv=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),Tv=zod.z.object({CurrentProgress:W.nullish(),MaxProgress:W.nullish()}).passthrough(),Av=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Le.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:W.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),hu).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:vv.nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),af=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(Av).nullish(),SharedProgress:Tv.nullish(),Status:of.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:zod.z.number().nullish()}).passthrough(),wv=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:of.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:p.nullish()}).passthrough(),kv=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(wv).nullish()}).passthrough(),lf=zod.z.object({ServerTimeUtc:p.nullish(),UserState:kv.nullish(),ActiveGroup:af.nullish(),SecondsRemaining:W.nullish()}),uf=zod.z.object({ServerTimeUtc:p.nullish(),Group:af.nullish(),SecondsRemaining:W.nullish()}),vl=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:H.nullish()}),cf=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Ne={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var zv={Mesh:"Mesh",Host:"Host"},Tl=zod.z.enum(["Mesh","Host"]).catch("Mesh"),Mv={ServerRelay:"ServerRelay",P2P:"P2P"},Al=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),Ov={Public:"Public",Private:"Private"},Ev=zod.z.enum(["Public","Private"]).catch("Public"),Uv={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},qv=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),pf=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),Lv=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),df=zod.z.object({SystemState:Lv.nullish(),DefaultTopology:Tl.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:Al.nullish(),AllowCreatorChatOverride:zod.z.boolean().nullish(),MaxPlayersPerRoom:zod.z.number().nullish(),RoomTtlSeconds:zod.z.number().nullish(),MaxRoomLifetimeSeconds:zod.z.number().nullish(),HeartbeatIntervalMs:zod.z.number().nullish(),MemberTimeoutMs:zod.z.number().nullish(),MaxSignalPayloadBytes:zod.z.number().nullish(),MaxChatTextLength:zod.z.number().nullish(),RoomLogCap:zod.z.number().nullish(),VoiceEnabled:zod.z.boolean().nullish(),RecordVoices:zod.z.boolean().nullish(),IceServers:zod.z.array(pf).nullish()}).passthrough(),Bv=zod.z.object({UserID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),Ready:zod.z.boolean().nullish(),State:zod.z.record(zod.z.string(),zod.z.string()).nullish(),JoinedAt:zod.z.number().nullish(),IsHost:zod.z.boolean().nullish(),LastSeenMs:zod.z.number().nullish()}).passthrough(),Gv=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:Tl.nullish(),ChatMode:Al.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),Fv=zod.z.object({Seq:zod.z.number().nullish(),Type:qv.nullish(),FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Payload:zod.z.string().nullish(),Ts:zod.z.number().nullish()}).passthrough(),os=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:Tl.nullish(),ChatMode:Al.nullish(),Visibility:Ev.nullish(),Status:zod.z.string().nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),Members:zod.z.array(Bv).nullish(),IceServers:zod.z.array(pf).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),hf=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),mf=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),wl=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),ff=zod.z.object({Rooms:zod.z.array(Gv).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),gf=zod.z.object({Envelopes:zod.z.array(Fv).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),yo=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),Xe={CreateRoom:"CreateRoom",JoinRoom:"JoinRoom",LeaveRoom:"LeaveRoom",ListRooms:"ListRooms",GetRoom:"GetRoom",CloseRoom:"CloseRoom",Poll:"Poll",SendSignal:"SendSignal",SendChat:"SendChat",SetMemberState:"SetMemberState",ClaimHost:"ClaimHost",KickMember:"KickMember",UnbanMember:"UnbanMember"};var kl=zod.z.object({TitleCustomData:ho.nullish(),Character:Ar.nullish(),Item:An.nullish(),Currency:nn.nullish(),Store:Qs.nullish(),Lootbox:hl.nullish(),Quest:bs.nullish(),TimedEvent:hr.nullish(),Leaderboard:xr.nullish(),Season:Pr.nullish(),Reward:fl.nullish(),Collection:eo.nullish(),Craft:yl.nullish(),DealOffer:Pa.nullish(),Premium:cl.nullish(),TimedBoost:uo.nullish(),CoopEvent:qr.nullish(),GameLoop:go.nullish(),Match:ja.nullish(),Experiment:Th.nullish(),Blockchain:La.nullish(),Marketplace:$a.nullish(),Multiplayer:df.nullish(),UserCustomData:Yr.nullish(),Referral:Sl.nullish(),Localization:kh.nullish(),Analytics:gh.nullish(),Social:ed.nullish(),PlatformBridge:td.nullish(),GameSpec:zod.z.string().nullish(),Look:Wm.nullish()}).passthrough();var hi={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Ro=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(hi.GetTitlePublicConfiguration,e,kl)}getTitlePublicConfigurationExcept(e){return this.send(hi.GetTitlePublicConfigurationExcept,e,kl)}getCurrencyDefinitions(e){return this.send(hi.GetCurrencyDefinitions,e,nn)}getItemDefinitions(e){return this.send(hi.GetItemDefinitions,e,An)}getServerTime(e){return this.send(hi.GetServerTime,e,Fe)}};var Co=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Ne.GetGameLoops,e,go)}getBoardDefinition(e,t=false){return this.send(Ne.GetBoardDefinition,e,fo,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Ne.GetBoardDefinitionForLevel,e,fo,{silent:t})}getUserBoardState(e){return this.send(Ne.GetUserBoardState,e,Hm)}boardLoopRoll(e){return this.send(Ne.BoardLoopRoll,e,Xm)}boardLoopAttack(e){return this.send(Ne.BoardLoopAttack,e,ef)}boardLoopRaid(e){return this.send(Ne.BoardLoopRaid,e,Il)}boardLoopRaidFast(e){return this.send(Ne.BoardLoopRaidFast,e,Il)}boardLoopBuild(e){return this.send(Ne.BoardLoopBuild,e,tf)}boardSpecialChoose(e){return this.send(Ne.BoardSpecialChoose,e,Ie(sf))}boardSpecialApplyMultiplier(e){return this.send(Ne.BoardSpecialApplyMultiplier,e,rf)}boardSpecialClaim(e){return this.send(Ne.BoardSpecialClaim,e,nf)}getCommunityChestState(e){return this.send(Ne.GetCommunityChestState,e,lf)}joinOrCreateCommunityChest(e){return this.send(Ne.JoinOrCreateCommunityChest,e,uf)}claimCommunityChestMilestone(e){return this.send(Ne.ClaimCommunityChestMilestone,e,vl)}claimCommunityChestGrandPrize(e){return this.send(Ne.ClaimCommunityChestGrandPrize,e,vl)}leaveCommunityChest(e){return this.send(Ne.LeaveCommunityChest,e,cf)}};var Nv={Live:"Live",Latest:"Latest",Specific:"Specific"},_v={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},Vv=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),jv={None:"None",Disabled:"Disabled",NoActiveRevision:"NoActiveRevision",RevisionNotFound:"RevisionNotFound",InvalidFieldName:"InvalidFieldName",RateLimited:"RateLimited",HandlerNotFound:"HandlerNotFound",HandlerDisabled:"HandlerDisabled",Timeout:"Timeout",StatementCountExceeded:"StatementCountExceeded",StackOverflow:"StackOverflow",ApiCallLimitExceeded:"ApiCallLimitExceeded",JavaScriptException:"JavaScriptException",ExecutionError:"ExecutionError"},Wv=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),Hv=zod.z.object({Level:Vv,Message:zod.z.string().nullish(),Data:Wt.nullish()}),Kv=zod.z.object({Error:Wv,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Rf=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:Wt.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(Hv).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:Kv.nullish()}),zl={Execute:"Execute"};var So=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(zl.Execute,e,Rf)}};var xo=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Ye.GetDefinitions,e,Pd)}getUserState(e){return this.send(Ye.GetUserState,e,Id)}depositToken(e){return this.send(Ye.DepositToken,e,vd)}depositNFT(e){return this.send(Ye.DepositNFT,e,Td)}requestTokenWithdrawal(e){return this.send(Ye.RequestTokenWithdrawal,e,Ad)}requestNFTWithdrawal(e){return this.send(Ye.RequestNFTWithdrawal,e,wd)}getTransactionHistory(e){return this.send(Ye.GetTransactionHistory,e,kd)}retryWithdrawal(e){return this.send(Ye.RetryWithdrawal,e,zd)}confirmWithdrawal(e){return this.send(Ye.ConfirmWithdrawal,e,Md)}donateToDeveloper(e){return this.send(Ye.DonateToDeveloper,e,Na)}donateToUsersPool(e){return this.send(Ye.DonateToUsersPool,e,Na)}getPlayAccess(e){return this.send(Ye.GetPlayAccess,e,bd)}confirmPlayAccess(e){return this.send(Ye.ConfirmPlayAccess,e,Qt)}};var bo=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Oe.GetDefinitions,e,Hd)}getGroupedOffers(e){return this.send(Oe.GetGroupedOffers,e,Kd)}getOffersByItem(e){return this.send(Oe.GetOffersByItem,e,Ja)}getOffer(e){return this.send(Oe.GetOffer,e,Qd)}getBuyOrders(e){return this.send(Oe.GetBuyOrders,e,Ja)}getMyState(e){return this.send(Oe.GetMyState,e,dn)}getHistory(e){return this.send(Oe.GetHistory,e,Jd)}createListing(e){return this.send(Oe.CreateListing,e,ts)}cancelListing(e){return this.send(Oe.CancelListing,e,ht)}buy(e){return this.send(Oe.Buy,e,ht)}marketBuy(e){return this.send(Oe.MarketBuy,e,ht)}marketSell(e){return this.send(Oe.MarketSell,e,ht)}createAuction(e){return this.send(Oe.CreateAuction,e,ts)}placeBid(e){return this.send(Oe.PlaceBid,e,$d)}claimAuction(e){return this.send(Oe.ClaimAuction,e,ht)}createBuyOrder(e){return this.send(Oe.CreateBuyOrder,e,ts)}cancelBuyOrder(e){return this.send(Oe.CancelBuyOrder,e,ht)}fillBuyOrder(e){return this.send(Oe.FillBuyOrder,e,ht)}createDirectTrade(e){return this.send(Oe.CreateDirectTrade,e,ts)}respondDirectTrade(e){return this.send(Oe.RespondDirectTrade,e,ht)}cancelDirectTrade(e){return this.send(Oe.CancelDirectTrade,e,ht)}claimBack(e){return this.send(Oe.ClaimBack,e,ht)}};var Do=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(Xe.CreateRoom,e,os)}joinRoom(e){return this.send(Xe.JoinRoom,e,os)}leaveRoom(e,t=false){return this.send(Xe.LeaveRoom,e,wl,{keepalive:t})}listRooms(e){return this.send(Xe.ListRooms,e,ff)}getRoom(e){return this.send(Xe.GetRoom,e,os)}closeRoom(e){return this.send(Xe.CloseRoom,e,wl)}poll(e){return this.send(Xe.Poll,e,gf)}sendSignal(e){return this.send(Xe.SendSignal,e,yo,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(Xe.ClaimHost,e,os)}kickMember(e){return this.send(Xe.KickMember,e,hf)}unbanMember(e){return this.send(Xe.UnbanMember,e,mf)}sendChat(e){return this.send(Xe.SendChat,e,yo)}setMemberState(e){return this.send(Xe.SetMemberState,e,yo)}};var Qv={Free:"Free",Price:"Price",Holding:"Holding"},Ml=zod.z.enum(["Free","Price","Holding"]).catch("Free"),$v={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},Jv=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),Zv={All:"All",Any:"Any"},Yv=zod.z.enum(["All","Any"]).catch("All"),Xv={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},eT=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),tT={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},iT=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),sT={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Sf=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),rT={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},nT={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},oT=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),aT=zod.z.object({Type:Ci.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),MinLevel:zod.z.number().nullish()}).passthrough(),lT=zod.z.object({Requirements:zod.z.array(aT).nullish(),Match:Yv.nullish(),Mode:Jv.nullish()}).passthrough(),uT=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Ml.nullish(),Price:pe.nullish(),Holding:lT.nullish()}).passthrough(),cT=zod.z.object({AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxBytes:zod.z.number().nullish(),MaxCount:zod.z.number().nullish(),Required:zod.z.boolean().nullish()}).passthrough(),pT=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),cT).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(Ml).nullish(),PricePolicy:pn.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ae.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),dT=zod.z.object({Allowed:zod.z.array(es).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),hT=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),mT=zod.z.object({MaxTitleLength:zod.z.number().nullish(),MaxDescriptionLength:zod.z.number().nullish(),MaxTags:zod.z.number().nullish(),MaxTagLength:zod.z.number().nullish(),MaxMetadataKeys:zod.z.number().nullish(),MaxMetadataValueLength:zod.z.number().nullish(),MaxAccessOptions:zod.z.number().nullish(),ThumbnailMaxBytes:zod.z.number().nullish()}).passthrough(),fT=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Schedule:Re.nullish(),Gate:Z.nullish(),Order:zod.z.number().nullish()}).passthrough(),gT=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:Re.nullish(),ContentTypes:zod.z.record(zod.z.string(),pT).nullish(),PricePolicy:pn.nullish(),Commission:Qa.nullish(),HoldingPolicy:dT.nullish(),Moderation:hT.nullish(),Limits:mT.nullish(),Featured:zod.z.array(fT).nullish()}).passthrough(),yT=zod.z.object({Acquisitions:zod.z.number().nullish(),Downloads:zod.z.number().nullish(),Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),ReportCount:zod.z.number().nullish(),Remixes:zod.z.number().nullish()}).passthrough(),mi=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:Le.nullish(),Title:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Metadata:zod.z.record(zod.z.string(),zod.z.string()).nullish(),ThumbnailUrl:zod.z.string().nullish(),Visibility:eT.nullish(),Access:zod.z.array(uT).nullish(),Status:iT.nullish(),ModerationNote:zod.z.string().nullish(),Stats:yT.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),PublishedAt:p.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),RT=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Ml.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),xf=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Order:zod.z.number().nullish()}).passthrough(),bf=zod.z.object({Definitions:gT.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish(),CanPublish:zod.z.record(zod.z.string(),zod.z.boolean()).nullish(),Collections:zod.z.array(xf).nullish()}).passthrough(),Po=zod.z.object({Items:zod.z.array(mi).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Df=zod.z.object({Content:mi.nullish(),AccessState:zod.z.array(RT).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Pf=zod.z.object({Collection:xf.nullish(),Items:zod.z.array(mi).nullish()}).passthrough(),If=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:Le.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(mi).nullish()}).passthrough(),Cf=zod.z.object({Role:zod.z.string().nullish(),Index:zod.z.number().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish(),ServerCopy:zod.z.boolean().nullish()}).passthrough(),vf=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(Cf).nullish(),ThumbnailUpload:Cf.nullish(),ExpiresAt:p.nullish()}).passthrough(),Tf=zod.z.object({CreditsConfirmation:fe.nullish(),Content:mi.nullish(),Resources:O.nullish()}).passthrough(),Ol=zod.z.object({Content:mi.nullish()}).passthrough(),Af=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Sf.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:Mt.nullish(),Resources:O.nullish(),CommissionTaken:pe.nullish()}).passthrough(),CT=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),wf=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:oT.nullish(),Files:zod.z.array(CT).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:p.nullish()}).passthrough(),ST=zod.z.object({ContentID:zod.z.string().nullish(),Source:Sf.nullish(),OptionID:zod.z.string().nullish(),PricePaid:pe.nullish(),AcquiredAt:p.nullish(),Content:mi.nullish()}).passthrough(),kf=zod.z.object({Licenses:zod.z.array(ST).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),$e={GetDefinitions:"GetDefinitions",Browse:"Browse",GetContent:"GetContent",GetCollection:"GetCollection",GetCreatorProfile:"GetCreatorProfile",BeginUpload:"BeginUpload",Publish:"Publish",UpdateContent:"UpdateContent",Unpublish:"Unpublish",GetMyContent:"GetMyContent",Acquire:"Acquire",GetDownload:"GetDownload",GetMyLicenses:"GetMyLicenses",GetMyFavorites:"GetMyFavorites"};var Io=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send($e.GetDefinitions,e,bf)}browse(e){return this.send($e.Browse,e,Po)}getContent(e){return this.send($e.GetContent,e,Df)}getCollection(e){return this.send($e.GetCollection,e,Pf)}getCreatorProfile(e){return this.send($e.GetCreatorProfile,e,If)}beginUpload(e){return this.send($e.BeginUpload,e,vf)}publish(e){return this.send($e.Publish,e,Ie(Tf))}updateContent(e){return this.send($e.UpdateContent,e,Ol)}unpublish(e){return this.send($e.Unpublish,e,Ol)}getMyContent(e){return this.send($e.GetMyContent,e,Po)}acquire(e){return this.send($e.Acquire,e,Af)}getDownload(e){return this.send($e.GetDownload,e,wf)}getMyLicenses(e){return this.send($e.GetMyLicenses,e,kf)}getMyFavorites(e){return this.send($e.GetMyFavorites,e,Po)}};var vo=class extends B{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,ih,"defs")}get(e){return this.sendKeyed("Get",e,Ya,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,rh,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,Xa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,nh,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,el,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,el,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,oh,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,lh,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,ah,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,uh,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,sh,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,ch,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,Ya,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,Xa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var To=class{settings;emitter;host;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;credits;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.host=e.host??Go(),this.settings=Bl(e,this.host),this.emitter=new qi,this.clientPlatform=e.clientPlatform??this.host.getClientPlatform(),this.acquisition=new si(this.host),this.acquisition.capture(),this.playtime=new ji(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{}),this.host.supports.storePurchases&&this.purchase.restorePending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new ws({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e.fetch,debugLogging:this.settings.debugLogging,throttleMs:e.throttleMs,maxRequestsPerSecond:e.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new Os(this.emitter),this.cache=new Us(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new qs(this.host.storage,this.settings.titleID),this.api={authentication:new Pn(this),user:new In(this),currency:new vn(this),item:new wn(this),store:new kn(this),purchase:new En(this),lootbox:new Ln(this),reward:new Bn(this),quest:new jn(this),tutorial:new Gn(this),communityMarketing:new Fn(this),chat:new Nn(this),push:new _n(this),localization:new Vn(this),timedEvent:new Wn(this),leaderboard:new Hn(this),season:new Kn(this),premium:new Qn(this),character:new $n(this),match:new Jn(this),craft:new Yn(this),ai:new Xn(this),collection:new to(this),coopEvent:new io(this),dealOffer:new so(this),referral:new ro(this),mailbox:new no(this),advertising:new oo(this),social:new ao(this),timedBoost:new co(this),userCustomData:new po(this),titleCustomData:new mo(this),title:new Ro(this),gameLoop:new Co(this),cloudCode:new So(this),blockchain:new xo(this),marketplace:new bo(this),multiplayer:new Do(this),workshop:new Io(this),dataCollections:new vo(this),analytics:new xn(this),experiment:new bn(this)},this.userService=new _s(this),this.cache.attachState(this.userService),this.auth=new Bs(this),this.currency=new js(this),this.item=new Ws(this),this.store=new Js(this),this.credits=new Zs(this),this.purchase=new Ys(this),this.checkout=new Xs(this),this.lootbox=new er(this),this.reward=new ir(this),this.quest=new dr(this),this.tutorial=new rr(this),this.communityMarketing=new nr(this),this.chat=new lr(this),this.push=new ur(this),this.localization=new pr(this),this.timedEvent=new fr(this),this.leaderboard=new br(this),this.season=new Ir(this),this.premium=new vr(this),this.character=new wr(this),this.match=new kr(this),this.craft=new zr(this),this.ai=new Or(this),this.collection=new Er(this),this.coopEvent=new Lr(this),this.dealOffer=new Fr(this),this.referral=new Nr(this),this.mailbox=new jr(this),this.ads=new Hr(this),this.social=new $r(this),this.timedBoost=new Jr(this),this.userCustomData=new Xr(this),this.titleCustomData=new en(this),this.title=new tn(this),this.gameLoop=new sn(this),this.cloudCode=new rn(this),this.blockchain=new an(this),this.marketplace=new hn(this),this.multiplayer=new mn(this),this.workshop=new fn(this),this.dataCollections=new yn(this),this.analytics=new Cn(this),this.experiments=new Sn(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.host.getFullURL(),RelatedEntityID:G()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var Ao=class{ctx;constructor(e){this.ctx=new To(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),r=Jt(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(r,{...s,...i},zod.z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get host(){return this.ctx.host}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function bT(n){return new Ao(n)}var zf="idos_sso",Mf="state",El="idos:sso:state",DT="https://idosgames.com/sso/",PT=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],IT=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function vT(){if(typeof window>"u")return false;let{origin:n}=window.location;return PT.includes(n)||IT.test(n)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function TT(){if(typeof window>"u")return null;let n=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!n)return null;let e=new URLSearchParams(n),t=e.get(zf);if(!t)return null;let i=e.get(Mf)??"",s=MT();return ET(e),OT(),s&&i!==s?null:{code:t,state:i}}function AT(n){if(typeof window>"u")return;let e=n.returnTo??wT(),t=kT();zT(t);let i=new URL(n.ssoUrl??DT);i.searchParams.set("title",n.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function wT(){let{origin:n,pathname:e,search:t}=window.location;return `${n}${e}${t}`}function kT(){let n=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(n);else for(let e=0;e<n.length;e++)n[e]=Math.floor(Math.random()*256);return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function zT(n){try{window.sessionStorage.setItem(El,n);}catch{}}function MT(){try{return window.sessionStorage.getItem(El)}catch{return null}}function OT(){try{window.sessionStorage.removeItem(El);}catch{}}function ET(n){n.delete(zf),n.delete(Mf);let e=n.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var UT={EMAIL_SENDER_NOT_CONFIGURED:"Sign-in by e-mail is unavailable in this game right now. Try another way to sign in.",INVALID_VERIFICATION_CODE:"That code is not right. Check the e-mail and try again.",VERIFICATION_CODE_ATTEMPTS_EXCEEDED:"Too many wrong attempts. Ask for a new code.",INCORRECT_EMAIL_OR_PASSWORD:"Wrong e-mail or password.",INCORRECT_EMAIL:"That does not look like an e-mail address.",PASSWORD_LENGTH_INVALID:"The password must be 8 to 100 characters long.",TOO_MANY_FAILED_ATTEMPTS:"Too many attempts. Please try again a little later.",RATE_LIMIT_EXCEEDED:"Too many requests. Please try again in a moment.",APPLE_EMAIL_MISSING:"Apple did not share an e-mail address. Try again and allow it, or use another way to sign in.",INVALID_WALLET_SIGNATURE:"The signature does not match the wallet. Please try again.",WALLET_CHALLENGE_EXPIRED:"The request expired. Please try again.",WALLET_CHANGES_TOO_FREQUENT:"Too many wallets were changed this week. Try again in a few days.",WALLET_UNLINK_COOLDOWN:"This wallet was unlinked from another account less than 7 days ago. Try again after the 7 days.",PLAY_ACCESS_GUEST_DISABLED:"Guest play is off in this game. Sign in to link a crypto wallet.",PLAY_ACCESS_WALLET_LOGIN_ONLY:"This game can only be entered with a crypto wallet or your iDos Games account.",PLAY_ACCESS_WALLET_USED_BY_ANOTHER_ACCOUNT:"This wallet already plays with another account.",PLAY_ACCESS_WALLET_REQUIRED:"Link a crypto wallet to play.",PLAY_ACCESS_WALLET_NETWORK_NOT_GATED:"This wallet's network is not accepted here. Link a wallet of the required network.",PLAY_ACCESS_REQUIRED:"Check your balance to continue.",PLAY_ACCESS_CHECK_FAILED:"Could not check your balance right now. Please try again in a moment."};function qT(n,e="Something went wrong. Please try again."){return n?UT[n]??n:e}function LT(n,e){return !!n?.Claims?.[e]?.ClaimedAt}function BT(n){let e=n?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function GT(n,e){return n?.Claims?.[e]?.PremiumTiers??[]}function Ef(n,e,t,i=1){if(!n)return e;let s=n.Base??e,r=Math.max(0,t-i),o;switch(n.Shape??"Flat"){case "PerStep":o=s+(n.PerStep??0)*r;break;case "PerStepRate":o=s*(1+(n.PerStepRate??0)*r);break;case "Geometric":o=s*Math.pow(1+(n.GrowthRate??0),r);break;case "Table":o=s*Of(n,t,1);break;case "TableAbsolute":o=Of(n,t,s);break;default:o=s;break}return Number.isNaN(o)?s:(n.MinResult!=null&&o<n.MinResult&&(o=n.MinResult),n.MaxResult!=null&&o>n.MaxResult&&(o=n.MaxResult),o)}function FT(n,e,t=1){return Ef(n,1,e,t)}function NT(n){if(!n)return false;switch(n.Shape??"Flat"){case "PerStep":return (n.PerStep??0)!==0;case "PerStepRate":return (n.PerStepRate??0)!==0;case "Geometric":return (n.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return Uf(n.Points).length>0;default:return n.MinResult!=null||n.MaxResult!=null}}function _T(n){if(Number.isNaN(n)||n<=0)return 0;if(!Number.isFinite(n))return Number.MAX_SAFE_INTEGER;let e=Math.round(n);return Math.abs(n-e)<=1e-9*Math.max(1,Math.abs(n))?e:Math.ceil(n)}function Uf(n){if(!n)return [];let e=[];for(let t of n)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function Of(n,e,t){let i=Uf(n.Points);if(i.length===0)return t;let s=null,r=null,o=null;for(let c of i)(o===null||c.AtStep>o.AtStep)&&(o=c),c.AtStep<=e&&(s===null||c.AtStep>=s.AtStep)&&(s=c),c.AtStep>e&&(r===null||c.AtStep<r.AtStep)&&(r=c);if(s===null)return t;if(r===null){let c=n.TailGrowthRate??0;return c===0?o.Value:o.Value*Math.pow(1+c,e-o.AtStep)}switch(n.Interpolation??"Step"){case "Linear":{let c=(e-s.AtStep)/(r.AtStep-s.AtStep);return s.Value+c*(r.Value-s.Value)}case "Geometric":{if(s.Value<=0||r.Value<=0){let h=(e-s.AtStep)/(r.AtStep-s.AtStep);return s.Value+h*(r.Value-s.Value)}let c=(e-s.AtStep)/(r.AtStep-s.AtStep);return s.Value*Math.pow(r.Value/s.Value,c)}default:return s.Value}}var VT={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Ul=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),jT={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},WT=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),HT=zod.z.object({PlacementID:zod.z.string().nullish(),Type:Ul.nullish(),Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),CreditsRewarded:zod.z.number().nullish(),AllowedProviderIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),KT=zod.z.object({DefaultCreditsPerView:zod.z.number().nullish(),MaxCreditsBalance:zod.z.number().nullish(),DailyCreditEarnCap:zod.z.number().nullish(),DailyViewCap:zod.z.number().nullish(),MinSecondsBetweenViews:zod.z.number().nullish()}).passthrough(),QT=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),$T=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:WT.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),JT=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),ZT=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),YT=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),DisableInterstitials:zod.z.boolean().nullish(),DisableBanners:zod.z.boolean().nullish(),DisableAppOpen:zod.z.boolean().nullish()}).passthrough(),XT=zod.z.object({RequirePersonalizedAdsConsent:zod.z.boolean().nullish(),RequireTrackingConsent:zod.z.boolean().nullish(),CurrentPolicyVersion:zod.z.string().nullish(),RegulatedRegions:zod.z.array(zod.z.string()).nullish()}).passthrough(),eA=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),tA=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:Ul.nullish()}).passthrough(),iA={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},sA=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),rA=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:sA.nullish(),Enabled:zod.z.boolean().nullish(),Priority:zod.z.number().nullish(),AndroidAppID:zod.z.string().nullish(),IosAppID:zod.z.string().nullish(),WebAppID:zod.z.string().nullish(),Units:zod.z.record(zod.z.string(),tA).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),HT).nullish(),Providers:zod.z.record(zod.z.string(),rA).nullish(),RewardedVideo:KT.nullish(),Interstitial:QT.nullish(),Banner:$T.nullish(),AppOpen:JT.nullish(),FrequencyCapping:ZT.nullish(),PremiumAdReductions:zod.z.array(YT).nullish(),Consent:XT.nullish(),Verification:eA.nullish()}).passthrough();var nA=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),oA=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:p.nullish(),LastCompletedAt:p.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),aA=zod.z.object({Date:p.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),lA=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:p.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),uA=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:p.nullish(),ConsentRevokedAt:p.nullish()}).passthrough(),cA=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:Ul.nullish(),IssuedAt:p.nullish(),ExpiresAt:p.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),pA=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:p.nullish()}).passthrough();zod.z.object({Credits:nA.nullish(),Placements:zod.z.record(zod.z.string(),oA).nullish(),Daily:aA.nullish(),Session:lA.nullish(),LastImpressionAt:p.nullish(),LastInterstitialAt:p.nullish(),LastRewardedAt:p.nullish(),LastAppOpenAt:p.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:p.nullish(),Consent:uA.nullish(),PendingRequests:zod.z.record(zod.z.string(),cA).nullish(),FraudFlags:pA.nullish(),UpdatedAt:p.nullish()}).passthrough();
|
|
2
|
-
exports.AIAction=
|
|
1
|
+
'use strict';var zod=require('zod'),mn=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var mn__default=/*#__PURE__*/_interopDefault(mn);var $n=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.off(e,t);}}once(e,t){let n=this.on(e,i=>{n(),t(i);});return n}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e));}emit(e,t){let n=this.listeners.get(e);if(n)for(let i of [...n])i(t);}removeAllListeners(){this.listeners.clear();}};function mu(r){return {get:e=>r.getString(e),set:(e,t)=>r.setString(e,t),remove:e=>r.remove(e)}}var fu="https://api.idosgames.com";function gu(r,e){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??fu).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??mu(e.storage),locale:r.locale??e.getLanguage(),appVersion:r.appVersion??""}}function F(){return crypto.randomUUID()}var ey="idos-host-files",Di="files";function Ii(r){return new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function ty(r){return r.slice().buffer}var Pn=class{map=new Map;async read(e){let t=this.map.get(e);return t?t.bytes.slice():null}async write(e,t){return this.map.set(e,{bytes:t.slice(),updatedAt:Date.now()}),true}async remove(e){this.map.delete(e);}async list(e=""){let t=[];for(let[n,i]of this.map)n.startsWith(e)&&t.push({key:n,size:i.bytes.byteLength,updatedAt:i.updatedAt});return t.sort((n,i)=>i.updatedAt-n.updatedAt)}},ln=class{db=null;fallback=new Pn;open(){return this.db||(this.db=(async()=>{try{if(typeof indexedDB>"u")return null;let e=indexedDB.open(ey,1);return e.onupgradeneeded=()=>{e.result.objectStoreNames.contains(Di)||e.result.createObjectStore(Di,{keyPath:"key"});},await Ii(e)}catch{return null}})()),this.db}async store(e){let t=await this.open();if(!t)return null;try{return t.transaction(Di,e).objectStore(Di)}catch{return null}}async read(e){let t=await this.store("readonly");if(!t)return this.fallback.read(e);try{let n=await Ii(t.get(e));return n?new Uint8Array(n.bytes):null}catch{return null}}async write(e,t){let n=await this.store("readwrite");if(!n)return this.fallback.write(e,t);try{let i={key:e,bytes:ty(t),size:t.byteLength,updatedAt:Date.now()};return await Ii(n.put(i)),!0}catch{return false}}async remove(e){let t=await this.store("readwrite");if(!t)return this.fallback.remove(e);try{await Ii(t.delete(e));}catch{}}async list(e=""){let t=await this.store("readonly");if(!t)return this.fallback.list(e);try{let n=e&&typeof IDBKeyRange<"u"?IDBKeyRange.bound(e,e+"\uFFFF"):void 0,i=[];return await new Promise((s,o)=>{let p=t.openCursor(n);p.onerror=()=>o(p.error),p.onsuccess=()=>{let m=p.result;if(!m)return s();let g=m.value;g.key.startsWith(e)&&i.push({key:g.key,size:g.size,updatedAt:g.updatedAt}),m.continue();};}),i.sort((s,o)=>o.updatedAt-s.updatedAt)}catch{return []}}};function Jn(){return typeof document<"u"&&typeof document.createElement=="function"}function Pi(r={}){return Jn()?new Promise(e=>{let t=false,n=document.createElement("input");n.type="file",r.accept?.length&&(n.accept=r.accept.join(",")),n.multiple=r.multiple===true,n.style.display="none";let i=s=>{t||(t=true,n.remove(),e(s));};n.addEventListener("cancel",()=>i([])),n.addEventListener("change",()=>{let s=[...n.files??[]];Promise.all(s.map(async o=>{try{return {bytes:new Uint8Array(await o.arrayBuffer()),name:o.name,mime:o.type||"application/octet-stream"}}catch{return null}})).then(o=>i(o.filter(p=>p!==null)));}),document.body?.appendChild(n),n.click();}):Promise.resolve([])}var yu="idos_device_id",ta="idos:platformSignIn:declined:",dt="UNAVAILABLE",vn=Object.freeze({autoSignIn:false,signIn:false,rewardedAds:false,titleAds:false,storePurchases:false,creditsPayments:true,creditsConfirm:false,cryptoTopUp:false,sceneCaptureRequests:false,share:false,vibration:false,sharedMemory:false,filePicker:false,pushNotifications:false}),Ht=class{storage;files;visible=true;visibilityListeners=new Set;linkListeners=new Set;constructor(e,t=new Pn){this.storage=e,this.files=t;}buyProduct(e){return Promise.resolve({ok:false,error:dt})}finishPurchase(e,t){return Promise.resolve(false)}pendingPurchases(){return Promise.resolve([])}pickFiles(e){return Promise.resolve([])}requestPushToken(e){return Promise.resolve({error:dt})}getDeviceID(){let e=this.storage.getString(yu);return e||(e=this.newDeviceID(),this.storage.setString(yu,e)),e}newDeviceID(){return F()}setSignInDeclined(e,t){t?this.storage.setString(ta+e,"1"):this.storage.remove(ta+e);}isSignInDeclined(e){return this.storage.getString(ta+e)==="1"}isVisible(){return this.visible}onVisibilityChange(e){return this.visibilityListeners.add(e),()=>{this.visibilityListeners.delete(e);}}onLinkOpened(e){return this.linkListeners.add(e),()=>{this.linkListeners.delete(e);}}emitLink(e){for(let t of [...this.linkListeners])try{t(e);}catch{}}setVisible(e){if(e!==this.visible){this.visible=e;for(let t of [...this.visibilityListeners])try{t(e);}catch{}}}};function vi(r){return (typeof r=="number"?[r]:[...r]).map(t=>Math.max(0,Math.round(t)))}var un=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,t){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,t);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},Zn=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,t){this.map.set(e,t);}remove(e){this.map.delete(e);}};var xt={Virtual:"Virtual",Crypto:"Crypto"},Tn=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),Ai={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},wn=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),Ge={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Ti=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),ny={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},wi=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),iy={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Challenge:"Challenge",ChallengePoints:"ChallengePoints"},ki=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season","Challenge","ChallengePoints"]).catch("TimedEvent"),sy={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},Yn=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),qe={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};var Xn=class extends Ht{id="memory";supports;clientPlatform;deviceId;constructor(e={}){let t="getString"in e?{storage:e}:e;super(t.storage??new Zn),this.supports=Object.freeze({...vn,...t.supports}),this.clientPlatform=t.clientPlatform??Ge.Web,this.deviceId=t.deviceId??"memory-device";}setVisibleForTest(e){this.setVisible(e);}newDeviceID(){return this.deviceId}getPlatform(){return "Web"}getClientPlatform(){return this.clientPlatform}getFullURL(){return ""}getStartParameter(){return null}getReferrer(){return null}getTelegramInitDataRaw(){return null}getDeviceModel(){return "Memory"}getLanguage(){return ""}async signIn(){return {error:dt}}async showRewardedAd(){return {ok:false,error:dt}}async confirmCredits(){return {ok:false,error:dt}}async topUp(){return {ok:false,error:dt}}openInvoice(){}openUrl(){}async share(){return "unavailable"}async shareFile(){return "unavailable"}async copyText(){return false}vibrate(){}createWorker(){return null}};function ei(r){return [r.text,r.url].filter(e=>!!e).join(" ")}function zi(){return globalThis.crossOriginIsolated===true&&typeof SharedArrayBuffer<"u"}function Mi(r,e={}){if(typeof Worker>"u")return null;try{let t=typeof location<"u"?location.href:void 0,n=t?new URL(r,t):new URL(r),i={type:"module",name:e.name};if(n.protocol==="blob:"||n.protocol==="data:"||!t||n.origin===new URL(t).origin)return new Worker(n.href,i);let s=URL.createObjectURL(new Blob([`import ${JSON.stringify(n.href)};`],{type:"text/javascript"}));return new Worker(s,i)}catch{return null}}var na=1,Ru="__IDOS_HOST__";function ia(){let r=globalThis[Ru];return !r||typeof r!="object"||r.protocol!==1||typeof r.post!="function"?null:r}var ry={signIn:30*6e4,showRewardedAd:5*6e4,confirmCredits:10*6e4,topUp:15*6e4,openInvoice:3e4,openUrl:3e4,share:10*6e4,shareFile:10*6e4,copyText:3e4,vibrate:3e4,buyProduct:30*6e4,finishPurchase:6e4,pendingPurchases:6e4,requestPushToken:10*6e4};function oy(r){switch((r??"").toLowerCase()){case "android":return Ge.Android;case "ios":return Ge.Ios;case "web":return Ge.Web;default:return Ge.Unknown}}var ti=class extends Ht{id;supports;shell;pending=new Map;nextId=1;constructor(e,t=new un){super(t,new ln),this.shell=e,this.id=`native:${e.id??"unknown"}`;let n=e.capabilities??{},i=s=>n[s]??vn[s];this.supports=Object.freeze({autoSignIn:i("autoSignIn"),signIn:i("signIn")||i("autoSignIn"),rewardedAds:i("rewardedAds")||i("titleAds"),titleAds:i("titleAds"),storePurchases:i("storePurchases"),creditsPayments:i("creditsPayments"),creditsConfirm:i("creditsConfirm"),cryptoTopUp:i("cryptoTopUp"),sceneCaptureRequests:false,share:i("share"),vibration:i("vibration"),sharedMemory:zi(),filePicker:Jn(),pushNotifications:i("pushNotifications")}),e.receive=s=>this.receive(s),e.info?.visible===false&&this.setVisible(false);}receive(e){let t;try{t=JSON.parse(e);}catch{return}if(!(!t||t.v!==1)){if(t.kind==="response"&&typeof t.id=="string"){let n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id),clearTimeout(n.timer),n.resolve(t.ok===true?{ok:true,result:t.result??{}}:{ok:false,error:typeof t.error=="string"?t.error:"FAILED"});return}if(t.kind==="event"&&t.name==="visibility"){let n=t.data;typeof n?.visible=="boolean"&&this.setVisible(n.visible);return}if(t.kind==="event"&&t.name==="link"){let n=t.data;typeof n?.url=="string"&&n.url&&this.emitLink(n.url);}}}request(e,t){let n=`r${this.nextId++}`,i={v:1,kind:"request",id:n,method:e,params:t};return new Promise(s=>{let o=setTimeout(()=>{this.pending.delete(n),s({ok:false,error:"TIMEOUT"});},ry[e]);this.pending.set(n,{resolve:s,timer:o});try{this.shell.post(JSON.stringify(i));}catch{clearTimeout(o),this.pending.delete(n),s({ok:false,error:"UNAVAILABLE"});}})}notify(e,t){this.request(e,t);}newDeviceID(){return this.shell.info?.deviceId||super.newDeviceID()}getPlatform(){return this.getClientPlatform()===Ge.Ios?"iOS":this.getClientPlatform()}getClientPlatform(){return oy(this.shell.clientPlatform)}getFullURL(){return this.shell.info?.launchUrl??""}getStartParameter(){return this.shell.info?.startParameter??null}getReferrer(){return null}getTelegramInitDataRaw(){return null}getDeviceModel(){return this.shell.info?.deviceModel||this.id}getLanguage(){return this.shell.info?.language||""}async signIn(e){if(!this.supports.signIn)return {error:"UNAVAILABLE"};let t=await this.request("signIn",{titleID:e});if(!t.ok)return {error:t.error};let{code:n,ticket:i}=t.result;return typeof i=="string"&&i.length>0?{ticket:i}:typeof n=="string"&&n.length>0?{code:n}:{error:"no_code"}}async showRewardedAd(e){if(!this.supports.rewardedAds)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("showRewardedAd",e);return t.ok?{ok:true,via:t.result.via==="unit"?"unit":"ad"}:{ok:false,error:t.error}}async confirmCredits(e){if(!this.supports.creditsConfirm)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("confirmCredits",e);return t.ok?{ok:true}:{ok:false,error:t.error}}async topUp(e){if(!this.supports.cryptoTopUp)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("topUp",e);return t.ok?{ok:true}:{ok:false,error:t.error}}openInvoice(e){this.notify("openInvoice",{url:e});}async buyProduct(e){if(!this.supports.storePurchases)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("buyProduct",e);if(!t.ok)return {ok:false,error:t.error};let n=t.result.receipt;return n&&typeof n.receipt=="string"&&n.receipt?{ok:true,receipt:n}:{ok:false,error:"FAILED"}}async finishPurchase(e,t){return this.supports.storePurchases?(await this.request("finishPurchase",{receipt:e,consumable:t})).ok:false}async pendingPurchases(){if(!this.supports.storePurchases)return [];let e=await this.request("pendingPurchases",{});return !e.ok||!Array.isArray(e.result.receipts)?[]:e.result.receipts.filter(t=>t&&typeof t.receipt=="string"&&t.receipt)}async requestPushToken(e){if(!this.supports.pushNotifications)return {error:"UNAVAILABLE"};let t=await this.request("requestPushToken",{prompt:e.prompt===true});if(!t.ok)return {error:t.error};let{token:n,transport:i}=t.result;return typeof n!="string"||!n?{error:"UNAVAILABLE"}:{token:n,transport:i==="Apns"?"Apns":"Fcm"}}openUrl(e){this.notify("openUrl",{url:e});}async share(e){if(!this.supports.share)return await this.copyText(ei(e))?"copied":"unavailable";let t=await this.request("share",e);return t.ok?t.result.outcome??"shared":t.error==="CANCELLED"?"cancelled":"unavailable"}pickFiles(e){return Pi(e)}async shareFile(e){let t=await this.request("shareFile",{name:e.name,mime:e.mime,data:ay(e.bytes)});return t.ok?t.result.outcome??"shared":t.error==="CANCELLED"?"cancelled":"unavailable"}async copyText(e){return (await this.request("copyText",{text:e})).ok}vibrate(e){this.supports.vibration&&this.notify("vibrate",{pattern:vi(e)});}createWorker(e,t){return Mi(e,t)}};function ay(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)}function Kt(){return globalThis.Telegram?.WebApp??null}function Su(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return Cu(e);let t=r.cordova?.platformId;return t?Cu(t):r.navigator?.userAgent??""?Ge.Web:Ge.Unknown}function Cu(r){let e=r.toLowerCase();return e==="android"?Ge.Android:e==="ios"?Ge.Ios:e==="web"?Ge.Web:Ge.Unknown}var Lt=["https://idosgames.com","https://www.idosgames.com"],Oi="https://platform.idosgames.com",bu=/^[a-z0-9]{8}-preview\.idos\.games$/;function sa(r){return r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r.endsWith(".localhost")}function ra(){if(typeof window>"u")return false;let r=window.location.hostname.toLowerCase();return bu.test(r)?true:sa(r)&&globalThis.__IDOS_PREVIEW__!=null}function cn(r){if(typeof window<"u"&&bu.test(window.location.hostname.toLowerCase()))return r===Oi;if(Lt.includes(r))return true;if(typeof window>"u"||!sa(window.location.hostname))return false;try{return sa(new URL(r).hostname)}catch{return false}}var xu="IDOS_PLATFORM_WALLET_ACK",Du="PLATFORM_WALLET_UNAVAILABLE",ly=5e3,uy=18e4;function cy(){if(cn(Oi))return [Oi];let r=[...Lt],e=window.location.ancestorOrigins?.[0];return e&&!r.includes(e)&&cn(e)&&r.push(e),r}function py(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Bt(r,e,t,n={}){let i={ok:false,error:Du,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(i);let s=window.parent;if(!s)return Promise.resolve(i);let o=py(),p=n.answerTimeoutMs??uy;return new Promise(m=>{let g=false,j,ce=me=>{g||(g=true,window.removeEventListener("message",ve),clearTimeout(j),m(me));},ve=me=>{if(!cn(me.origin))return;let be=me.data;if(!(!be||be.requestId!==o)){if(be.type===xu){clearTimeout(j),j=setTimeout(()=>ce({ok:false,error:"TIMEOUT",data:{}}),p);return}be.type===e&&ce({ok:be.ok===true,error:typeof be.error=="string"?be.error:void 0,data:be});}};j=setTimeout(()=>ce(i),ly),window.addEventListener("message",ve);for(let me of cy())try{s.postMessage({type:r,requestId:o,...t},me);}catch{}})}var oa={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},hy=30*6e4;function Iu(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(ra())return false;let r=window.location.ancestorOrigins?.[0];if(r&&!Lt.includes(r))try{let e=new URL(r).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}function aa(){if(typeof window>"u"||!ra())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function Pu(r){let e=await Bt(oa.request,oa.response,{titleID:r,supports:["pgs"]},{answerTimeoutMs:hy}),t=e.data.ticket;if(e.ok&&typeof t=="string"&&t.length>0)return {ticket:t};let n=e.data.code;return e.ok&&typeof n=="string"&&n.length>0?{code:n}:{error:e.error??"no_code"}}var la={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},dy=15*6e4,my=/^[a-z0-9]{8}-preview\.idos\.games$/;function kn(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !my.test(window.location.hostname.toLowerCase())}async function vu(r){let e=await Bt(la.request,la.response,{titleID:r.titleID,userID:r.userID,currencyID:r.currencyID,amount:r.amount},{answerTimeoutMs:dy});return e.ok?{ok:true}:{ok:false,error:e.error}}var ua={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},fy=5*6e4;function Au(){return kn()}async function Tu(r){let e=await Bt(ua.request,ua.response,{titleID:r.titleID,userID:r.userID,requestID:r.requestID,placementID:r.placementID,adUnitID:r.adUnitID??null},{answerTimeoutMs:fy});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var ca={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},gy=10*6e4,yy=["DECLINED","NOT_ENOUGH_CREDITS"];function wu(){let r=globalThis.navigator?.userAgent??"";if(!/\biDosGamesApp\/(?:player|studio)\//.test(r))return true;let e=/\biDosGamesPlatform\/(ios|android)\b/.exec(r);return (e?e[1]:/\bAndroid\b/.test(r)?"android":"ios")!=="ios"}function ku(){return kn()}async function zu(r){let e=await Bt(ca.request,ca.response,{titleID:r.titleID,confirmationID:r.confirmationID},{answerTimeoutMs:gy});return e.ok?{ok:true}:{ok:false,error:e.error}}var Ou="IDOS_APP_FRAME_HIDDEN";function pn(){return globalThis.navigator??null}function Ei(){return typeof window<"u"}function Mu(){if(!Ei())return false;try{return window.self!==window.top}catch{return true}}var ni=class extends Ht{id;supports;hiddenBySite=false;documentHidden=false;constructor(e=new un){if(super(e,new ln),!Ei()){this.id="web",this.supports=vn;return}let t=pn(),n=Iu();this.supports=Object.freeze({autoSignIn:n,signIn:n||aa(),rewardedAds:Au(),titleAds:false,storePurchases:false,creditsPayments:wu(),creditsConfirm:ku(),cryptoTopUp:kn(),sceneCaptureRequests:Mu(),share:typeof t?.share=="function",vibration:typeof t?.vibrate=="function",sharedMemory:zi(),filePicker:Jn(),pushNotifications:false}),this.id=Kt()?"telegram":aa()?"preview":this.supports.cryptoTopUp?"site":"web",this.watchVisibility(),window.addEventListener("hashchange",()=>this.emitLink(window.location.href));}watchVisibility(){typeof document<"u"&&(this.documentHidden=document.visibilityState==="hidden",document.addEventListener("visibilitychange",()=>{this.documentHidden=document.visibilityState==="hidden",this.update();})),Mu()&&window.addEventListener("message",e=>{let t=e.data;!t||t.type!==Ou||cn(e.origin)&&(this.hiddenBySite=t.hidden===true,this.update());}),this.update();}update(){this.setVisible(!this.documentHidden&&!this.hiddenBySite);}getPlatform(){return Kt()?.platform??"Web"}getClientPlatform(){return Su()}getFullURL(){return Ei()?window.location.href:""}getStartParameter(){let e=Kt()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){return typeof document>"u"?null:document.referrer||null}getTelegramInitDataRaw(){let e=Kt()?.initData;return e&&e.length>0?e:null}getDeviceModel(){return pn()?.userAgent||"Web"}getLanguage(){return pn()?.language||""}async signIn(e){return this.supports.signIn?Pu(e):{error:dt}}async showRewardedAd(e){return this.supports.rewardedAds?Tu(e):{ok:false,error:dt}}async confirmCredits(e){return this.supports.creditsConfirm?zu(e):{ok:false,error:dt}}async topUp(e){return this.supports.cryptoTopUp?vu(e):{ok:false,error:dt}}openInvoice(e){let t=Kt();if(t?.openInvoice){t.openInvoice(e);return}this.openUrl(e);}openUrl(e){let t=Kt();if(t?.openTelegramLink&&/^https:\/\/t\.me\//i.test(e)){t.openTelegramLink(e);return}Ei()&&window.open(e,"_blank","noopener");}async share(e){let t=pn();if(t?.share)try{return await t.share({url:e.url||void 0,title:e.title,text:e.text}),"shared"}catch(n){if(n?.name==="AbortError")return "cancelled"}return await this.copyText(ei(e))?"copied":"unavailable"}pickFiles(e){return Pi(e)}async shareFile(e){if(typeof document>"u"||typeof Blob>"u")return "unavailable";let t=new Blob([e.bytes],{type:e.mime}),n=pn();if(typeof File<"u"&&n?.share&&n.canShare){let s=new File([t],e.name,{type:e.mime});if(n.canShare({files:[s]}))try{return await n.share({files:[s],title:e.name}),"shared"}catch(o){if(o?.name==="AbortError")return "cancelled"}}let i=document.createElement("a");return i.href=URL.createObjectURL(t),i.download=e.name,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(i.href),3e4),"saved"}async copyText(e){let t=pn();if(t?.clipboard)try{return await t.clipboard.writeText(e),!0}catch{}return Ry(e)}vibrate(e){try{pn()?.vibrate?.(vi(e));}catch{}}createWorker(e,t){return Mi(e,t)}};function Ry(r){if(typeof document>"u"||!document.body)return false;let e=document.createElement("textarea");e.value=r,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();let t=false;try{t=document.execCommand("copy");}catch{t=false;}return e.remove(),t}function pa(){let r=ia();return r?new ti(r):typeof window>"u"?new Xn:new ni}var ha="idos_acq",Eu=["gclid","fbclid","ttclid","msclkid","yclid"],Cy=["ref","r"],Sy=["ref_","ref-","ref=","r_","r-"];var dn=class{constructor(e){this.host=e;}host;capture(){let e=this.readFromEnvironment();by(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),n=t?{...t.signal}:{},i=Iy(this.host.getDeviceModel());return i&&(n.OsVersion=i),e&&(n.AppVersion=e),Object.keys(n).length>0?n:void 0}clear(){this.host.storage.remove(ha);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let n=Lu(Uu(t));if(n)return n}return qi(t)}readFromEnvironment(){let e={},t=Uu(this.host.getFullURL());hn(e,"UtmSource",t.get("utm_source")),hn(e,"UtmMedium",t.get("utm_medium")),hn(e,"UtmCampaign",t.get("utm_campaign")),hn(e,"UtmTerm",t.get("utm_term")),hn(e,"UtmContent",t.get("utm_content")),hn(e,"ClaimToken",t.get("idos_click"));for(let g of Eu){let j=t.get(g);if(j){e.ClickID=j;break}}let n=this.host.getStartParameter()??"",i=Dy(n);if(i){for(let g of xy)hn(e,g,i.get(Bu[g])??null);for(let g of Eu){let j=i.get(g);if(j){e.ClickID=j;break}}}let s=qi(i?i.get("ref")??i.get("r")??"":n),o=Lu(t),p=s||o;p&&(e.ReferralCode=p,e.ChannelHint=s?"telegram":"query");let m=this.host.getReferrer();return m&&(e.Referrer=m),e}read(){try{let e=this.host.storage.getString(ha);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.host.storage.setString(ha,JSON.stringify(e));}catch{}}};function by(r){return !!(r.UtmSource||r.UtmMedium||r.UtmCampaign||r.ClickID||r.Referrer||r.ReferralCode||r.ClaimToken)}function hn(r,e,t){t&&(r[e]=t);}var qu="a1_",Bu={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},xy=Object.keys(Bu);function Dy(r){let e=(r||"").trim();if(!e.startsWith(qu))return null;let t=e.slice(qu.length);if(!t)return null;try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),i=atob(n+"=".repeat((4-n.length%4)%4)),s=Uint8Array.from(i,m=>m.charCodeAt(0)),o=new TextDecoder().decode(s),p=new URLSearchParams(o);return [...p.keys()].length>0?p:null}catch{return null}}function Uu(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function Lu(r){for(let e of Cy){let t=r.get(e);if(t)return qi(t)}return null}function qi(r){let e=(r||"").trim();if(!e)return null;for(let t of Sy)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Iy(r){let e=r||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let n=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(n)return n[1]}var Gu="idos_usage_pending",Nu="idos_usage_session",_u="idos_usage_closed_session",Fu="idos_usage_new_session",Vu="idos_usage_last_activity",ii=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;stopVisibility=null;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=!this.ctx.host.isVisible(),this.timer=setInterval(()=>this.tick(),200*1e3),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=e=>{if(!e){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,n=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,n,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=n,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=n,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(Gu),this.currentSessionSeconds=this.readNumber(Nu),this.pendingClosedSessionSeconds=this.readNumber(_u),this.isNewSessionPending=this.readNumber(Fu)!==0;let e=this.readNumber(Vu);this.currentSessionSeconds>0&&e>0&&(Date.now()-e)/1e3>=1800&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,Math.floor(this.currentSessionSeconds)),this.currentSessionSeconds=0);}persist(){this.writeNumber(Gu,this.pendingSeconds),this.writeNumber(Nu,this.currentSessionSeconds),this.writeNumber(_u,this.pendingClosedSessionSeconds),this.writeNumber(Fu,this.isNewSessionPending?1:0),this.writeNumber(Vu,Date.now());}readNumber(e){let t=this.ctx.host.storage.getString(e),n=t?Number(t):0;return Number.isFinite(n)&&n>0?n:0}writeNumber(e,t){try{this.ctx.host.storage.setString(e,String(Math.floor(t)));}catch{}}};function B(r){return {ok:true,data:r}}function h(r,e){return {ok:false,reason:r,error:e}}var l=h("unauthorized","Not logged in.");function Py(r){return r.ok}function vy(r){return !r.ok}var Q=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="string"?Number(r):r;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(r)}`}),zod.z.NEVER)}),ne=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="number"?String(r):r.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(r)}`}),zod.z.NEVER):t}),u=zod.z.string();var Tt=zod.z.object({Type:wn.nullish(),CurrencyID:zod.z.string().nullish(),Amount:Q.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),Ay=zod.z.object({Type:ki.nullish(),EntityID:zod.z.string()}),Ty=zod.z.object({Address:Ay.nullish(),Amount:Q.nullish(),Source:zod.z.string().nullish()}),pe=zod.z.object({Entries:zod.z.array(Tt).nullish(),EventTokens:zod.z.array(Ty).nullish()}),ju=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:pe.nullish()}),$=zod.z.object({Standard:pe.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(ju).nullish()}),Gt=zod.z.object({Standard:pe.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(ju).nullish()}),O=zod.z.object({Grant:$.nullish(),Consume:Gt.nullish()}),Nt=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:O.nullish(),ToResult:O.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:pe.nullish()});var wy=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),ky={Completed:"Completed",Started:"Started",StepReached:"StepReached"},zy=zod.z.object({FlowIDs:zod.z.array(zod.z.string()).nullish(),Mode:zod.z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:zod.z.string().nullish(),Negate:zod.z.boolean().nullish(),SkippedCountsAsCompleted:zod.z.boolean().nullish()}).passthrough(),ee=zod.z.object({Segments:zod.z.array(zod.z.string()).nullish(),MinPremiumTier:zod.z.number().nullish(),RequiredPremiumIDs:zod.z.array(zod.z.string()).nullish(),MinLevel:zod.z.number().nullish(),MaxLevel:zod.z.number().nullish(),Countries:zod.z.array(zod.z.string()).nullish(),RegisteredWithinDays:zod.z.number().nullish(),ActiveWithinDays:zod.z.number().nullish(),Experiment:wy.nullish(),Tutorial:zy.nullish(),Platforms:zod.z.array(Ti).nullish()}).passthrough();var Pe=zod.z.object({TotalCap:zod.z.number().nullish(),DailyCap:zod.z.number().nullish(),DailyWeightCap:zod.z.number().nullish(),PerActivationCap:zod.z.number().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish()}).passthrough();var My=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Oy=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Ey=zod.z.object({AnchorUtc:zod.z.string().nullish(),MaxCycles:zod.z.number().nullish(),PauseBetweenPhasesSec:zod.z.number().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish()}).passthrough();zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();var qy=zod.z.object({Reset:zod.z.string().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:zod.z.string().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();zod.z.object({SourceType:zod.z.string().nullish(),TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var mt=zod.z.object({SourceType:zod.z.string().nullish(),BaseWeight:zod.z.number().nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish(),TileTypeFilter:zod.z.array(zod.z.string()).nullish(),TileIndexFilter:zod.z.array(zod.z.number()).nullish(),ChanceOutcomeFilter:zod.z.array(zod.z.string()).nullish(),OutcomeFilter:zod.z.array(zod.z.string()).nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Limits:Pe.nullish()}).passthrough(),Ce=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:Oy.nullish(),Chain:Ey.nullish(),Cyclic:qy.nullish(),ActivationTriggers:zod.z.array(mt).nullish(),Relative:My.nullish()}).passthrough();var Uy={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},Ly=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),By={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Gy=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),Ny=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Je=zod.z.object({Base:zod.z.number().nullish(),Shape:Ly.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(Ny).nullish(),Interpolation:Gy.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var _y=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:$.nullish()}).passthrough(),Fy=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),da=zod.z.object({Bundles:zod.z.array(_y).nullish(),Multipliers:zod.z.array(Fy).nullish()}).passthrough();var Vy=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Ui=zod.z.object({Source:Vy.nullish(),SourceKey:zod.z.string().nullish(),Curve:Je.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:pe.nullish(),ExcludeRewards:pe.nullish()}).passthrough(),Wu=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),Ve=zod.z.object({MilestoneID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredProgress:zod.z.number().nullish(),Rewards:$.nullish(),BonusRewards:$.nullish(),SeasonTierRewards:da.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),zn=zod.z.object({Milestones:zod.z.record(zod.z.string(),Ve).nullish()}).passthrough();var J=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var jy=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),wt=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxBalance:zod.z.number().nullish(),MaxPerGrant:zod.z.number().nullish(),DailyEarnCap:zod.z.number().nullish(),BurnOnEventEnd:zod.z.boolean().nullish(),BurnConversion:jy.nullish()}).passthrough();var Wy=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),Mn=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),EquippedSlot:Wy.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),K=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),Mn).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var Oe=r=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:r.nullish()}),kt=r=>zod.z.object({ServerTimeUtc:u,Items:zod.z.array(Oe(r)),Resources:O.nullish(),Inventory:K.nullish()});var Hy={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Hu=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Ky=zod.z.object({}).passthrough().transform(r=>r),Qy=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:u.nullish(),CycleEndUtc:u.nullish(),PointsTotalEarned:Q.nullish(),PointsCurrent:Q.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:Ve.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),ma=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:Q.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:Hu}),Ku=zod.z.object({State:Ky.nullish(),PointsTracks:zod.z.record(zod.z.string(),Qy).nullish()}),fa=zod.z.object({ServerTimeUtc:u,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:Hu.nullish(),Resources:O.nullish(),Inventory:K.nullish()}),ga=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:Q.nullish(),Resources:O.nullish(),Inventory:K.nullish(),NextMilestone:Ve.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Qu=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),$u=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(ma).nullish()}),Ju=zod.z.array(Oe(fa)),Zu=zod.z.array(Oe(ga)),$y={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Jy=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Zy={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Yy=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),Yu=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:Jy.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(mt).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),ya=zod.z.object({Milestones:J.nullish(),Linking:J.nullish(),Availability:J.nullish(),Reward:J.nullish(),Objectives:J.nullish()}).passthrough(),Xy=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Xu=zod.z.object({CycleIDs:zod.z.array(zod.z.string()).nullish(),GroupID:zod.z.string().nullish(),PhaseIDs:zod.z.array(zod.z.string()).nullish(),RequiredQuestIDs:zod.z.array(zod.z.string()).nullish(),PrerequisiteMode:Yy.nullish()}).passthrough(),ec=zod.z.object({Schedule:Ce.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),tc=zod.z.object({Grant:$.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),eR=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Xy.nullish(),Linking:Xu.nullish(),Availability:ec.nullish(),Objectives:zod.z.record(zod.z.string(),Yu).nullish(),Reward:tc.nullish(),Presets:ya.nullish()}).passthrough(),tR=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:ee.nullish(),Reward:$.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),nR=zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Gate:ee.nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),Presets:ya.nullish(),PointsToken:wt.nullish()}).passthrough(),iR=zod.z.object({Milestones:zod.z.record(zod.z.string(),zn).nullish(),Linking:zod.z.record(zod.z.string(),Xu).nullish(),Availability:zod.z.record(zod.z.string(),ec).nullish(),Reward:zod.z.record(zod.z.string(),tc).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Yu)).nullish()}).passthrough(),sR=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Ce.nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),Gate:ee.nullish(),PointsToken:wt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),tR).nullish(),Phases:zod.z.record(zod.z.string(),nR).nullish(),Presets:ya.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Bi=zod.z.object({Cycles:zod.z.record(zod.z.string(),sR).nullish(),Quests:zod.z.record(zod.z.string(),eR).nullish(),Presets:iR.nullish()}).passthrough(),It={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var rR={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},oR=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),aR={Never:"Never",OnRequest:"OnRequest",Always:"Always"},lR=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),uR={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},cR=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),pR={GameLoop:"GameLoop"},hR={Raid:"Raid",Attack:"Attack"},dR=zod.z.object({Title:zod.z.string().nullish(),TitleKey:zod.z.string().nullish(),Body:zod.z.string().nullish(),BodyKey:zod.z.string().nullish(),AnchorID:zod.z.string().nullish(),HighlightTarget:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),UiHint:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),mR=zod.z.object({Mode:oR.nullish(),Triggers:zod.z.array(mt).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),fR=zod.z.object({Grant:$.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),gR=zod.z.object({TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),RandomActionType:zod.z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),yR=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:gR.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),RR=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),Ra=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:dR.nullish(),Completion:mR.nullish(),Effects:fR.nullish(),Script:yR.nullish(),Policy:RR.nullish()}).passthrough(),CR=zod.z.object({DisplayName:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),Description:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),nc=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:mt.nullish()}).passthrough(),ic=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:lR.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),sc=zod.z.object({Grant:$.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),SR=zod.z.object({Availability:J.nullish(),Policy:J.nullish(),Reward:J.nullish(),Steps:J.nullish()}).passthrough(),bR=zod.z.object({FlowID:zod.z.string().nullish(),Identity:CR.nullish(),Availability:nc.nullish(),Policy:ic.nullish(),Steps:zod.z.record(zod.z.string(),Ra).nullish(),Reward:sc.nullish(),Presets:SR.nullish()}).passthrough(),xR=zod.z.object({BlockingFlowIDs:zod.z.array(zod.z.string()).nullish(),BlockedModules:zod.z.array(zod.z.string()).nullish(),BlockedActions:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),BlockBeforeStart:zod.z.boolean().nullish(),SkipLiftsBlock:zod.z.boolean().nullish()}).passthrough(),DR=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:xR.nullish()}).passthrough(),IR=zod.z.object({Availability:zod.z.record(zod.z.string(),nc).nullish(),Policy:zod.z.record(zod.z.string(),ic).nullish(),Reward:zod.z.record(zod.z.string(),sc).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Ra)).nullish()}).passthrough(),rc=zod.z.object({Flows:zod.z.record(zod.z.string(),bR).nullish(),Settings:DR.nullish(),Presets:IR.nullish()}).passthrough(),PR=zod.z.object({}).passthrough().transform(r=>r),oc=zod.z.object({FlowID:zod.z.string(),Status:cR,CurrentStepID:zod.z.string().nullish(),CurrentStep:Ra.nullish(),TotalSteps:zod.z.number(),CompletedSteps:zod.z.number(),CanSkip:zod.z.boolean(),RewardClaimed:zod.z.boolean(),RewardPending:zod.z.boolean(),VariantID:zod.z.string().nullish()}).passthrough(),Gi=zod.z.object({State:PR.nullish(),Flows:zod.z.array(oc).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),$t=zod.z.object({Flow:oc.nullish()}).passthrough(),ac=zod.z.object({FlowID:zod.z.string().nullish(),Granted:O.nullish()}).passthrough(),lc=zod.z.array(Oe($t)),uc=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),ft={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Ni(r){return Array.isArray(r)?r.filter(e=>e!==null).map(Ni):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,Ni(t)])):r}var _i=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),n=this.last.get(e);return n!==void 0&&t-n<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var Fi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function cc(r){return r===429||r>=500&&r<=599}function Vi(r,e=Math.random){let t=Math.min(500*Math.pow(2,r-1),4e3),n=t*.2*(e()*2-1);return Math.max(50,t+n)}function Jt(r){return new Promise(e=>setTimeout(e,r))}var pc=15e3;async function hc(r){try{let t=JSON.parse(await r.text()),n=Number(t?.RetryAfterMs);if(Number.isFinite(n)&&n>0)return n}catch{}let e=Number(r.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function dc(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function mc(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var Ca=15,fc=1e3,ji=class{constructor(e=Ca,t=()=>Date.now(),n=Jt){this.perSecond=e;this.now=t;this.wait=n;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=fc;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(fc-(e-this.starts[0])+5);}}};var vR=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function En(r){if(!r)return null;let e=vR.exec(r);if(!e)return null;let[,t,n,i]=e;if(!t||n===void 0||i===void 0)return null;let s=new mn__default.default(n),o=new mn__default.default(i),p=o.minus(mn__default.default.max(s,0));return p.lte(0)?null:{currencyID:t,required:o.toNumber(),available:s.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var AR=12e3,TR=new Set(["RelatedEntityID"]);function wR(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[n,i]of Object.entries(e))TR.has(n)||(t[n]=i);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var kR=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(ma).nullish(),TutorialProgress:zod.z.array(uc).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),Wi=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Fi;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new _i(e.throttleMs),this.pacer=new ji(e.maxRequestsPerSecond??Ca),this.clientPlatform=e.clientPlatform??Ge.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,n,i={}){let s=i.throttleKey??wR(e,t);if(!this.throttler.tryAcquire(s))return h("throttled","Throttled");if(!this.inflight.add(s))return h("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,p=JSON.stringify(t),m=i.ticket??null,g=i.silent??!1,j=i.timeoutMs??AR,ce=i.autoRetry??!0,ve=!1,me=!1,be=0;for(;;){let Ut;i.keepalive||await this.pacer.take();try{Ut=await this.doFetch(o,p,m,j,i.keepalive??!1);}catch{if(ce&&be<3){be++,await Jt(Vi(be));continue}return this.connectionFailure("Internet Connection Error",g)}let ot=Ut.status;if(ot>=200&&ot<300){let ue=!me&&this.cryptoTopUpHandler!==null,Me=await this.parseSuccess(Ut,n,g,e,ue);if(!Me.ok&&ue){let ge=En(Me.error);if(ge){if(me=!0,await this.runTopUp(ge))continue;g||this.emitter.emit("error:global",Me.error);}}return Me}if(ot===401){if(!ve&&this.sessionRefreshHandler){ve=!0;let ue=null;try{ue=await this.sessionRefreshHandler();}catch{ue=null;}if(ue){m=ue;continue}}return this.emitter.emit("auth:unauthorized",void 0),h("unauthorized","Unauthorized")}if(cc(ot)){let ue=ot===429?await hc(Ut):null;if(ue!==null&&ue>pc)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ue/1e3)} s`,g);if(ce&&be<3){be++,await Jt(ue!==null?dc(ue):ot===429?mc(be):Vi(be));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${ot})`,g)}let Kn="";try{Kn=await Ut.text();}catch{}if(ot===409&&/operation in progress/i.test(Kn)&&ce&&be<3){be++,await Jt(Vi(be));continue}return this.handleWebError(Kn,ot,g)}}finally{this.inflight.remove(s),this.lowerBusy();}}async doFetch(e,t,n,i,s=false){let o=new AbortController,p=setTimeout(()=>{o.abort();},i);try{let m={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return n&&(m.Authorization=`Bearer ${n}`),await this.fetchImpl(e,{method:"POST",body:t,headers:m,signal:o.signal,...s?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,n,i,s=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",n)}let p;try{p=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",n)}let m=kR.safeParse(p);if(!m.success)return this.globalError("Malformed response envelope",n);if(!m.data.Success){let me=m.data.Error??"Server returned Success=false",be=s&&En(me);return !n&&!be&&this.emitter.emit("error:global",me),h("server",me)}let g=m.data.StateVersions;g&&Object.keys(g).length>0&&this.emitter.emit("user:stateVersions",{epoch:m.data.StateEpoch??null,versions:g});let j=m.data.QuestProgress;j&&j.length>0&&this.emitter.emit("quest:systemProgress",j);let ce=m.data.TutorialProgress;ce&&ce.length>0&&this.emitter.emit("tutorial:systemProgress",ce);let ve=t.safeParse(m.data.Data);if(!ve.success){let me=t.safeParse(Ni(m.data.Data));me.success&&(ve=me);}if(!ve.success){let me=`Validation error (${i}): ${ve.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",me),n||this.emitter.emit("error:global",me),h("validation",me)}return B(ve.data)}handleWebError(e,t,n){let i=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),h("server","PLAY_ACCESS_REQUIRED");i=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{i=`HTTP ${t}: ${e}`;}return n||this.emitter.emit("error:global",i),h("server",i)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),h("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),h("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function qn(r){return (typeof r=="string"?r:r.toISOString()).slice(0,10)}function si(r){return `${qn(r)}T00:00:00.000Z`}function gc(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function yc(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function xa(r,e,t,n){let i={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return i;r.InventoryV2??={};let s=r.InventoryV2,o=n.toISOString(),p=new Map,m=new Map,g=new Map,j=new Map,ce=new Map,ve=new Map,me=new Map,be=new Map,Ut=e.Grant?.PremiumTiers??[],ot=Ut.length;for(let ue=0;;ue++){let Me,ge;if(ue===0)Me=e.Grant?.Standard?.Entries,ge=false;else if(ue-1<ot)Me=Ut[ue-1]?.Resources?.Entries,ge=false;else if(ue===1+ot)Me=e.Consume?.Standard?.Entries,ge=true;else break;if(Me)for(let fe of Me){if(fe.Type==null)continue;let Re=Math.max(0,fe.Amount??0);if(!(Re<=0))switch(fe.Type){case "VirtualCurrency":{if(!fe.CurrencyID)continue;let Se=ge?m:p;Se.set(fe.CurrencyID,(Se.get(fe.CurrencyID)??0)+Re);break}case "CryptoCurrency":{if(!fe.CurrencyID)continue;let Se=ge?j:g;Se.set(fe.CurrencyID,(Se.get(fe.CurrencyID)??new mn__default.default(0)).plus(Re));break}case "Item":{if(!fe.ItemID)continue;let Se=MR(t,fe.CatalogID,fe.ItemID),Te=(Se?Se.IsStackable??true:true)?ge?ve:ce:ge?be:me;Te.set(fe.ItemID,(Te.get(fe.ItemID)??0)+Re);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(i.vcChanged=p.size>0||m.size>0,i.vcChanged){s.VirtualCurrencies??={};for(let ue of new Set([...p.keys(),...m.keys()])){let Me=p.get(ue)??0,ge=m.get(ue)??0,fe=Me-ge,Re=s.VirtualCurrencies[ue];Re?(Re.Amount+=fe,Re.UpdatedAt=o,Re.Daily&&qn(Re.Daily.PeriodStartUtc)===qn(n)?(Re.Daily.Earned+=Me,Re.Daily.Spent+=ge):Re.Daily={PeriodStartUtc:si(n),Earned:Me,Spent:ge}):s.VirtualCurrencies[ue]={Amount:fe,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:si(n),Earned:Me,Spent:ge}};}}if(i.ccChanged=g.size>0||j.size>0,i.ccChanged){s.CryptoCurrencies??={};for(let ue of new Set([...g.keys(),...j.keys()])){let Me=g.get(ue)??new mn__default.default(0),ge=j.get(ue)??new mn__default.default(0),fe=Me.minus(ge),Re=s.CryptoCurrencies[ue];Re?(Re.Amount=new mn__default.default(Re.Amount).plus(fe).toString(),Re.UpdatedAt=o):s.CryptoCurrencies[ue]={Amount:fe.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(i.itemsChanged=ce.size>0||ve.size>0||me.size>0||be.size>0,i.itemsChanged){s.Items??={},s.UnstackableItems??={};let ue=s.UnstackableItems,Me=new Set([...ce.keys(),...ve.keys(),...me.keys(),...be.keys()]);for(let ge of Me){let fe=(ce.get(ge)??0)-(ve.get(ge)??0),Re=(me.get(ge)??0)-(be.get(ge)??0),Se=fe+Re,ht=s.Items[ge];ht?(fe!==0&&(ht.StackableAmount+=fe),Re!==0&&(ht.UnstackableAmount+=Re),Se!==0&&(ht.TotalAmount+=Se)):s.Items[ge]={StackableAmount:Math.max(0,fe),UnstackableAmount:Math.max(0,Re),TotalAmount:Math.max(0,Se)};}for(let[ge,fe]of be){if(fe<=0)continue;let Re=Object.values(ue).filter(Se=>Se.ItemID===ge&&Se.EquippedSlot==null&&(Se.ExpiresAt==null||new Date(Se.ExpiresAt)>n)).sort(zR).slice(0,fe).map(Se=>Se.ItemInstanceID);for(let Se of Re)delete ue[Se];}for(let[ge,fe]of me){let Re=OR(t,ge);for(let Se=0;Se<fe;Se++){let ht=F();ue[ht]={ItemInstanceID:ht,ItemID:ge,CatalogID:Re,RemainingUses:1,AcquiredAt:o};}}}r.EventToken??={};let Kn=r.EventToken;for(let ue=0;;ue++){let Me,ge;if(ue===0)Me=e.Grant?.Standard?.EventTokens,ge=false;else if(ue-1<ot)Me=Ut[ue-1]?.Resources?.EventTokens,ge=false;else if(ue===1+ot)Me=e.Consume?.Standard?.EventTokens,ge=true;else break;if(!(!Me||Me.length===0))for(let fe of Me){let Re=fe.Address;if(!Re||Re.Type==null)continue;let Se=fe.Amount??0;if(Se<=0)continue;let ht=ER(Kn,Re.Type);if(!ht)continue;let Te=ht[Re.EntityID];Te||(Te={},ht[Re.EntityID]=Te),Te.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Te.Daily??={Date:si(n),TotalEarned:0},Te.Meta??={};let Qn=fe.Source&&fe.Source.length>0?fe.Source:"CustomAction";ge?(Te.Balance.Current-=Se,Te.Balance.TotalSpent+=Se):(Te.Balance.Current+=Se,Te.Balance.TotalEarned+=Se,qn(Te.Daily.Date)!==qn(n)&&(Te.Daily={Date:si(n),TotalEarned:0}),Te.Daily.TotalEarned+=Se,Te.Daily.EarnedBySource??={},Te.Daily.EarnedBySource[Qn]=(Te.Daily.EarnedBySource[Qn]??0)+Se,Te.Daily.TriggersBySource??={},Te.Daily.TriggersBySource[Qn]=(Te.Daily.TriggersBySource[Qn]??0)+1,Te.Daily.LastTriggerBySource??={},Te.Daily.LastTriggerBySource[Qn]=o,Te.Meta.JoinedAtUtc||(Te.Meta.JoinedAtUtc=o),Te.Meta.LastEarnedAtUtc=o),i.tokensChanged=true;}}return i}function zR(r,e){return r.AcquiredAt!==e.AcquiredAt?r.AcquiredAt<e.AcquiredAt?-1:1:r.ItemInstanceID===e.ItemInstanceID?0:r.ItemInstanceID<e.ItemInstanceID?-1:1}function MR(r,e,t){let n=r?.Catalogs;if(n){if(e){let i=n[e]?.Items?.[t];if(i)return i}for(let i of Object.values(n)){let s=i.Items?.[t];if(s)return s}}}function OR(r,e){let t=r?.Catalogs;if(t){for(let[n,i]of Object.entries(t))if(i.Items&&e in i.Items)return n}}function ER(r,e){switch(e){case "TimedEvent":return r.TimedEvent??={};case "Quest":return r.Quest??={};case "Leaderboard":return r.Leaderboard??={};case "CoopEvent":return r.CoopEvent??={};case "Season":return r.Season??={};case "Challenge":return r.Challenge??={};case "ChallengePoints":return r.ChallengePoints??={};default:return null}}function Rc(r,e,t){let n={drop:[],restore:{}};if(!t)return n;let i=t.ChangedInstances??{},s=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let m of Object.values(i))m?.ItemID&&o.add(m.ItemID);for(let m of s){let g=r[m]?.ItemID;g&&o.add(g);}if(o.size===0)return n;let p=m=>s.has(m)||m in i;if(e){for(let[m,g]of Object.entries(e))m in r||p(m)||g&&o.has(g.ItemID)&&n.drop.push(m);for(let[m,g]of Object.entries(r))m in e||p(m)||g&&o.has(g.ItemID)&&(n.restore[m]=g);}return n}function Da(r,e){return r===e||r.startsWith(`${e}:`)}var Ki=class r{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let n of Object.values(t))n&&(typeof n.Amount=="number"&&(n.Amount=String(n.Amount)),typeof n.Frozen=="number"&&(n.Frozen=String(n.Frozen)));}applyUserState(e){r.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let n of t)this.currentState[n]=e[n];r.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){r.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,n=new Date){if(!this.currentState)return;let i=xa(this.currentState,e,t,n);this.emitResourceChanges(i,false);}applyResourcesWithDelta(e,t,n,i=new Date){if(!this.currentState)return;let s=this.currentState,o={...s.InventoryV2?.UnstackableItems??{}},p=xa(s,e,n,i),m=Rc(o,s.InventoryV2?.UnstackableItems,t),g=Object.entries(t?.ChangedInstances??{}),j=t?.RemovedInstanceIDs??[],ce=m.drop.length>0||Object.keys(m.restore).length>0||g.length>0||j.length>0;if(ce){s.InventoryV2??={},s.InventoryV2.UnstackableItems??={};let ve=s.InventoryV2.UnstackableItems;for(let me of m.drop)delete ve[me];for(let[me,be]of Object.entries(m.restore))ve[me]=be;for(let[me,be]of g)ve[me]=be;for(let me of j)delete ve[me];}this.emitResourceChanges(p,ce);}emitResourceChanges(e,t){let n=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),n&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(n||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,n,i){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let s=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof mn__default.default?t:new mn__default.default(t),p=i===void 0?new mn__default.default(0):i instanceof mn__default.default?i:new mn__default.default(i),m=n??new Date().toISOString(),g=s[e];g?(g.Amount=new mn__default.default(g.Amount).plus(o).toString(),p.isZero()||(g.Frozen=new mn__default.default(g.Frozen??0).plus(p).toString()),g.UpdatedAt=m):s[e]={Amount:o.toString(),Frozen:p.toString(),CreatedAt:m,UpdatedAt:m},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,n){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let i=this.currentState.Store.Purchases,s=i[e];s||(s={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},i[e]=s),s.TotalPurchases+=t,s.LastPurchasedAt=n,n>=s.DailyResetUtc?(s.DailyPurchases=t,s.DailyResetUtc=gc(n)):s.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,n){if(!e||n<=0)return;this.currentState??={};let i=this.currentState.Lootbox??={};if(i.Pity??={},t){let s=new Date().toISOString();for(let o of t)o.RuleID&&(i.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:s});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchRewardWindowState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Windows??={},this.currentState.Reward.Windows[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,n){if(!e)return;this.currentState??={},this.currentState.Quest??={};let i=this.currentState.Quest;if(t){i.Cycles??={};let s=i.Cycles[t];if(!s)return;s.Quests??={};let o=s.Quests[e]??={QuestID:e,Status:n};o.Status=n,n==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {i.PermanentQuests??={};let s=i.PermanentQuests[e]??={QuestID:e,Status:n};s.Status=n,n==="Claimed"&&(s.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let n=this.getQuestPointsProgress(e);n&&(n.Milestone??={},this.markMilestoneClaimed(n.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let n of Object.values(e)){if(!n.CycleID)continue;let i=n.InstanceKey?`${n.CycleID}:${n.InstanceKey}`:n.CycleID,s=t[i]??={};s.Balance??={Current:0,TotalEarned:0,TotalSpent:0},s.Balance.Current=n.PointsCurrent??0,s.Balance.TotalEarned=n.PointsTotalEarned??0,s.Milestone??={};for(let o of n.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(s.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let n=this.currentState.Quest.Cycles[e];n&&(n.ClaimedGroupCompletionIDs??=[],n.ClaimedGroupCompletionIDs.includes(t)||n.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let n=t.Flows[e.FlowID]??={FlowID:e.FlowID};n.Status=e.Status,n.CurrentStepID=e.CurrentStepID??null,n.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(n.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let n of e){if(!n.FlowID||!n.StepID)continue;let i=t.Flows[n.FlowID]??={FlowID:n.FlowID,Status:"InProgress"};i.Steps??={};let s=i.Steps[n.StepID]??={StepID:n.StepID};s.Progress=n.Progress,n.Completed&&(s.CompletedAtUtc??=new Date().toISOString(),i.CurrentStepID===n.StepID&&(i.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let n of e){if(!n.QuestID)continue;let i;if(!n.CycleID)t.PermanentQuests??={},i=t.PermanentQuests[n.QuestID]??={QuestID:n.QuestID,Status:n.Status};else {t.Cycles??={};let s=t.Cycles[n.CycleID];if(!s)continue;s.Quests??={},i=s.Quests[n.QuestID]??={QuestID:n.QuestID,Status:n.Status};}if(i.Status=n.Status,n.ObjectiveID){i.Objectives??={};let s=i.Objectives[n.ObjectiveID]??={ObjectiveID:n.ObjectiveID,CurrentValue:0,Completed:false};s.CurrentValue=n.NewValue??0,n.ObjectiveCompleted&&(s.Completed=true,s.CompletedAtUtc??=new Date().toISOString());}n.Status==="Completed"&&(i.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[n,i]of Object.entries(t))if(Da(n,e)&&i)return i;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,n,i){if(!(!t||!n)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[s,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((i?s!==i:!Da(s,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),n));this.patchActiveEventMilestoneClaimed(e,t,n,i),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,n,i){let s=this.activeEventsCache?.ActiveEvents;if(s)for(let o of s)o.Type!==e||o.TimedEventID!==t||i&&o.TokenEntityID&&o.TokenEntityID!==i||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),n));}markMilestoneClaimed(e,t){e.Claims??={};let n=e.Claims[t]??={};n.ClaimedAt??=new Date().toISOString(),n.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let n=this.ensureLeaderboardProgress(e);n.CurrentScore=t.CurrentScore??0,n.LastKnownRank=t.LastKnownRank??0,n.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,n.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,n.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,n,i){if(!e)return;let s=this.ensureLeaderboardProgress(e);(s.ScoreCycleVersion??0)<i&&(s.ScoreEarnedThisCycle=0,s.ClaimedMilestoneIDs=[],s.BracketID=null),s.CurrentScore=t,s.ScoreEarnedThisCycle=(s.ScoreEarnedThisCycle??0)+n,s.ScoreCycleVersion=i,s.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let n=this.ensureLeaderboardProgress(e);n.ClaimedMilestoneIDs??=[],n.ClaimedMilestoneIDs.includes(t)||n.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,n=t[e];return n||(n={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=n),n}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let n=this.ensureSeasonState(e);n.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let n=this.ensureSeasonState(e);n.ClaimedTierRewards??=[],n.ClaimedTierRewards.includes(t)||n.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,n=t[e];return n||(n={SeasonChainID:e},t[e]=n),n}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let n=this.currentState?.Character?.Characters;if(!n)return;let i=false;for(let s of Object.values(n))for(let o of Object.values(s.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,i=true);i&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySelectedCharacter(e){this.currentState??={},this.currentState.Character??={};let t=e??null;(this.currentState.Character.SelectedCharacterID??null)!==t&&(this.currentState.Character.SelectedCharacterID=t,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let n=this.currentState.Character.Characters,i=n[e];i||(i={CharacterID:e},n[e]=i),t(i),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,n){if(!e||!t)return;let i=this.currentState?.Character?.Characters?.[e];i&&(i.Equipment??={},n===null?delete i.Equipment[t]:i.Equipment[t]=n,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,n=false;for(let[i,s]of Object.entries(e.ChangedInstances??{}))t[i]=s,n=true;for(let i of e.RemovedInstanceIDs??[])i in t&&(delete t[i],n=true);n&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,n){this.currentState??={};let i=this.currentState.CoopEvent??={MyObjectIndex:-1};i.ActiveGroupID=e,i.ActiveCoopEventID=t,i.MyObjectIndex=n,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(n=>n!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(n=>n!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(n=>n!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),n=false;typeof e.FriendsCount=="number"&&(n||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(n||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(n||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),n&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let n=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let i of Object.keys(n)){let s=n[i];s&&s.BoostID===e.BoostID&&i!==e.InstanceID&&delete n[i];}n[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,n,i,s){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,p={Value:n,UpdatedAt:new Date().toISOString(),Version:i,LastWriter:"Client",ExpiresAt:s??null};if(e==="Private")o.Private??={},o.Private[t]=p;else if(e==="Public")o.Public??={},o.Public[t]=p;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let n=this.currentState.CustomData;if(e==="Private")n.Private&&delete n.Private[t];else if(e==="Public")n.Public&&delete n.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let n=this.ensureBoard();n.BuildingStates??=[];let i=n.BuildingStates.find(s=>s.SlotIndex===e);i||(i={SlotIndex:e},n.BuildingStates.push(i)),t(i),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let i=this.ensureBoard().Pending;i&&(e&&(i.RaidLayout=e),t>=0&&(i.OpenedIndices??=[],i.OpenedIndices.includes(t)||i.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let n=this.ensureBoard().Pending;!n||n.Type.toUpperCase()!=="SPECIAL"||(n.Special??={},e(n.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let i of Object.values(e.CryptoBalances??{}))i?.CurrencyID&&this.patchCryptoCurrencyDelta(i.CurrencyID,i.AmountDelta,i.UpdatedAt,i.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),n=e.PendingAdded;if(t.size>0||n){let i=this.currentState.Blockchain??={},s=i.PendingWithdrawals??[];t.size>0&&(s=s.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),n&&!s.some(o=>o.TitleTransactionID===n.TitleTransactionID)&&(s=[...s,n]),i.PendingWithdrawals=s;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var Qi=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,n]of Object.entries(e))this.sections.has(t)||this.sections.set(t,n);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let n=this.config?.[e];return n??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var $i=class{user;config;constructor(e){this.user=new Ki(e),this.config=new Qi;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function qR(r){return r}var UR=0,LR=1500,BR=3,Zi=class{constructor(e,t,n=null,i="",s="auto"){this.emitter=e;this.config=t;this.storage=n;this.titleId=i;this.loginMode=s;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return B(void 0);let n=Date.now(),i=[],s=[];for(let m of new Set(e)){let g=this.rules.get(m);if(g&&(t?.force||g.needsServer(n))){i.push(this.runRule(m,g));continue}(t?.force||!this.state.isStateFresh(m,t?.maxAgeMs))&&s.push(m);}let p=(await Promise.all([...i,s.length>0?this.queueSlice(s):Promise.resolve(B(void 0))])).find(m=>!m.ok);return p&&!p.ok?p:B(void 0)}runRule(e,t){let n=this.ruleInflight.get(e);if(n)return n;let i=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,i),i}queueSlice(e){for(let n of e)this.pending.add(n);let t=new Promise(n=>this.waiters.push(n));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},UR),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let n;this.batchRunning=new Promise(i=>n=i);try{let i=this.state?await this.state.readStateSlice(e):B(void 0),s=i.ok?B(void 0):i;for(let o of t)o(s);}finally{this.batchRunning=null,n();}}async read(e,t,n){this.register(e);let i=Ji(e,n?.args);if(this.noteUsed(e,n?.args,n?.loginParams),!n?.forceRefresh){let g=this.fresh(i,n?.maxAgeMs);if(g)return B(g.data);let j=this.loginFailures.get(i);if(j)return this.loginFailures.delete(i),j;let ce=this.inflight.get(i);if(ce)return ce}let s=this.generation.get(i)??0,o=Date.now(),m=t().then(g=>{if(!g.ok)return g;let j=Date.now();if((this.generation.get(i)??0)===s)return this.entries.set(i,{data:g.data,storedAt:j,expiresAt:Ia(e,g.data,j)}),g;let ce=this.entries.get(i);if(ce&&ce.storedAt>=o)return g;let ve=Ia(e,g.data,j);return this.entries.set(i,{data:g.data,storedAt:j,expiresAt:Math.min(ve??1/0,j+LR)}),g}).finally(()=>{this.inflight.get(i)===m&&this.inflight.delete(i);});return this.inflight.set(i,m),m}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...n})=>n))}acceptLoginViews(e){for(let t of e??[]){let n=this.loginBindings.get(t.Name);if(!n)continue;let i=t.Key?t.Key:void 0,s=Ji(n.view,i);if(!t.Success){this.loginFailures.set(s,h("server",t.Error??"View failed."));continue}let o=n.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(s),n.apply(o.data,i),this.put(n.view,o.data,i));}}noteUsed(e,t,n){if(!e.login||this.loginMode!=="auto")return;let i=e.login;this.loadUsed().then(()=>{let s=Cc({Name:i,Key:t});this.used.get(s)?.n!==this.session&&(this.used.set(s,{Name:i,Key:t??"",...n,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>BR||this.used.set(Cc(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),n=t?JSON.parse(t):null;return !n||typeof n.s!="number"||!Array.isArray(n.v)?e:{session:n.s,views:n.v.filter(i=>i&&typeof i.Name=="string"&&typeof i.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(Ji(e,t))?.data}put(e,t,n){this.register(e);let i=Ji(e,n);this.bump(i);let s=Date.now();this.entries.set(i,{data:t,storedAt:s,expiresAt:Ia(e,t,s)});}invalidate(e,t){let n=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${n}|${t}`);return}for(let i of [...this.entries.keys(),...this.inflight.keys()])(i===n||i.startsWith(`${n}|`))&&this.drop(i);this.drop(n);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,n])=>({key:t,ageMs:e-n.storedAt,expiresInMs:n.expiresAt===null?null:n.expiresAt-e}))}fresh(e,t){let n=this.entries.get(e);if(!n)return;let i=Date.now();if(!(n.expiresAt!==null&&i>=n.expiresAt)&&!(t!==void 0&&i-n.storedAt>t))return n}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let n of this.views.values())n.dependsOn?.some(i=>t.has(i))&&this.invalidate(n);}};function Ji(r,e){return e===void 0?r.key:`${r.key}|${e}`}function Cc(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function Ia(r,e,t){let n=r.expiresAt?.(e)??null,i=r.ttlMs!==void 0?t+r.ttlMs:null;return n!==null&&i!==null?Math.min(n,i):n??i}var Yi=class{constructor(e,t){this.storage=e;this.authTypeKey=`Saved_AuthType_${t}`,this.emailKey=`Saved_Auth_Email_${t}`,this.passwordKey=`Saved_Auth_Password_${t}`,this.refreshTokenKey=`Saved_Auth_RefreshToken_${t}`;}storage;authTypeKey;emailKey;passwordKey;refreshTokenKey;get lastAuthType(){let e=this.storage.getString(this.authTypeKey);return GR(e)?e:qe.None}saveAuthType(e){this.storage.setString(this.authTypeKey,e);}get savedEmail(){return this.storage.getString(this.emailKey)??""}get savedPassword(){return this.storage.getString(this.passwordKey)??""}saveEmailAndPassword(e,t){this.storage.setString(this.emailKey,e),this.storage.setString(this.passwordKey,t);}get savedRefreshToken(){return this.storage.getString(this.refreshTokenKey)??""}saveRefreshToken(e){e?this.storage.setString(this.refreshTokenKey,e):this.storage.remove(this.refreshTokenKey);}clear(){this.storage.remove(this.authTypeKey),this.storage.remove(this.emailKey),this.storage.remove(this.passwordKey),this.storage.remove(this.refreshTokenKey);}};function GR(r){return r!==null&&Object.values(qe).includes(r)}var NR=8,_R=100,FR=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,Xi=["GameLoop"];function VR(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var es=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=qe.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,n){let i=this.authContext;if(!i)return l;let s=this.baseRequest();s.UserID=i.userID,s.ClientSessionTicket=i.clientSessionTicket,s.WalletAddress=e,s.NetworkID=t,n&&(s.WalletSignature=n);let o=await this.ctx.api.authentication.linkWallet(s);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return l;let n=this.baseRequest();n.UserID=t.userID,n.ClientSessionTicket=t.clientSessionTicket,n.NetworkID=e;let i=await this.ctx.api.authentication.unlinkWallet(n);return i.ok&&i.data.PlayAccess&&this.setPlayAccess(i.data.PlayAccess),i}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.host.getDeviceID(),e.Device=this.ctx.host.getDeviceModel(),e.Platform=this.ctx.host.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(qe.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.host.getTelegramInitDataRaw();if(!e)return h("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let n=await this.ctx.api.authentication.loginWithTelegram(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(qe.Telegram)):n}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.Password=t;let i=await this.ctx.api.authentication.loginWithEmail(n);if(!i.ok)return i;this.applyAuthContext(i.data);let s=await this.fetchAndApplyClientState(qe.Email);return s.ok&&this.keepEmailCredentials(e,t),s}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.Password=t,n.DeviceID=this.ctx.host.getDeviceID(),n.Device=this.ctx.host.getDeviceModel(),n.Platform=this.ctx.host.getPlatform();let i=await this.ctx.api.authentication.registerWithEmail(n);return i.ok?(this.pendingRegistration={email:e,password:t},B({codeTtlMinutes:i.data.CodeTtlMinutes??0,resendCooldownSeconds:i.data.ResendCooldownSeconds??0})):i}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.VerificationCode=t;let i=await this.ctx.api.authentication.confirmEmailRegistration(n);if(!i.ok)return i;this.applyAuthContext(i.data);let s=await this.fetchAndApplyClientState(qe.Email);return s.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,s}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let n=await this.ctx.api.authentication.resendVerificationCode(t);return n.ok?B(void 0):n}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let n=await this.ctx.api.authentication.loginWithGoogle(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(qe.Google)):n}async loginWithApple(e,t){if(!e?.trim())return h("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.AppleIDToken=e,t?.nonce&&(n.AuthNonce=t.nonce),t?.name?.trim()&&(n.Username=t.name.trim());let i=await this.ctx.api.authentication.loginWithApple(n);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(qe.Apple)):i}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.WalletAddress=e,n.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(n)}async loginWithWallet(e,t,n){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.WalletAddress=e,i.NetworkID=t,i.WalletSignature=n,i.Platform=this.ctx.host.getPlatform(),i.Device=this.ctx.host.getDeviceModel(),i.DeviceID=this.ctx.host.getDeviceID();let s=await this.ctx.api.authentication.loginWithWallet(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(qe.Wallet)):s}async loginWithSsoCode(e){if(!e)return h("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.host.getDeviceID(),t.Device=this.ctx.host.getDeviceModel(),t.Platform=this.ctx.host.getPlatform();let n=await this.ctx.api.authentication.loginWithSsoCode(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(qe.iDosGames)):n}async loginWithPlatformGameTicket(e){if(!e)return h("client","Platform game ticket is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.PlatformGameTicket=e;let n=await this.ctx.userService.prepareLoginClientState(Xi,Xi);t.ClientState=n.request;let i=await this.ctx.api.authentication.resolvePlatformGameSession(t);if(!i.ok)return i;this.applyAuthContext(i.data),this.platformGameSession=true;let s=i.data.ClientState;return this.fetchAndApplyClientState(qe.iDosGames,s?()=>n.finish(s):void 0)}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,n){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.Email=e,i.ResetToken=t,i.Password=n,this.ctx.api.authentication.resetPassword(i)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==qe.None?e:qe.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let n=this.baseRequest();n.RefreshToken=t,e?.appOpened&&(n.AppOpened=true);let i=await this.ctx.api.authentication.refreshSession(n);return i.ok?(this.applyRefresh(i.data),"ok"):(VR(i.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,n){switch(e){case qe.Email:return this.loginWithEmail(t,n);case qe.Device:case qe.None:return this.loginWithDeviceID();case qe.Telegram:return this.loginWithTelegram();default:return Promise.resolve(h("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;if(this.platformGameSession){this.refreshing=true;try{let t=await this.ctx.host.signIn(this.ctx.settings.titleID);if(!t.ticket)return null;let n=this.baseRequest();n.PlatformGameTicket=t.ticket;let i=await this.ctx.api.authentication.resolvePlatformGameSession(n);return i.ok?(this.applyAuthContext(i.data),this.platformGameSession=!0,i.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==qe.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===qe.None)return null;this.refreshing=true;try{return (await this.replay(e,this.sessionEmail||this.ctx.authStore.savedEmail,this.sessionPassword||this.ctx.authStore.savedPassword)).ok&&this.authContext?this.authContext.clientSessionTicket:null}catch{return null}finally{this.refreshing=false;}}logout(){this.authContext=null,this.playAccessStatus=null,this.forgetSession(),this.ctx.authStore.clear(),this.ctx.data.reset(),this.ctx.emitter.emit("auth:loggedOut",void 0);}static isValidEmail(e){return e.length>0&&FR.test(e)}static isValidPasswordLength(e){return e.length>=NR&&e.length<=_R}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=qe.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e,t){let n=t?await t():await this.ctx.userService.getClientStateExcept(Xi,Xi);return n.ok&&(this.sessionAuthType=e,this.rememberSession?(this.ctx.authStore.saveAuthType(e),this.ctx.authStore.saveRefreshToken(this.sessionRefreshToken)):this.ctx.authStore.clear(),this.ctx.emitter.emit("auth:loggedIn",void 0)),n}};var jR="idos:cfg",Un=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Sc(t)}`:e&&e.length>0?`f:${Sc(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.v!="string"||!n.c?null:n}catch{return null}}async write(e,t,n){try{let i={v:t,c:n};await this.storage.set(this.keyOf(e),JSON.stringify(i));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${jR}:${this.titleId}:${e}`}};function Sc(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var bc="idos:loc",Ln=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.v!="number"||!n.t||typeof n.t!="object"?null:n}catch{return null}}async write(e,t,n){try{let i={v:t,t:n};await this.storage.set(this.keyOf(e),JSON.stringify(i)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let n={};for(let[i,s]of Object.entries(t))typeof s=="number"&&s>0&&(n[i]=s);return n}catch{return {}}}async noteVersion(e,t){let n=await this.readVersions();n[e]!==t&&(n[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(n)));}keyOf(e){return `${bc}:${this.titleId}:${e}`}versionsKey(){return `${bc}:${this.titleId}:versions`}};var WR="idos:sec",ts=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let n=JSON.parse(t);return !n||typeof n!="object"||n.v!==e||!n.s||typeof n.s!="object"?{}:n.s}catch{return {}}}async write(e,t){try{let n={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(n));}catch{}}keyOf(){return `${WR}:${this.titleId}`}};var HR="idos:state",ns=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.e!="string"||!n.v||!n.s?null:n}catch{return null}}async write(e,t,n,i){if(!(!e||!t))try{let s={e:t,v:n,s:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}keyOf(e){return `${HR}:${this.titleId}:${e}`}};function KR(r,e){if(!r)return;let t=new Set((e??[]).map(i=>i.trim().toLowerCase()));if(t.size===0)return r;let n={};for(let[i,s]of Object.entries(r))t.has(i.toLowerCase())||(n[i]=s);return n}function Pa(r,e,t,n){let i={...r??{}};if(!e||!t||!n)return i;for(let[s,o]of Object.entries(t))n[s]===o&&s in e&&(i[s]=e[s]);return i}function QR(r){return {...r??{}}}function va(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.StateEpoch:null}var is=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,n=Date.now()){if(this.versions[e]===void 0)return false;let i=this.confirmedAt[e];return i===void 0?false:t===void 0||n-i<=t}forget(e){let t=[];for(let n of e)this.versions[n]!==void 0&&(delete this.versions[n],delete this.confirmedAt[n],t.push(n));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=KR(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let o=Object.keys(this.versions);this.reset(e),this.notify(o);}return []}let n=Date.now(),i=[],s=[];for(let[o,p]of Object.entries(t)){let m=this.versions[o];m!==p&&(m!==void 0&&p===m+1?(this.versions[o]=p,this.confirmedAt[o]=n):(delete this.versions[o],delete this.confirmedAt[o],m!==void 0&&p>m+1&&s.push(o)),i.push(o),this.dirty=true);}return this.notify(i),s}afterFullRead(e,t){let n=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=QR(t);let i=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=i;this.dirty=true;let s=new Set;for(let o of new Set([...Object.keys(n),...Object.keys(this.versions)]))n[o]!==this.versions[o]&&s.add(o);this.notify([...s]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let n=Date.now(),i=[];for(let[s,o]of Object.entries(t??{}))this.versions[s]!==o&&i.push(s),this.versions[s]=o,this.confirmedAt[s]=n;this.dirty=true,this.notify(i);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var xc=h("server","Title configuration is unavailable (CDN and API both failed)."),ss=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:F()}:null}get configCache(){return this.cache??=new Un(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new Ln(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new ts(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new is(new ns(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){if(!this.ctx.auth.context?.userID||!this.stateStore.currentEpoch)return;let i=this.stateStore.noteMutation(e,t);i.length>0&&(this.ctx.cache.ensureState(i),this.ctx.emitter.emit("user:changedElsewhere",{containers:i}));}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return l;let t=Un.scopeOf(e.TitleFields,null),n=await this.configCache.read(t);n&&(e.KnownTitleConfigVersion=n.v),await this.prepareLocalization(e);let i=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let s=await this.ctx.api.user.getClientState(e);if(!s.ok)return s;let o=await this.resolveTitleConfig(s.data,t,n,{Fields:e.TitleFields});return o==null?xc:(this.finishStateHandshake(s.data,i),await this.restoreSections(s.data.TitleConfigVersion,o),await this.applyClientState(s.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(s.data.Views),await this.applyLocalization(s.data.Localization),await this.flushState(i),s)}async prepareStateHandshake(e,t){let n=this.ctx.auth.context?.userID;if(!n)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(n),await this.stateStore.flush(n,this.ctx.data.user.state);let i=this.stateStore.versionsFor(t);if(i){e.KnownStateVersions=i;let s=this.stateStore.currentEpoch;s&&(e.KnownStateEpoch=s);}return {userId:n,cached:this.stateStore.cachedState,sent:i}}finishStateHandshake(e,t){let n=Pa(e.User,t.cached,t.sent,e.StateVersions);e.User=n;let i=va(e);!i||!t.userId||this.stateStore.afterFullRead(i,e.StateVersions);}async resolveTitleConfig(e,t,n,i){let s=e.TitleConfigVersion;if(n&&s&&n.v===s)return n.c;if(e.TitleConfigUrl){let p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return s&&await this.configCache.write(t,s,p),p}let o=await this.fetchConfigFromApi(i);return o!=null?(s&&await this.configCache.write(t,s,o),o):n?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let n=await t.json();return n&&typeof n=="object"?n:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let n={...t,...e},i=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(n):await this.ctx.api.title.getTitlePublicConfiguration(n);return i.ok?i.data:null}async getClientStateExcept(e,t){let n=this.baseRequest();if(!n)return l;let i=await this.prepareClientStateExcept(n,e,t,true),s=await this.ctx.api.user.getClientStateExcept(n);return s.ok?this.finishClientStateExcept(i,s.data):s}async prepareLoginClientState(e,t){let n={BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:F()},i=await this.prepareClientStateExcept(n,e,t,false);return {request:n,finish:async s=>{let o=this.ctx.auth.context?.userID??null;return o&&await this.stateStore.load(o),i.handshake={userId:o,cached:null,sent:void 0},this.finishClientStateExcept(i,s)}}}async prepareClientStateExcept(e,t,n,i){e.ExcludeFields=t,e.ExcludeTitleFields=n;let s=Un.scopeOf(null,n??[]),o=await this.configCache.read(s);o&&(e.KnownTitleConfigVersion=o.v),await this.prepareLocalization(e);let p=i?await this.prepareStateHandshake(e,t??null):{userId:null,cached:null,sent:void 0};return await this.prepareLoginViews(e),{scope:s,cached:o,handshake:p,excludeFields:t,excludeTitleFields:n}}async finishClientStateExcept(e,t){let n=await this.resolveTitleConfig(t,e.scope,e.cached,{ExcludeFields:e.excludeTitleFields??[]});return n==null?xc:(this.finishStateHandshake(t,e.handshake),await this.restoreSections(t.TitleConfigVersion,n),await this.applyClientState(t,n,e.excludeFields,e.excludeTitleFields),this.ctx.cache.acceptLoginViews(t.Views),await this.applyLocalization(t.Localization),await this.flushState(e.handshake),B(t))}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let n=t,i={};for(let[s,o]of Object.entries(await this.sectionCache.read(e)))n[s]==null&&(i[s]=o);this.ctx.data.config.restoreSections(i),this.ctx.data.config.setSectionSink((s,o)=>{n[s]!=null||o==null||(i[s]=o,this.sectionCache.write(e,i));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let n=await this.localizationCache.readVersions();Object.keys(n).length>0&&(e.KnownLocalizationVersions=n);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),n=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:n});}async resolveLocalizationTable(e){let t=e.Locale??null,n=e.Version??0;if(!t)return null;let i=await this.localizationCache.read(t);if(n<=0)return i?.t??null;if(i&&i.v===n)return i.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,n,o),o}let s=await this.fetchLocalizationFromApi(t,i?.v??0);return s??i?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let n=await t.json();return n&&typeof n=="object"?n:null}catch{return null}}async fetchLocalizationFromApi(e,t){let n=this.baseRequest();if(!n)return null;let i=await this.ctx.api.localization.getLocalizationTable({...n,Locale:e,KnownVersion:t});if(!i.ok)return null;let s=i.data;if(s.NotModified)return null;let o=s.Entries??{},p=s.Version??0,m=s.Locale??e;return p>0&&await this.localizationCache.write(m,p,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):l}async getUserState(e){let t=this.baseRequest();if(!t)return l;e&&e.length>0&&(t.Fields=e);let n=await this.prepareStateHandshake(t,null),i=await this.ctx.api.user.getUserState(t);if(!i.ok)return i;let s=Pa(i.data.User,n.cached,n.sent,i.data.StateVersions);i.data.User=s;let o=n.sent??{},p=Object.entries(i.data.StateVersions??{}).filter(([g,j])=>o[g]!==j||this.ctx.data.user.state?.[g]===void 0).map(([g])=>g);this.ctx.data.user.applyUserStateContainers(s,p);let m=va(i.data);return m&&(this.stateStore.afterSliceRead(m,i.data.StateVersions),await this.flushState(n)),i}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,n){let i=this.baseRequest();if(!i)return l;i.UsageTime=e,i.IsNewSession=t,i.SessionDurationSeconds=n;let s=await this.ctx.api.user.addUsageTime(i);return s.ok&&this.ctx.emitter.emit("user:usageTimeAdded",s.data),s}async deleteUserAccount(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return l;t.Username=e;let n=await this.ctx.api.user.changeUsername(t);return n.ok&&this.ctx.emitter.emit("user:usernameChanged",n.data),n}async applyClientState(e,t,n,i){let s=n?.includes("GameLoop")===true,o=i?.includes("GameLoop")===true,p=s?this.ctx.data.user.state?.GameLoop:void 0,m=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let g=this.ctx.data.user.state;s&&g&&g.GameLoop==null&&(g.GameLoop=p);let j=this.ctx.data.config.titlePublicConfiguration;o&&j&&j.GameLoop==null&&(j.GameLoop=m),this.ctx.emitter.emit("user:clientStateReceived",e);}};var os=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return h("client","SpendID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${F()}`},i=await this.ctx.api.currency.spend(n);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",i.data)),i}async convert(e,t,n,i,s,o){if(!t)return h("client","SourceID is required.");if(!i)return h("client","TargetID is required.");if(s<=0)return h("client","Amount must be positive.");if(e===n&&t===i)return h("client","Source and target must differ.");if(e===xt.Crypto||n===xt.Crypto)return h("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return l;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:n,TargetID:i,SourceAmount:String(Math.trunc(s)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${n}_${i}_${F()}`},m=await this.ctx.api.currency.convert(p);if(m.ok){let g=m.data,j={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:g.SourceID,Amount:g.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:g.TargetID,Amount:g.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(j,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",g);}return m}async cryptoConvert(e,t,n,i,s,o){let p=s instanceof mn__default.default?s:new mn__default.default(s);if(!t)return h("client","SourceID is required.");if(!i)return h("client","TargetID is required.");if(p.lte(0))return h("client","SourceAmount must be a positive decimal.");if(e===n&&t===i)return h("client","Source and target must differ.");if(e===xt.Virtual&&n===xt.Virtual)return h("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===xt.Virtual&&!p.isInteger())return h("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return l;let m={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:n,TargetID:i,SourceAmount:p.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${n}_${i}_${F()}`},g=await this.ctx.api.currency.cryptoConvert(m);if(g.ok){let j=g.data,ce=[],ve=[];if(j.SourceType===xt.Virtual&&ce.push({Type:"VirtualCurrency",CurrencyID:j.SourceID,Amount:Math.trunc(Number(j.SourceSpent))}),j.TargetType===xt.Virtual&&ve.push({Type:"VirtualCurrency",CurrencyID:j.TargetID,Amount:Math.trunc(Number(j.TargetCredited))}),ce.length>0||ve.length>0){let me={Consume:ce.length>0?{Standard:{Entries:ce}}:null,Grant:ve.length>0?{Standard:{Entries:ve}}:null};this.ctx.data.user.applyResourceOperation(me,this.ctx.data.config.itemDefinitions);}j.SourceType===xt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.SourceID,new mn__default.default(j.SourceSpent).negated(),j.ServerTimeUtc),j.TargetType===xt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.TargetID,new mn__default.default(j.TargetCredited),j.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",j);}return g}};var as=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,n,i){let s=e.trim();if(!s)return h("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:n,CreditsConfirmationID:i,RelatedEntityID:`upgrade_item_${s}_${F()}`};t&&t.length>0&&(o.FodderInstanceIDs=[...t]);let p=await this.ctx.api.item.upgradeLevel(o);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(p.data.ItemInstanceID??s,p.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",p.data)),p}async upgradeLevelsBatch(e){if(!e||e.length===0)return h("client","upgrades is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},n=await this.ctx.api.item.upgradeLevelsBatch(t);if(n.ok){for(let i of n.data)i.Success&&i.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(i.Data.ItemInstanceID,i.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",n.data);}return n}};var ls=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:Gt.nullish(),AllowedPlatforms:zod.z.array(Ti).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),de=zod.z.record(zod.z.string(),ls),$R=zod.z.object({Store:wi,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var ri={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},ye=zod.z.object({ConfirmationID:zod.z.string(),Url:zod.z.string(),Status:zod.z.string(),PriceCredits:zod.z.number(),ExpiresAt:u}).passthrough(),Dc=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),JR={LoginRequired:"CREDITS_LOGIN_REQUIRED",NotEnough:"NOT_ENOUGH_CREDITS",SellerUnknown:"CREDITS_SELLER_UNKNOWN",PriceChanged:"CREDITS_PRICE_CHANGED",ConfirmationPending:"CREDITS_CONFIRMATION_PENDING",ConfirmationDeclined:"CREDITS_CONFIRMATION_DECLINED",ConfirmationExpired:"CREDITS_CONFIRMATION_EXPIRED",ConfirmationNotFound:"CREDITS_CONFIRMATION_NOT_FOUND",ConfirmationMismatch:"CREDITS_CONFIRMATION_MISMATCH",BatchForbidden:"CREDITS_BATCH_FORBIDDEN",NotAllowedHere:"CREDITS_NOT_ALLOWED_HERE",MixedWithStorePayment:"CREDITS_MIXED_WITH_STORE_PAYMENT",SellerNotReady:"CREDITS_SELLER_NOT_READY",ConfirmationInUse:"CREDITS_CONFIRMATION_IN_USE"},Aa=zod.z.object({ServerTimeUtc:u,OfferID:zod.z.string(),Count:zod.z.number(),Resources:O.nullish(),Inventory:K.nullish(),CreditsConfirmation:ye.nullish()}),Ic=zod.z.array(Oe(Aa)),ZR=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:u,LastPurchasedAt:u}),YR=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:u}),Pc=zod.z.object({Purchases:zod.z.record(zod.z.string(),ZR).nullish(),Rotations:zod.z.record(zod.z.string(),YR).nullish()}).passthrough().transform(r=>r),_t=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),us=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),XR={Fixed:"Fixed",Title:"Title",Player:"Player"},eC=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:ee.nullish()}).passthrough(),vc=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(eC).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),tC=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Rotation:J.nullish()}).passthrough(),nC=zod.z.object({SlotID:zod.z.string().nullish(),Identity:_t.nullish(),Availability:us.nullish(),Rotation:vc.nullish(),Presets:tC.nullish()}).passthrough(),iC=zod.z.object({Identity:J.nullish(),Availability:J.nullish()}).passthrough(),sC=zod.z.object({SectionID:zod.z.string().nullish(),Identity:_t.nullish(),Availability:us.nullish(),Slots:zod.z.record(zod.z.string(),nC).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:iC.nullish()}).passthrough(),Ac=zod.z.object({Sections:zod.z.record(zod.z.string(),sC).nullish()}).passthrough(),rC=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Layout:J.nullish()}).passthrough(),oC=zod.z.object({StoreID:zod.z.string().nullish(),Identity:_t.nullish(),Availability:us.nullish(),Layout:Ac.nullish(),Presets:rC.nullish()}).passthrough(),Tc=zod.z.object({Options:de.nullish(),CompareAt:zod.z.record(zod.z.string(),Gt).nullish()}).passthrough(),wc=zod.z.object({Grant:$.nullish()}).passthrough(),kc=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),aC=zod.z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish(),Availability:J.nullish()}).passthrough(),lC=zod.z.object({OfferID:zod.z.string().nullish(),Identity:_t.nullish(),Pricing:Tc.nullish(),Reward:wc.nullish(),Availability:kc.nullish(),Presets:aC.nullish()}).passthrough(),uC=zod.z.object({Identity:zod.z.record(zod.z.string(),_t).nullish(),Availability:zod.z.record(zod.z.string(),us).nullish(),Layout:zod.z.record(zod.z.string(),Ac).nullish(),Rotation:zod.z.record(zod.z.string(),vc).nullish(),Pricing:zod.z.record(zod.z.string(),Tc).nullish(),Reward:zod.z.record(zod.z.string(),wc).nullish(),OfferAvailability:zod.z.record(zod.z.string(),kc).nullish()}).passthrough(),cs=zod.z.object({Stores:zod.z.record(zod.z.string(),oC).nullish(),StoreOffers:zod.z.record(zod.z.string(),lC).nullish(),Presets:uC.nullish()}).passthrough(),cC=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:u.nullish()}).passthrough(),pC=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:Gt.nullish(),CompareAtCost:Gt.nullish(),DiscountPercent:zod.z.number().nullish(),IsFree:zod.z.boolean(),IsAdPaid:zod.z.boolean(),IsStorePaid:zod.z.boolean(),IsCreditsPaid:zod.z.boolean().nullish(),CreditsPrice:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),hC=zod.z.object({OfferID:zod.z.string(),Identity:_t.nullish(),PriceOptions:zod.z.array(pC).nullish(),Rewards:$.nullish(),State:cC.nullish()}).passthrough(),dC=zod.z.object({SlotID:zod.z.string(),Identity:_t.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:u.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:hC.nullish()}).passthrough(),mC=zod.z.object({SectionID:zod.z.string(),Identity:_t.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(dC).nullish()}).passthrough(),fC=zod.z.object({StoreID:zod.z.string(),Identity:_t.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:u.nullish(),Sections:zod.z.array(mC).nullish()}).passthrough(),ps=zod.z.object({ServerTimeUtc:u,Stores:zod.z.array(fC).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Ft={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},gC="OFFER_NOT_IN_ROTATION";var zc="Store",Mc={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=null;for(let t of r.Stores??[])for(let n of t.Sections??[])for(let i of n.Slots??[]){let s=Date.parse(i.RefreshesAtUtc??"");!Number.isNaN(s)&&(e===null||s<e)&&(e=s);}return e}},hs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Mc,{schema:ps,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,n){if(!e)return h("client","OfferID is required.");if(t<1)return h("client","Count must be at least 1.");let i=this.ctx.auth.context;if(!i)return l;let s={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,StoreID:n?.slot?.storeID,SectionID:n?.slot?.sectionID,SlotID:n?.slot?.slotID,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${i.userID}_${F()}`},o=await this.ctx.api.store.purchase(s);if(o.ok&&!o.data.CreditsConfirmation){let p=o.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return o}async purchaseWithCredits(e,t=1,n={}){return await this.ctx.credits.pay(i=>this.purchase(e,t,{selectedOptionID:n.selectedOptionID,slot:n.slot,creditsConfirmationID:i}),{onConfirmation:n.onConfirmation,signal:n.signal,pollMs:n.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):l}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):l}async purchaseBatch(e){if(!e||e.length===0)return h("client","purchases is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},n=await this.ctx.api.store.purchaseBatch(t);if(n.ok){let i=false;for(let s of n.data)!s.Success||!s.Data||!s.Data.OfferID||(this.ctx.data.user.patchStorePurchase(s.Data.OfferID,s.Data.Count,s.Data.ServerTimeUtc),!i&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true));this.ctx.emitter.emit("store:offersPurchasedBatch",n.data);}return n}async getDefinitions(e){let t=this.ctx.cache.configSection(zc,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.store.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(zc,i.data),this.ctx.emitter.emit("store:definitionsLoaded",i.data)),i}getStorefront(e){return this.ctx.cache.read(Mc,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let n of t.Sections??[])for(let i of n.Slots??[]){let s=i.RefreshesAtUtc;s&&(e===null||Date.parse(s)<Date.parse(e))&&(e=s);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var ds=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let n=await e(void 0);if(!n.ok||!n.data.CreditsConfirmation)return n;let i=n.data.CreditsConfirmation,s=()=>e(i.ConfirmationID);if(this.ctx.host.supports.creditsConfirm){let m=await this.ctx.host.confirmCredits({titleID:this.ctx.settings.titleID,confirmationID:i.ConfirmationID});if(m.ok)return await s();if(m.error==="DECLINED")return h("server","CREDITS_CONFIRMATION_DECLINED");if(m.error==="NOT_ENOUGH_CREDITS")return h("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(i);let o=Math.max(1e3,t.pollMs??2500),p=Date.parse(i.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return h("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>p)return h("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(j=>setTimeout(j,o));let m=await this.ctx.store.getCreditsConfirmation(i.ConfirmationID);if(!m.ok)continue;let g=m.data.Status;if(g!==ri.Pending)return g===ri.Declined?h("server","CREDITS_CONFIRMATION_DECLINED"):g===ri.Expired?h("server","CREDITS_CONFIRMATION_EXPIRED"):await s()}}};var ms=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return l;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return l;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?B(t.data.Purchase??{}):t}async validatePurchase(e,t,n){if(!t)return h("client","Receipt is required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:n?.signature,ProductID:n?.productID,TransactionID:n?.transactionID},s=await this.ctx.api.purchase.validatePurchase(i);return s.ok&&this.applyValidation(s.data),s}async buyWithTelegramStars(e,t){if(!e)return h("client","productID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),ProductID:e},i=await this.ctx.api.purchase.createTelegramInvoice(n);return i.ok&&t?.open!==false&&this.ctx.host.openInvoice(i.data.InvoiceLink),i}async buy(e){if(!e)return h("client","productID is required.");if(!this.ctx.host.supports.storePurchases)return h("client","UNAVAILABLE");if(!this.ctx.auth.context)return l;let t=await this.getDefinitions();if(!t.ok)return t;let n=t.data.Purchase?.Products?.[e],i=this.hostStore(),s=n?.StoreProductIDs?.[i];if(!n||n.Enabled===false||!s)return h("client","NOT_SOLD");let o=this.ctx.buildAuthedBaseRequest(),p=await this.ctx.host.buyProduct({storeProductID:s,type:n.Type??"Consumable",accountID:o.UserID??void 0});return !p.ok||!p.receipt?h("client",p.error??"FAILED"):this.deliver(p.receipt,n)}async restorePending(){if(!this.ctx.host.supports.storePurchases||!this.ctx.auth.context)return 0;let e=await this.ctx.host.pendingPurchases();if(e.length===0)return 0;let t=await this.getDefinitions(),n=t.ok?Object.values(t.data.Purchase?.Products??{}):[],i=0;for(let s of e){let o=n.find(p=>s.storeProductID&&p.StoreProductIDs?.[s.store]===s.storeProductID);(await this.deliver(s,o)).ok&&i++;}return i}async deliver(e,t){let n=await this.validatePurchase(e.store,e.receipt,{signature:e.signature});return n.ok&&await this.ctx.host.finishPurchase(e,(t?.Type??"Consumable")==="Consumable"),n}hostStore(){return this.ctx.host.getClientPlatform()===Ge.Ios?"AppleAppStore":"GooglePlay"}async validatePurchasesBatch(e){if(!e||e.length===0)return h("client","receipts is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},n=await this.ctx.api.purchase.validatePurchasesBatch(t);if(n.ok)for(let i of n.data.Items)i.Success&&i.Data&&this.applyValidation(i.Data);return n}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Oc=3,yC=700,fs=class{constructor(e){this.ctx=e;e.host.supports.cryptoTopUp&&this.setTopUpHandler(this.hostTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return En(e)}hostTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let n=await this.ctx.host.topUp({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return n.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:n.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=Oc;t++){let n=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(n.ok)return;if(n.reason!=="throttled"||t===Oc)break;await Jt(yC);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,n])=>({...n,OptionID:n.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,n)=>(t.OptionID??"").localeCompare(n.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let n of t)if(n?.Type===Ai.Purchase&&n.ProductID)return n.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let n of t){if(n?.Type!==Ai.CryptoCurrency||!n.CurrencyID)continue;let i=Number(n.Amount??0);if(!(i>0))continue;let s=this.cryptoBalance(n.CurrencyID);return s>=i?null:{currencyID:n.CurrencyID,required:i,available:s,missing:i-s}}return null}cryptoBalance(e){let n=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(n?.Amount??0)}};var Ec="Lootbox",gs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ec,e);if(t){let s={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),B(s)}let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.lootbox.getDefinitions(n);if(i.ok){let s=i.data.LootboxDefinitions;s&&(this.ctx.data.config.patchSection(Ec,s),this.ctx.emitter.emit("lootbox:definitionsLoaded",s));}return i}async open(e,t,n,i,s){if(!e)return h("client","LootboxID is required.");if(t<1)return h("client","Count must be at least 1.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:n,Payment:i,CreditsConfirmationID:s,RelatedEntityID:`lootbox_${e}_${n??"default"}_${F()}`},p=await this.ctx.api.lootbox.open(o);if(p.ok&&!p.data.CreditsConfirmation){let m=p.data;m.TriggeredPity&&m.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,m.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(m.Resources,m.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",m);}return p}};var Ta="Reward";function ys(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Rs=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Reward",{needsServer:()=>!t&&Object.values(e.cache.configSection(Ta)?.Comebacks??{}).some(n=>n?.TrackPresenceOnRead===true),refresh:async()=>{let n=await this.getUserRewardsState();return n.ok&&(t=true),n}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(Ta,e);if(t){let s={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),B(s)}let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.reward.getRewardDefinitions(n);if(i.ok){let s=i.data.RewardDefinitions;s&&(this.ctx.data.config.patchSection(Ta,s),this.ctx.emitter.emit("reward:definitionsLoaded",s));}return i}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let n=t.data;this.multiplierEnabled=n.Enabled,this.multiplier=n.Enabled?n.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",n);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${F()}`},i=await this.ctx.api.reward.claimDailyReward(n);if(i.ok){let s=i.data;this.ctx.data.user.patchDailyCalendarState(s.CalendarID,s.DailyState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",s);}return i}async collectIdleAccrual(e){if(!ys(e))return h("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${F()}`},n=await this.ctx.api.reward.collectIdleAccrual(t);if(n.ok){let i=n.data;this.ctx.data.user.patchIdleAccrualState(i.AccrualID,i.IdleState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",i);}return n}async claimComebackReward(e){if(!ys(e))return h("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${F()}`},n=await this.ctx.api.reward.claimComebackReward(t);if(n.ok){let i=n.data;this.ctx.data.user.patchComebackState(i.ComebackID,i.ComebackState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",i);}return n}async claimReward(e){if(!ys(e))return h("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${F()}`},n=await this.ctx.api.reward.claimReward(t);if(n.ok){let i=n.data;this.ctx.data.user.patchClaimRewardState(i.ClaimID,i.ClaimState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",i);}return n}async claimRewardWindow(e,t,n={}){if(!ys(e))return h("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return h("client","Amount must be a positive number.");let i=n.boost??"None";if(i==="Ad"&&!n.adRequestID)return h("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:i,...n.adRequestID?{AdRequestID:n.adRequestID}:{},RelatedEntityID:n.roundID??`reward_window_${e}_${F()}`},o=await this.ctx.api.reward.claimRewardWindow(s);if(o.ok){let p=o.data;this.ctx.data.user.patchRewardWindowState(p.WindowID,p.WindowState),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:windowClaimed",p);}return o}};var Cs="Tutorial",qc={key:"tutorial.state",login:"TutorialState",ttlMs:5*6e4,dependsOn:["Tutorial"],invalidateOn:["tutorial:flowStarted","tutorial:flowSkipped","tutorial:flowReset","tutorial:stepChanged","tutorial:stepsCompletedBatch","tutorial:rewardClaimed","tutorial:systemProgress"]},Ss=class{constructor(e){this.ctx=e;e.cache.bindLoginView(qc,{schema:Gi,apply:n=>this.applyUserTutorialState(n)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(Cs)?.Flows??{}).length>0,refresh:async()=>{let n=await this.getUserTutorialState();return n.ok&&(t=true),n}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(Cs,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.tutorial.getTutorialDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Cs,i.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",i.data)),i}getUserTutorialState(e=true,t){return this.ctx.cache.read(qc,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return l;t.AutoStart=e;let n=await this.ctx.api.tutorial.getUserTutorialState(t);return n.ok&&this.applyUserTutorialState(n.data),n}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.reportStepShown(n))}async completeStep(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.completeStep(n),{relatedEntityID:`tutorial_step_${e}_${t}_${F()}`})}async completeStepsBatch(e,t){let n=e?.trim();if(!n)return h("client","FlowID is required.");if(!t||t.length===0)return h("client","stepIDs is required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepIDs:t,RelatedEntityID:`tutorial_batch_${n}_${F()}`},s=await this.ctx.api.tutorial.completeStepsBatch(i);return s.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",s.data)),s}async skipStep(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.skipStep(n))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return h("client","FlowID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${F()}`},i=await this.ctx.api.tutorial.claimFlowReward(n);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",i.data)),i}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,n){let i=e?.trim();if(!i)return h("client","FlowID is required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i},o=await t(s);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(n.event,o.data)),o}async stepCall(e,t,n,i){let s=e?.trim(),o=t?.trim();if(!s)return h("client","FlowID is required.");if(!o)return h("client","StepID is required.");if(!this.ctx.auth.context)return l;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:s,StepID:o};i?.relatedEntityID&&(p.RelatedEntityID=i.relatedEntityID);let m=this.ctx.data.user.state?.Tutorial?.Flows?.[s]?.RewardClaimed===true,g=await n(p);return g.ok&&(this.applyFlowView(g.data),this.mayHavePaid(s,o,m,g.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",g.data)),g}mayHavePaid(e,t,n,i){return !n&&i.Flow?.RewardClaimed===true?true:i.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Cs)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}};var bs=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return l;e>0&&(t.Limit=e);let n=await this.ctx.api.communityMarketing.getEarnings(t);return n.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",n.data),n}async claim(e){if(!e)return h("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.CampaignID=e;let n=await this.ctx.api.communityMarketing.claim(t);return n.ok&&this.ctx.emitter.emit("communityMarketing:claimed",n.data),n}async withdrawCryptoReward(e,t,n){if(!e)return h("client","campaignID is required.");if(!t)return h("client","walletAddress is required.");let i=this.ctx.authedRequest();if(!i)return l;i.CampaignID=e,i.WalletAddress=t,n&&(i.Amount=n);let s=await this.ctx.api.communityMarketing.withdrawCryptoReward(i);return s.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",s.data),s}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Ne=zod.z.object({Username:zod.z.string().nullish(),Country:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Premium:zod.z.boolean().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BoardRank:zod.z.number().nullish()}).passthrough();var RC={Global:"Global",Announcement:"Announcement",Group:"Group"},Lc=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),CC={None:"None",Language:"Language",Region:"Region"},SC=zod.z.enum(["None","Language","Region"]).catch("None"),bC={Anyone:"Anyone",Friends:"Friends"},xC=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),DC={Reject:"Reject",Mask:"Mask"},IC=zod.z.enum(["Reject","Mask"]).catch("Reject"),PC={Player:"Player",Publisher:"Publisher",System:"System"},vC=zod.z.enum(["Player","Publisher","System"]).catch("Player"),AC={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var TC=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),Bc=zod.z.object({Gate:ee.nullish(),Schedule:Ce.nullish()}).passthrough(),Gc=zod.z.object({Gate:ee.nullish(),Limits:Pe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Nc=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),wC=zod.z.object({Availability:J.nullish(),Write:J.nullish(),Retention:J.nullish()}).passthrough(),kC=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:TC.nullish(),Type:Lc.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:SC.nullish(),Capacity:zod.z.number().nullish(),Availability:Bc.nullish(),Write:Gc.nullish(),Retention:Nc.nullish(),Presets:wC.nullish()}).passthrough(),zC=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:ee.nullish(),WhoCanMessage:xC.nullish(),Limits:Pe.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),MC=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:IC.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Pe.nullish()}).passthrough(),OC=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),EC=zod.z.object({Availability:zod.z.record(zod.z.string(),Bc).nullish(),Write:zod.z.record(zod.z.string(),Gc).nullish(),Retention:zod.z.record(zod.z.string(),Nc).nullish()}).passthrough(),_c=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),kC).nullish(),Direct:zC.nullish(),Moderation:MC.nullish(),Polling:OC.nullish(),Presets:EC.nullish()}).passthrough(),qC=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),Uc=zod.z.object({LastAt:zod.z.string().nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:zod.z.string().nullish(),TotalCount:zod.z.number().nullish(),LastTextHash:zod.z.string().nullish()}).passthrough();zod.z.object({MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish(),Ignored:zod.z.array(zod.z.string()).nullish(),Channels:zod.z.record(zod.z.string(),qC).nullish(),Limits:zod.z.record(zod.z.string(),Uc).nullish(),ReportLimits:Uc.nullish()}).passthrough();var wa=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),xs=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:Ne.nullish(),AuthorType:vC.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),SystemKey:zod.z.string().nullish(),SystemParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),UC=zod.z.object({ChannelID:zod.z.string().nullish(),RoomID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Type:Lc.nullish(),CanWrite:zod.z.boolean().nullish(),WriteBlockedReason:zod.z.string().nullish(),SlowModeSeconds:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Ds=zod.z.object({Channels:zod.z.array(UC).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),LC=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(xs).nullish(),NextCursor:wa.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Fc=zod.z.object({Rooms:zod.z.array(LC).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Vc=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(xs).nullish(),NextBefore:wa.nullish()}).passthrough(),jc=zod.z.object({Message:xs.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),Wc=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ne.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),BC=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ne.nullish(),LastMessage:xs.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Hc=zod.z.object({Conversations:zod.z.array(BC).nullish()}).passthrough(),Bn=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:wa.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),Kc=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),tt={GetChatDefinitions:"GetChatDefinitions",GetChannels:"GetChannels",Poll:"Poll",GetHistory:"GetHistory",GetConversations:"GetConversations",SendMessage:"SendMessage",OpenDirectChannel:"OpenDirectChannel",MarkRead:"MarkRead",JoinChannel:"JoinChannel",LeaveChannel:"LeaveChannel",ReportMessage:"ReportMessage",IgnoreUser:"IgnoreUser",UnignoreUser:"UnignoreUser"};var Qc="Chat",$c={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Is=class{constructor(e){this.ctx=e;e.cache.bindLoginView($c,{schema:Ds,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(Qc,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.chat.getChatDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Qc,i.data),this.ctx.emitter.emit("chat:definitionsLoaded",i.data)),i}getChannels(e,t){return this.ctx.cache.read($c,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.Locale=e);let n=await this.ctx.api.chat.getChannels(t);return n.ok&&this.ctx.emitter.emit("chat:channelsLoaded",n.data),n}async poll(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let n=await this.ctx.api.chat.poll(t);if(!n.ok)return n;for(let i of n.data.Rooms??[])i.NextCursor&&i.RoomID&&this.cursors.set(i.RoomID,i.NextCursor),i.Messages&&i.Messages.length>0&&this.ctx.emitter.emit("chat:messages",i);return n}async getHistory(e,t,n){let i=this.ctx.authedRequest();return i?(i.RoomID=e,t&&(i.Before=t),n&&(i.Limit=n),this.ctx.api.chat.getHistory(i)):l}async sendMessage(e,t,n){let i=this.ctx.authedRequest();if(!i)return l;i.ChannelID=e,i.Text=t,n&&(i.Locale=n);let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async sendDirect(e,t){let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.Text=t;let i=await this.ctx.api.chat.sendMessage(n);return i.ok&&this.ctx.emitter.emit("chat:sent",i.data),i}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):l}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):l}async markRead(e,t){let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let i=await this.ctx.api.chat.markRead(n);return i.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),i}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):l}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):l}async reportMessage(e,t,n,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,s.MessageID=t,s.Reason=n,i&&(s.Comment=i),this.ctx.api.chat.reportMessage(s)):l}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):l}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):l}resetCursors(){this.cursors.clear();}};var GC={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},NC=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),_C={Player:"player",Title:"title",Creator:"creator"},Gn={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Jc=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),FC=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),ka=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:NC.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(FC).nullish()}).passthrough(),Zc=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(ka).nullish()}).passthrough(),nt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var VC="IDOS_PLATFORM_PUSH_REQUEST",jC="IDOS_PLATFORM_PUSH_RESPONSE",WC=12e4;function Yc(r){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(n=>{let i=false,s=m=>{i||(i=true,window.removeEventListener("message",o),clearTimeout(p),n(m));},o=m=>{let g=m?.data;!g||g.type!==jC||g.requestId!==t||Lt.includes(m.origin)&&s(g.ok===true);},p=setTimeout(()=>s(false),WC);window.addEventListener("message",o);for(let m of Lt)try{e.postMessage({type:VC,requestId:t,titleID:r},m);}catch{}})}var HC="idos:push:deviceToken:",Ps=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let n=await this.ctx.api.push.getPushConfig(t),i=n.ok?n.data:{Configured:false,PublicKey:null};return this.cachedConfig=i,n.ok&&this.ctx.emitter.emit("push:configLoaded",i),i}async getState(){let e=await this.getConfig();if(this.ctx.host.supports.pushNotifications){if(!e.Configured)return nt.Unsupported;let s=await this.ctx.host.requestPushToken({prompt:false});return s.error==="BLOCKED"?nt.Blocked:s.token?this.ctx.host.storage.getString(this.deviceTokenKey())===s.token?nt.Subscribed:nt.Idle:s.error==="NOT_GRANTED"?nt.Idle:nt.Unsupported}if(!e.Configured||!e.PublicKey)return nt.Unsupported;if(this.isEmbedded())return nt.Embedded;if(!this.isSupported())return nt.Unsupported;let t=Notification.permission;return t==="denied"?nt.Blocked:t!=="granted"?nt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?nt.Subscribed:nt.Idle}async subscribe(e={}){let t=await this.getConfig();if(this.ctx.host.supports.pushNotifications)return this.subscribeDevice(t,e);if(!t.Configured||!t.PublicKey)return h("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Yc(this.ctx.settings.titleID)?B({Where:"portal",Subscription:null}):h("client","The portal did not complete the subscription.");if(!this.isSupported())return h("client","This browser has no Push API.");let n=await Notification.requestPermission();if(n!=="granted")return h("client",n==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let i=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await i.pushManager.getSubscription()??await i.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:KC(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return l;let m=o.toJSON();p.PushEndpoint=m.endpoint,p.PushP256dh=m.keys?.p256dh,p.PushAuth=m.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let g=await this.ctx.api.push.subscribePush(p);return g.ok?(this.ctx.emitter.emit("push:subscribed",g.data),B({Where:"game",Subscription:g.data})):g}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return l;if(this.ctx.host.supports.pushNotifications){let n=this.ctx.host.storage.getString(this.deviceTokenKey());if(!n)return h("client","This device has no push subscription to remove.");e.PushDeviceToken=n;let i=await this.ctx.api.push.unsubscribePush(e);return i.ok&&(this.ctx.host.storage.remove(this.deviceTokenKey()),this.ctx.emitter.emit("push:unsubscribed",void 0)),i}if(this.isSupported()){let i=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();i&&(e.PushEndpoint=i.endpoint,await i.unsubscribe());}if(!e.PushEndpoint)return h("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):l}async unsubscribeByHash(e){if(!e)return h("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return l;t.PushEndpointHash=e;let n=await this.ctx.api.push.unsubscribePush(t);return n.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),n}async subscribeDevice(e,t){if(!e.Configured)return h("client","Push notifications are not available for this title.");let n=await this.ctx.host.requestPushToken({prompt:true});if(!n.token)return h("client",n.error==="BLOCKED"?"The player blocked notifications for this app.":"The device gave no push token.");let i=this.ctx.authedRequest();if(!i)return l;i.PushTransport=n.transport??"Fcm",i.PushDeviceToken=n.token,i.PushLocale=t.locale??(this.ctx.host.getLanguage()||void 0),i.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let s=await this.ctx.api.push.subscribePush(i);return s.ok?(this.ctx.host.storage.setString(this.deviceTokenKey(),n.token),this.ctx.emitter.emit("push:subscribed",s.data),B({Where:"game",Subscription:s.data})):s}deviceTokenKey(){return HC+this.ctx.settings.titleID}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function KC(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),n=new ArrayBuffer(t.length),i=new Uint8Array(n);for(let s=0;s<t.length;s++)i[s]=t.charCodeAt(s);return n}var vs=Object.freeze({}),As=class{constructor(e){this.ctx=e;}ctx;table={...vs};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new Ln(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,n])=>({Locale:n?.Locale??t,DisplayName:n?.DisplayName??null,Order:n?.Order??0})).sort((t,n)=>(t.Order??0)-(n.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let n=this.resolveKey(e,t),i=this.lookup(n)??this.lookup(e);return i===void 0?this.onMissing(e):t?QC(i,t):i}applyState(e,t){if(!e){this.reset();return}let n=e.Locale??null;this.table=t.table??{...vs},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return l;let n=await this.loadTableFromApi(e);if(!n.ok)return n;let{locale:i,table:s,fallbackLocale:o}=n.data,p=null;if(o){let m=await this.loadTableFromApi(o);m.ok&&(p=m.data.table);}return this.table=s,this.fallbackTable=p,this.currentFallbackLocale=o,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:o,entryCount:Object.keys(s).length}),{ok:true,data:i}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):l}reset(){this.table={...vs},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:F()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return l;t.Locale=e;let n=await this.cache.read(Xc(e));n&&(t.KnownVersion=n.v);let i=await this.ctx.api.localization.getLocalizationTable(t);if(!i.ok)return i;let s=i.data,o=s.Locale??Xc(e),p=s.Version??0;if(s.NotModified){let g=n??await this.cache.read(o);return {ok:true,data:{locale:o,table:g?.t??{...vs},fallbackLocale:s.FallbackLocale??null}}}let m=s.Entries??{};return p>0&&await this.cache.write(o,p,m),{ok:true,data:{locale:o,table:m,fallbackLocale:s.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let n=t?.count;if(typeof n!="number")return e;let i=this.pluralCategory(n),s=`${e}.${i}`;if(this.lookup(s)!==void 0)return s;let o=`${e}.other`;return this.lookup(o)!==void 0?o:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function QC(r,e){return r.replace(/\{(\w+)\}/g,(t,n)=>{let i=e[n];return i===void 0?t:String(i)})}function Xc(r){return r.trim().replace(/_/g,"-").toLowerCase()}var za="Quest",$C={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:r=>{let e=Date.now(),t=null,n=[...Object.values(r.PointsTracks??{}).map(i=>i?.CycleEndUtc),...Object.values(r.State?.Cycles??{}).map(i=>i?.CycleEndUtc)];for(let i of n){let s=Date.parse(i??"");!Number.isNaN(s)&&s>e&&(t===null||s<t)&&(t=s);}return t}},Ts=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:n=>{let i=e.cache.configSection(za)?.Cycles;if(!i)return false;let s=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(i)){let p=Date.parse(s[o]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=n&&t<p)return true}return false},refresh:async()=>{let n=await this.getUserQuestState(true,{forceRefresh:true});return n.ok&&(t=Date.now()),n}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(za,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.quest.getQuestDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(za,i.data),this.ctx.emitter.emit("quest:definitionsLoaded",i.data)),i}getUserQuestState(e=true,t){return this.ctx.cache.read($C,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return l;t.AutoRefreshCycles=e;let n=await this.ctx.api.quest.getUserQuestState(t);if(n.ok){let i=n.data.State??{};this.ctx.data.user.applyQuest(i),this.ctx.data.user.patchQuestPointsTracks(n.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",i);}return n}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let n=e.trim();if(!n)return h("client","QuestID is required.");if(!this.ctx.auth.context)return l;let i=t&&t.trim().length>0?t.trim():void 0,s={...this.ctx.buildAuthedBaseRequest(),QuestID:n,CycleID:i,RelatedEntityID:`quest_claim_${i??""}_${n}_${F()}`},o=await this.ctx.api.quest.claimQuestReward(s);if(o.ok){let p=o.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return h("client","quests is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},n=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(n.ok){let i=false;for(let s of n.data)!s.Success||!s.Data||(this.ctx.data.user.patchQuestStatus(s.Data.QuestID,s.Data.CycleID,"Claimed"),!i&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",n.data);}return n}async claimMilestoneReward(e,t){let n=e.trim(),i=t.trim();if(!n||!i)return h("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),CycleID:n,MilestoneID:i,RelatedEntityID:`milestone_claim_${n}_${i}_${F()}`},o=await this.ctx.api.quest.claimMilestoneReward(s);if(o.ok){let p=o.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return h("client","milestones is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(n.ok){let i=false;for(let s of n.data)!s.Success||!s.Data||(this.ctx.data.user.patchMilestoneClaimed(s.Data.CycleID,s.Data.MilestoneID),!i&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",n.data);}return n}async claimGroupCompletionReward(e,t){let n=e.trim(),i=t.trim();if(!n||!i)return h("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),CycleID:n,GroupCompletionID:i,RelatedEntityID:`group_completion_${n}_${i}_${F()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(s);if(o.ok){let p=o.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return o}async addQuestProgress(e,t){let n=e.trim();if(!n)return h("client","MetricID is required.");if(t<0)return h("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),MetricID:n,ProgressValue:t},s=await this.ctx.api.quest.addQuestProgress(i);return s.ok&&(this.ctx.data.user.patchQuestProgressUpdates(s.data.Updates),this.ctx.emitter.emit("quest:progressAdded",s.data)),s}};var ep=zod.z.object({}).passthrough().transform(r=>r);var JC=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),ZC=zod.z.object({Schedule:zod.z.array(JC).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),YC=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:u.nullish(),NextBonusStartUtc:u.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),XC=zod.z.object({Milestones:J.nullish()}).passthrough(),Ma=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Category:zod.z.string().nullish(),Token:wt.nullish(),TokenSources:zod.z.array(mt).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),Presets:XC.nullish(),BonusWindow:ZC.nullish()}).passthrough(),eS=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:Ma.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),tS=zod.z.object({TimedEventID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:Ce.nullish(),Content:Ma.nullish(),Events:zod.z.array(eS).nullish(),Gate:ee.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),nS=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),iS=zod.z.object({Milestones:zod.z.record(zod.z.string(),zn).nullish()}).passthrough(),ws=zod.z.object({Definitions:zod.z.record(zod.z.string(),tS).nullish(),Settings:nS.nullish(),Presets:iS.nullish()}).passthrough(),sS=zod.z.object({Type:Yn,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:Ma.nullish(),Progress:ep.nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:Ve.nullish(),BonusWindow:YC.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),ks=zod.z.object({ActiveEvents:zod.z.array(sS).nullish()}).passthrough(),tp=zod.z.object({Tokens:zod.z.record(zod.z.string(),ep).nullish()}),Oa=zod.z.object({Type:Yn.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),Ea=zod.z.object({Type:Yn.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}),rS=zod.z.object({Type:Yn.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),qa=zod.z.array(Oe(Ea)),np=zod.z.array(Oe(Oa)),ip=zod.z.array(Oe(rS)),yt={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var sp="TimedEvent",rp={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:r=>{let e=null;for(let t of r.ActiveEvents??[]){let n=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},zs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(rp,{schema:ks,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(rp,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(sp,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.timedEvent.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(sp,i.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",i.data)),i}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,n,i,s,o,p=1){if(!t)return h("client","LteID is required.");if(!n)return h("client","SourceType is required.");if(!this.ctx.auth.context)return l;let m={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:n,Outcome:i,AmountOverride:s,SourceParams:o,RollMultiplier:p},g=await this.ctx.api.timedEvent.grantTokens(m);return g.ok&&(this.ctx.data.user.applyResourceOperation(g.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",g.data)),g}async spendTokens(e,t,n){if(!t)return h("client","LteID is required.");if(n<=0)return h("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:n},s=await this.ctx.api.timedEvent.spendTokens(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",s.data)),s}async claimMilestone(e,t,n){if(!t||!n)return h("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:n},s=await this.ctx.api.timedEvent.claimMilestone(i);if(s.ok){let o=s.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,n,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return s}async claimMilestonesBatch(e){if(!e||e.length===0)return h("client","milestones is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return n.ok&&(this.applyMilestoneClaimBatch(n.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",n.data)),n}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return l;e&&e.length>0&&(t.Events=e);let n=await this.ctx.api.timedEvent.claimAllMilestones(t);return n.ok&&(this.applyMilestoneClaimBatch(n.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",n.data)),n}async spendTokensBatch(e){if(!e||e.length===0)return h("client","spends is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},n=await this.ctx.api.timedEvent.spendTokensBatch(t);if(n.ok){let i=false;for(let s of n.data)!i&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(s.Data.Resources,this.ctx.data.config.itemDefinitions),i=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",n.data);}return n}async grantTokensBatch(e){if(!e||e.length===0)return h("client","grants is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},n=await this.ctx.api.timedEvent.grantTokensBatch(t);if(n.ok){let i=false;for(let s of n.data)!i&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(s.Data.Resources,this.ctx.data.config.itemDefinitions),i=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",n.data);}return n}applyMilestoneClaimBatch(e){let t=false;for(let n of e){if(!n.Success||!n.Data)continue;let i=n.Data;i.Type&&i.LteID&&i.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(i.Type,i.LteID,i.MilestoneID,i.TokenEntityID),!t&&i.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(i.Rewards,i.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var oS=zod.z.object({UserID:zod.z.string(),Score:Q.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:u.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:Ne.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),oi=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:Q.nullish(),CycleEndUtc:u.nullish(),TopUsers:zod.z.array(oS).nullish(),BracketID:zod.z.string().nullish()}),aS=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),MilestoneTokensEarned:Q.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Ms=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:Q.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:Q.nullish(),MilestoneTokensEarned:Q.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:Ve.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(aS).nullish()}),Os=zod.z.object({LeaderboardID:zod.z.string(),NewScore:Q,CycleVersion:zod.z.number()}),Es=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),qs=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish()}),op=zod.z.array(Oe(oi)),Us=zod.z.array(Oe(Ms)),ap=zod.z.array(Oe(Es)),lp=zod.z.array(Oe(qs)),up=zod.z.array(Oe(Os)),lS=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:Oe(Es).nullish(),Milestones:zod.z.array(Oe(qs)).nullish()}),cp=zod.z.array(lS),uS=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:Oe(oi).nullish(),Progress:Oe(Ms).nullish()}),pp=zod.z.array(uS),cS=zod.z.string(),hp=zod.z.object({Rank:zod.z.string().nullish(),Rewards:$.nullish(),SeasonTierRewards:da.nullish()}).passthrough(),pS=zod.z.object({RankRewards:zod.z.array(hp).nullish()}).passthrough(),hS=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),dS=zod.z.object({Milestones:J.nullish(),RankRewards:J.nullish()}).passthrough(),mS=zod.z.object({LeaderboardID:zod.z.string(),DisplayName:zod.z.string().nullish(),ScoreDisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsEnabled:zod.z.boolean().nullish(),ScoreAggregation:cS.nullish(),Schedule:Ce.nullish(),ChainEvents:zod.z.array(hS).nullish(),Gate:ee.nullish(),TopUsersLimit:zod.z.number().nullish(),MinScoreToEnterTop:zod.z.number().nullish(),BracketSize:zod.z.number().nullish(),LinkedSeasonChainID:zod.z.string().nullish(),RankRewards:zod.z.array(hp).nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),Presets:dS.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(mt).nullish()}).passthrough(),fS=zod.z.object({Milestones:zod.z.record(zod.z.string(),zn).nullish(),RankRewards:zod.z.record(zod.z.string(),pS).nullish()}).passthrough(),Ls=zod.z.object({Definitions:zod.z.record(zod.z.string(),mS).nullish(),Presets:fS.nullish()}).passthrough(),Ze={GetDefinitions:"GetDefinitions",GetLeaderboard:"GetLeaderboard",GetMyProgress:"GetMyProgress",SubmitScore:"SubmitScore",SubmitScoreFromSource:"SubmitScoreFromSource",ClaimCycleReward:"ClaimCycleReward",ClaimMilestone:"ClaimMilestone",GetFriendsLeaderboard:"GetFriendsLeaderboard",GetLeaderboardsBatch:"GetLeaderboardsBatch",GetProgressBatch:"GetProgressBatch",ClaimCycleRewardsBatch:"ClaimCycleRewardsBatch",ClaimMilestonesBatch:"ClaimMilestonesBatch",SubmitScoresBatch:"SubmitScoresBatch",ClaimAllRewardsBatch:"ClaimAllRewardsBatch",GetOverviewBatch:"GetOverviewBatch"};var dp="Leaderboard",mp={key:"leaderboard.progress",login:"LeaderboardProgress",ttlMs:5*6e4,dependsOn:["Leaderboard","EventToken"],invalidateOn:["leaderboard:scoreSubmitted","leaderboard:scoresSubmittedBatch","leaderboard:cycleRewardClaimed","leaderboard:cycleRewardsClaimedBatch","leaderboard:milestoneClaimed","leaderboard:milestonesClaimedBatch","leaderboard:allRewardsClaimedBatch"]},Bs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(mp,{schema:Us,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(dp,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.leaderboard.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(dp,i.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",i.data)),i}async getLeaderboard(e){if(!e)return h("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getLeaderboard(t);return n.ok&&this.ctx.emitter.emit("leaderboard:loaded",n.data),n}async getMyProgress(e){if(!e)return h("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getMyProgress(t);return n.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),n.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",n.data)),n}async submitScore(e,t){if(!e)return h("client","LeaderboardID is required.");if(t<=0)return h("client","Score must be positive.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},i=await this.ctx.api.leaderboard.submitScore(n);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),s.NewScore,t,s.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",s);}return i}async submitScoreFromSource(e,t,n,i,s=1){if(!e)return h("client","LeaderboardID is required.");if(!t)return h("client","SourceType is required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:n,Params:i,RollMultiplier:s},p=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(p.ok){let m=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),m.NewScore,m.NewScore,m.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",m);}return p}async claimCycleReward(e){if(!e)return h("client","LeaderboardID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},n=await this.ctx.api.leaderboard.claimCycleReward(t);if(n.ok){let i=n.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",i);}return n}async claimMilestone(e,t,n){if(!e||!t)return h("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...n?{CycleKey:n}:{}},s=await this.ctx.api.leaderboard.claimMilestone(i);if(s.ok){let o=s.data;n||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",o);}return s}async getFriendsLeaderboard(e){if(!e)return h("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return n.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",n.data),n}async getLeaderboardsBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return n.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",n.data),n}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(h("client","leaderboardIDs is required.")):this.ctx.cache.read(mp,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getProgressBatch(t);return n.ok&&this.applyProgressBatch(n.data),n}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},n=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(n.ok){for(let i of n.data)!i.Success||!i.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(i.Data.LeaderboardID)),i.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",n.data);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return h("client","milestones is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(n.ok){for(let i of n.data)!i.Success||!i.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(i.Data.LeaderboardID),i.Data.MilestoneID),i.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",n.data);}return n}async submitScoresBatch(e){if(!e||e.length===0)return h("client","scores is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},n=await this.ctx.api.leaderboard.submitScoresBatch(t);if(n.ok){for(let i of n.data)!i.Success||!i.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(i.Data.LeaderboardID),i.Data.NewScore,i.Data.NewScore,i.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",n.data);}return n}async claimAllRewardsBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},n=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(n.ok){for(let i of n.data){let s=this.cycleDocID(i.LeaderboardID);i.CycleReward?.Success&&i.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(s),i.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.CycleReward.Data.Resources,i.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of i.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(s,o.Data.MilestoneID),o.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(o.Data.Resources,o.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",n.data);}return n}async getOverviewBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getOverviewBatch(t);if(n.ok){for(let i of n.data)i.Progress?.Success&&i.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(i.LeaderboardID),i.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",n.data);}return n}};var Ua=zod.z.object({}).passthrough().transform(r=>r),Gs=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>Rp).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:Q.nullish(),UserState:Ua.nullish(),NextTier:zod.z.lazy(()=>yp).nullish()}).passthrough(),fp=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:Q.nullish(),NewStatusTokens:Q.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),La=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:O.nullish(),Inventory:K.nullish()}),gp=kt(La);var yp=zod.z.object({Tier:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredTokens:Q.nullish(),TierReachedReward:$.nullish()}).passthrough(),Rp=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:Q.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(yp).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var gS=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Ce.nullish(),Seasons:zod.z.array(Rp).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:ee.nullish()}).passthrough(),Ns=zod.z.object({Chains:zod.z.record(zod.z.string(),gS).nullish()}).passthrough(),Yt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Cp="Season",Sp={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=Date.parse(r.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},_s=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Sp,{schema:Gs,apply:(t,n)=>this.applyActiveSeason(n??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Cp,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.season.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Cp,i.data),this.ctx.emitter.emit("season:definitionsLoaded",i.data)),i}getActiveSeason(e,t){return e?this.ctx.cache.read(Sp,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(h("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return l;t.SeasonChainID=e;let n=await this.ctx.api.season.getActiveSeason(t);return n.ok&&this.applyActiveSeason(e,n.data),n}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return h("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.SeasonChainID=e;let n=await this.ctx.api.season.getUserState(t);return n.ok&&(this.ctx.data.user.patchSeasonState(e,n.data),this.ctx.emitter.emit("season:userStateLoaded",n.data)),n}async grantStatusTokens(e,t){if(!e)return h("client","SeasonChainID is required.");if(t<=0)return h("client","Amount must be positive.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${F()}`},i=await this.ctx.api.season.grantStatusTokens(n);return i.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,i.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",i.data)),i}async claimTierReward(e,t){if(!e)return h("client","SeasonChainID is required.");if(t<=0)return h("client","TierNumber must be positive.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${F()}`},i=await this.ctx.api.season.claimTierReward(n);if(i.ok){let s=i.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",s);}return i}async claimTierRewardsBatch(e,t){if(!e)return h("client","SeasonChainID is required.");let n=(t??[]).filter(o=>o>0);if(n.length===0)return h("client","TierNumbers is required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:n,RelatedEntityID:`season_tier_batch_${e}_${F()}`},s=await this.ctx.api.season.claimTierRewardsBatch(i);if(s.ok){let o=s.data;for(let p of o.Items??[]){let m=p.Data?.TierNumber;p.Success&&typeof m=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,m);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return s}};var bp="Premium",Fs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(bp,e);if(t){let s={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",s),B(s)}let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.premium.getDefinitions(n);return i.ok&&i.data.Premium&&(this.ctx.data.config.patchSection(bp,i.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",i.data)),i}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return h("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},i=await this.ctx.api.premium.activateTrial(n);return i.ok&&(i.data.Premium&&this.ctx.data.user.applyPremium(i.data.Premium),this.ctx.emitter.emit("premium:trialActivated",i.data)),i}async purchaseItemOrCurrency(e,t,n="Default",i=1,s){if(!e||!t)return h("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:n,Count:i,CreditsConfirmationID:s,RelatedEntityID:`premium_purchase_${e}_${t}`},p=await this.ctx.api.premium.purchaseItemOrCurrency(o);if(p.ok&&!p.data.CreditsConfirmation){let m=p.data;m.Premium&&this.ctx.data.user.applyPremium(m.Premium),this.ctx.data.user.applyResourceOperation(m.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",m);}return p}async purchaseRealMoney(e,t,n,i,s,o,p,m){if(!e||!t)return h("client","PremiumID and TransactionID are required.");if(!i||!s)return h("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return l;let g={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:n,ProductID:i,ReceiptData:s,PurchaseToken:o,PackageName:p,AppStoreEnvironment:m,RelatedEntityID:`premium_iap_${e}_${t}`},j=await this.ctx.api.premium.purchaseRealMoney(g);if(j.ok){let ce=j.data;ce.Premium&&this.ctx.data.user.applyPremium(ce.Premium),this.ctx.data.user.applyResourceOperation(ce.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",ce);}return j}};var Vs=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:u.nullish()}),ai=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:Q.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),Vs).nullish(),UpdatedAt:u.nullish()}).passthrough(),xp=zod.z.object({Characters:zod.z.record(zod.z.string(),ai).nullish(),SelectedCharacterID:zod.z.string().nullish()}),Ba=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Ga=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Dp=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Vs).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Ip=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),yS=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Pp=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),yS).nullish(),Inventory:K.nullish()}),Na=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:O.nullish()}),vp=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:Vs.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Ap=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Vs.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Tp=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),RS=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:u.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:de.nullish()}),CS=zod.z.object({CharacterID:zod.z.string(),CharacterOpen:zod.z.boolean().nullish(),DefaultSkinID:zod.z.string().nullish(),WornSkinID:zod.z.string().nullish(),Skins:zod.z.array(RS).nullish()}),wp=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),CS).nullish()}),kp=zod.z.object({ServerTimeUtc:u,SelectedCharacterID:zod.z.string().nullish()}),zp=kt(Na),Mp=kt(Ga),Op=kt(Ba),_a=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),Ep=zod.z.object({StatID:zod.z.string(),TypeID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish(),Weight:zod.z.number().nullish(),PriceOptions:de.nullish(),CostCurve:Je.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Je.nullish(),RankCurve:Je.nullish(),Requirements:zod.z.array(_a).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),SS=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(_a).nullish(),AllowedRarityIDs:zod.z.array(zod.z.string()).nullish(),AllowedItemTags:zod.z.array(zod.z.string()).nullish(),MinItemLevel:zod.z.number().nullish(),MaxItemLevel:zod.z.number().nullish()}).passthrough(),qp=zod.z.object({Slots:zod.z.record(zod.z.string(),SS).nullish()}).passthrough(),Up=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Lore:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),bS=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),xS=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:de.nullish()}).passthrough(),DS=zod.z.object({Stats:J.nullish(),Levels:J.nullish(),Equipment:J.nullish()}).passthrough(),Lp=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:de.nullish(),CostCurve:Je.nullish()}).passthrough(),Fa="@skin";function IS(r){return !!r&&r.startsWith("@")}var PS=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),vS=zod.z.object({PriceOptions:de.nullish(),Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),AS=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(_a).nullish()}).passthrough(),TS=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Up.nullish(),Item:PS.nullish(),Sale:vS.nullish(),Requirements:AS.nullish()}).passthrough(),wS=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),TS).nullish()}).passthrough(),kS=zod.z.object({CharacterID:zod.z.string(),Identity:Up.nullish(),Classification:bS.nullish(),Unlock:xS.nullish(),Presets:DS.nullish(),Equipment:qp.nullish(),Stats:zod.z.record(zod.z.string(),Ep).nullish(),RankLadder:Lp.nullish(),RankStatCurve:Je.nullish(),StatMaxLevelCurve:Je.nullish(),Skins:wS.nullish()}).passthrough(),zS=zod.z.object({Stats:zod.z.record(zod.z.string(),Ep).nullish()}).passthrough(),MS=zod.z.object({RankLadder:Lp.nullish()}).passthrough(),OS=zod.z.object({Equipment:qp.nullish()}).passthrough(),ES=zod.z.object({Stats:zod.z.record(zod.z.string(),zS).nullish(),Levels:zod.z.record(zod.z.string(),MS).nullish(),Equipment:zod.z.record(zod.z.string(),OS).nullish()}).passthrough(),js=zod.z.object({Definitions:zod.z.record(zod.z.string(),kS).nullish(),Presets:ES.nullish()}).passthrough(),$e={GetCharacterDefinitions:"GetCharacterDefinitions",GetUserCharacters:"GetUserCharacters",UnlockCharacter:"UnlockCharacter",UpgradeStatLevel:"UpgradeStatLevel",UpgradeCharacterLevel:"UpgradeCharacterLevel",EquipItems:"EquipItems",UnequipItems:"UnequipItems",UnequipAllCharacters:"UnequipAllCharacters",UnlockCharactersBatch:"UnlockCharactersBatch",UpgradeCharacterLevelsBatch:"UpgradeCharacterLevelsBatch",UpgradeStatLevelsBatch:"UpgradeStatLevelsBatch",UnlockSkin:"UnlockSkin",EquipSkin:"EquipSkin",UnequipSkin:"UnequipSkin",GetCharacterSkins:"GetCharacterSkins",SelectCharacter:"SelectCharacter"},qS="SKIN_ALREADY_OWNED";var Va="Character",Ws=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Va)?.Definitions,n=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([i,s])=>s?.Unlock?.UnlockedByDefault===true&&!n[s.CharacterID??i])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(Va,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.character.getCharacterDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Va,i.data),this.ctx.emitter.emit("character:definitionsLoaded",i.data)),i}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let n=t.data.Characters??{};this.ctx.data.user.applyCharacter(n),this.ctx.data.user.applySelectedCharacter(t.data.SelectedCharacterID),this.ctx.emitter.emit("character:userCharactersLoaded",n);}return t}async unlockCharacter(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${F()}`},i=await this.ctx.api.character.unlockCharacter(n);if(i.ok&&!i.data.CreditsConfirmation){let s=i.data;this.ctx.data.user.patchCharacter(s.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},s.Power!=null&&(o.Power=s.Power),o.UpdatedAt=s.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(s.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",s);}return i}async upgradeStatLevel(e,t,n){if(!e||!t)return h("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${F()}`,SelectedOptionID:n?.selectedOptionID,CreditsConfirmationID:n?.creditsConfirmationID,...n?.levels!=null?{Levels:n.levels}:{},...n?.targetLevel!=null?{TargetLevel:n.targetLevel}:{}},s=await this.ctx.api.character.upgradeStatLevel(i);if(s.ok&&!s.data.CreditsConfirmation){let o=s.data;this.ctx.data.user.patchCharacter(o.CharacterID,p=>{p.StatLevels??={},p.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(p.Power=o.Power),p.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return s}async upgradeCharacterLevel(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${F()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},i=await this.ctx.api.character.upgradeCharacterLevel(n);if(i.ok&&!i.data.CreditsConfirmation){let s=i.data;this.ctx.data.user.patchCharacter(s.CharacterID,o=>{o.Level=s.NewLevel,s.Power!=null&&(o.Power=s.Power),o.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(s.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",s);}return i}async equipItems(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},i=await this.ctx.api.character.equipItems(n);return i.ok&&(this.applyEquipChangesLocally(e,i.data),this.ctx.emitter.emit("character:itemsEquipped",i.data)),i}async unequipItems(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},i=await this.ctx.api.character.unequipItems(n);if(i.ok){let s=i.data;this.applyUnequipChangesLocally(e,s),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:s.ClearedSlotIDs??[],power:s.Power??null});}return i}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,n){if(!e||!t)return h("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,AutoEquip:n?.autoEquip??false,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${F()}`},s=await this.ctx.api.character.unlockSkin(i);if(s.ok&&!s.data.CreditsConfirmation){let o=s.data;this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),o.Equipped&&o.Equipment&&this.applySkinLocally(o.CharacterID,o.Equipment,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",o);}return s}async equipSkin(e,t,n){if(!e||!t)return h("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:n},s=await this.ctx.api.character.equipSkin(i);if(s.ok){let o=s.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return s}async unequipSkin(e){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},n=await this.ctx.api.character.unequipSkin(t);if(n.ok){let i=n.data;i.Cleared&&(this.applyInventoryDelta(i.Inventory),this.applySkinLocally(i.CharacterID,null,i.Power,i.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",i);}return n}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):l}async selectCharacter(e){let t=this.ctx.authedRequest();if(!t)return l;let n=e?.trim();if(!n)return h("client","CharacterID is required.");t.CharacterID=n;let i=await this.ctx.api.character.selectCharacter(t);return i.ok&&(this.ctx.data.user.applySelectedCharacter(i.data.SelectedCharacterID),this.ctx.emitter.emit("character:selected",i.data)),i}applySkinLocally(e,t,n,i){let s=this.ctx.data.user;s.patchCharacterEquipment(e,Fa,t??null),s.patchCharacter(e,o=>{n!=null&&(o.Power=n),o.UpdatedAt=i;});}async unlockCharactersBatch(e){if(!e||e.length===0)return h("client","characterIDs is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},n=await this.ctx.api.character.unlockCharactersBatch(t);return n.ok&&(this.applyBatchResults(n.data,i=>{this.ctx.data.user.patchCharacter(i.CharacterID,s=>{s.Level??=1,s.StatLevels??={},s.Equipment??={},i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=i.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",n.data)),n}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return h("client","upgrades is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},n=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return n.ok&&(this.applyBatchResults(n.data,i=>{this.ctx.data.user.patchCharacter(i.CharacterID,s=>{s.Level=i.NewLevel,i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=i.ServerTimeUtc,i.NewLevel===1&&(s.StatLevels??={},s.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",n.data)),n}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return h("client","upgrades is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},n=await this.ctx.api.character.upgradeStatLevelsBatch(t);return n.ok&&(this.applyBatchResults(n.data,i=>{this.ctx.data.user.patchCharacter(i.CharacterID,s=>{s.StatLevels??={},s.StatLevels[i.StatID]=i.StatLevel,i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=i.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",n.data)),n}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let n of e.Items??[])!n.Success||!n.Data||t(n.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[i,s]of Object.entries(t.Equipment??{}))n.patchCharacterEquipment(e,i,s);n.patchCharacter(e,i=>{t.Power!=null&&(i.Power=t.Power),i.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let n=t.ClearedSlotIDs??[];if(n.length===0&&t.Power==null)return;let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let s of n)i.patchCharacterEquipment(e,s,null);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[n,i]of Object.entries(e.Characters??{})){for(let s of i.ClearedSlotIDs??[])t.patchCharacterEquipment(n,s,null);t.patchCharacter(n,s=>{i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=e.ServerTimeUtc;});}}};var Bp="Match",Hs=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,n,i,s,o){let p=this.ctx.auth.context;if(!p)return l;let m={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:n,BattleStrategy:i,TargetUserID:s,SelectedOptionID:o,RelatedEntityID:`pvp_create_${p.userID}_${F()}`},g=await this.ctx.api.match.createMatch(m);return g.ok&&(this.ctx.data.user.applyResourceOperation(g.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",g.data)),g}async updateMatch(e,t={}){if(!e)return h("client","MatchID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},i=await this.ctx.api.match.updateMatch(n);return i.ok&&this.ctx.emitter.emit("match:updated",i.data),i}async cancelMatch(e){if(!e)return h("client","MatchID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},n=await this.ctx.api.match.cancelMatch(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",n.data)),n}async instantBattle(e,t,n,i){let s=this.ctx.auth.context;if(!s)return l;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:n,BattleStrategy:i,RelatedEntityID:`pvp_battle_${e}_${F()}`},p=await this.ctx.api.match.instantBattle(o);if(p.ok){let m=p.data,g=this.ctx.data.config.itemDefinitions;if(m.Resources)this.ctx.data.user.applyResourceOperation(m.Resources,g);else if(m.ResourcesDual){let j=m.ResourcesDual;j.FromUserID===s.userID&&j.FromResult?this.ctx.data.user.applyResourceOperation(j.FromResult,g):j.ToUserID===s.userID&&j.ToResult&&this.ctx.data.user.applyResourceOperation(j.ToResult,g);}this.ctx.emitter.emit("match:instantBattleCompleted",m);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},n=await this.ctx.api.match.saveStrategy(t);return n.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),n}async getMyMatches(e=0,t=20,n){let i=this.ctx.authedRequest();if(!i)return l;i.Page=e,i.PageSize=t,i.Statuses=n;let s=await this.ctx.api.match.getMyMatches(i);return s.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",s.data),s}async getAvailableMatches(e=0,t=20,n=false){let i=this.ctx.authedRequest();if(!i)return l;i.Page=e,i.PageSize=t,i.OnlyPublic=n;let s=await this.ctx.api.match.getAvailableMatches(i);return s.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",s.data),s}async getDefinitions(e){let t=this.ctx.cache.configSection(Bp,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.match.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Bp,i.data),this.ctx.emitter.emit("match:definitionsLoaded",i.data)),i}};var US="Challenge",Ks=class{constructor(e){this.ctx=e;}ctx;lastState=null;get definitions(){return this.ctx.cache.configSection(US)??null}get state(){return this.lastState}chainDefinition(e){return this.definitions?.Chains?.[e]??null}phaseDefinition(e,t){return t?this.chainDefinition(e)?.Challenges?.find(n=>n?.ChallengeID===t)??null:null}chainView(e){return this.lastState?.Chains?.find(t=>t.ChainID===e)??null}newAttemptID(){return F().replace(/-/g,"")}async getState(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.ChainID=e);let n=await this.ctx.api.challenge.getState(t);return n.ok&&this.applyState(n.data,e),n}async refreshOpponents(e){if(!e)return h("client","ChainID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.ChainID=e;let n=await this.ctx.api.challenge.refreshOpponents(t);return n.ok&&this.applyState(n.data,e),n}async attempt(e,t,n,i,s){if(!e)return h("client","ChainID is required.");if(!n)return h("client","AttemptID is required.");let o=this.ctx.authedRequest();if(!o)return l;o.ChainID=e,o.AttemptID=n,"tierID"in t?o.TierID=t.tierID:o.RevengeID=t.revengeID,i&&(o.CharacterID=i),s&&(o.BattleStrategy=s);let p=await this.ctx.api.challenge.attempt(o);if(p.ok){let m=p.data;m.IsReplay||this.ctx.data.user.applyResourcesWithDelta(m.Rewards,m.Inventory,this.ctx.data.config.itemDefinitions),this.patchAfterAttempt(e,m,"revengeID"in t?t.revengeID:void 0),this.ctx.emitter.emit("challenge:attemptCompleted",m);}return p}async claimMilestone(e,t,n){if(!e||!t)return h("client","ChainID and MilestoneID are required.");let i=this.ctx.authedRequest();if(!i)return l;i.ChainID=e,i.MilestoneID=t,n&&(i.InstanceKey=n);let s=await this.ctx.api.challenge.claimMilestone(i);if(s.ok){let o=s.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.markClaimed(e,o.InstanceKey??n,t),this.ctx.emitter.emit("challenge:milestoneClaimed",o);}return s}async claimReachedMilestones(e){if(!this.ctx.auth.context)return l;let t=[],n=(this.lastState?.Chains??[]).filter(i=>!e||i.ChainID===e);for(let i of n){if(!i.ChainID)continue;let s=[i.Active,...i.Ended??[]].filter(o=>!!o&&!!o.CanClaim);for(let o of s)for(let p of this.reachedUnclaimed(i.ChainID,o)){let m=await this.claimMilestone(i.ChainID,p,o.InstanceKey??void 0);m.ok&&t.push(m.data);}}return B(t)}reachedUnclaimed(e,t){let n=this.phaseDefinition(e,t.ChallengeID),i=t.PointsEarned??0,s=new Set(t.ClaimedMilestoneIDs??[]);return Object.entries(n?.Milestones??{}).filter(([o,p])=>!s.has(o)&&(p?.RequiredProgress??1/0)<=i).sort((o,p)=>(o[1]?.RequiredProgress??0)-(p[1]?.RequiredProgress??0)).map(([o])=>o)}applyState(e,t){if((e.Rewards||e.Inventory)&&this.ctx.data.user.applyResourcesWithDelta(e.Rewards,e.Inventory,this.ctx.data.config.itemDefinitions),t&&this.lastState){let n=(this.lastState.Chains??[]).filter(i=>i.ChainID!==t);this.lastState={...e,Chains:[...n,...e.Chains??[]]};}else this.lastState=e;this.ctx.emitter.emit("challenge:stateLoaded",e);}patchAfterAttempt(e,t,n){let i=this.chainView(e);if(!i)return;t.Tickets!=null&&(i.Tickets=t.Tickets);let s=i.Active;if(!s||s.InstanceKey!==t.InstanceKey)return;t.PointsEarned!=null&&(s.PointsEarned=t.PointsEarned),t.IsReplay||(s.AttemptsToday=(s.AttemptsToday??0)+1);let o=t.Attempt;if(!(!o?.Win||!s.Arena))if(o.IsRevenge)s.Arena.Revenges=(s.Arena.Revenges??[]).filter(p=>p.RevengeID!==n);else for(let p of s.Arena.Opponents??[])p.TierID===o.TierID&&p.OpponentID===o.OpponentID&&(p.Defeated=true);}markClaimed(e,t,n){let i=this.chainView(e);if(i)for(let s of [i.Active,...i.Ended??[]])s&&(t&&s.InstanceKey!==t||!t&&s!==i.Active||(s.ClaimedMilestoneIDs=[...new Set([...s.ClaimedMilestoneIDs??[],n])]));}};var Gp="Craft",Qs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Gp,e);if(t){let s={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),B(s)}let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.craft.getDefinitions(n);return i.ok&&i.data.CraftDefinitions&&(this.ctx.data.config.patchSection(Gp,i.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",i.data.CraftDefinitions)),i}async craft(e,t,n=1,i,s,o){if(!e)return h("client","CraftID is required.");let p=this.ctx.auth.context;if(!p)return l;let m={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:n,SelectedOptionID:i,InputInstanceIDs:s,CreditsConfirmationID:o,RelatedEntityID:`craft_${e}_${p.userID}_${F()}`},g=await this.ctx.api.craft.craft(m);return g.ok&&!g.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(g.data.Resources,g.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",g.data)),g}};var Xt=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(Xt),zod.z.record(zod.z.string(),Xt)]));var en={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Np=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),fn={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function li(r){return r!==fn.Pending&&r!==fn.Running}var LS={Disabled:"AI_DISABLED",FeatureNotFound:"AI_FEATURE_NOT_FOUND",FeatureDisabled:"AI_FEATURE_DISABLED",WrongAction:"AI_WRONG_ACTION",NotAvailableForPlayer:"AI_NOT_AVAILABLE_FOR_PLAYER",FeatureClosed:"AI_FEATURE_CLOSED",LimitReached:"AI_LIMIT_REACHED",Cooldown:"AI_COOLDOWN",BadInput:"AI_BAD_INPUT",PromptRejected:"AI_PROMPT_REJECTED",Unavailable:"AI_UNAVAILABLE",GenerationFailed:"AI_GENERATION_FAILED",GenerationNotFound:"AI_GENERATION_NOT_FOUND"};function BS(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var GS=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),NS=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),$s=zod.z.object({CreditsConfirmation:ye.nullish(),GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Np.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),Xt).nullish(),Assets:zod.z.array(GS).nullish(),Error:NS.nullish(),Charge:O.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:O.nullish(),Context:zod.z.record(zod.z.string(),Xt).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish()}),_p=zod.z.object({Data:zod.z.array($s).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),_S=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish()}).passthrough(),Pt=zod.z.record(zod.z.string(),zod.z.string()),FS=zod.z.object({Key:zod.z.string().nullish(),Role:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),Label:Pt.nullish()}).passthrough(),VS=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Default:zod.z.string().nullish(),Multiline:zod.z.boolean().nullish(),Label:Pt.nullish(),Placeholder:Pt.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string().nullish(),Label:Pt.nullish()}).passthrough()).nullish()}).passthrough(),Fp=zod.z.object({Key:zod.z.string(),Kind:zod.z.string().nullish(),Name:Pt.nullish(),Hint:Pt.nullish(),Unit:Pt.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string(),Name:Pt.nullish(),Group:zod.z.string().nullish()}).passthrough()).nullish(),Groups:zod.z.array(zod.z.object({Key:zod.z.string(),Name:Pt.nullish()}).passthrough()).nullish(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),Step:zod.z.number().nullish()}).passthrough(),Vp=zod.z.object({PriceOptions:de.nullish()}).passthrough(),jS=zod.z.object({Id:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Action:zod.z.string().nullish(),IsTrend:zod.z.boolean().nullish(),Category:zod.z.string().nullish(),Order:zod.z.number().nullish(),Name:Pt.nullish(),Description:Pt.nullish(),Preview:zod.z.object({Url:zod.z.string().nullish(),PosterUrl:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough().nullish(),Inputs:zod.z.array(FS).nullish(),Variables:zod.z.array(VS).nullish(),Settings:zod.z.array(Fp).nullish()}).passthrough(),WS=zod.z.object({Modality:Np.nullish(),Async:zod.z.boolean().nullish(),Limits:Pe.nullish(),PriceOptions:de.nullish(),Tags:zod.z.array(zod.z.string()).nullish(),HistoryMessages:zod.z.number().nullish(),MaxTokens:zod.z.number().nullish(),AllowImages:zod.z.boolean().nullish(),MaxInputImages:zod.z.number().nullish(),MaxInputImageBytes:zod.z.number().nullish(),AllowedImageTypes:zod.z.array(zod.z.string()).nullish(),MaxImages:zod.z.number().nullish(),AllowEdit:zod.z.boolean().nullish(),AllowReferenceImage:zod.z.boolean().nullish(),MaxPromptChars:zod.z.number().nullish(),LockBehavior:zod.z.boolean().nullish(),ImageSize:zod.z.string().nullish(),VideoSize:zod.z.string().nullish(),VideoSeconds:zod.z.number().nullish(),Voice:zod.z.string().nullish(),AudioFormat:zod.z.string().nullish(),MusicFormat:zod.z.string().nullish(),ThreeDOperation:zod.z.string().nullish(),ThreeDAnimations:zod.z.array(zod.z.string()).nullish(),Reward:$.nullish(),PromptVariables:zod.z.array(_S).nullish(),AllowFreePrompt:zod.z.boolean().nullish(),PlatformTemplateId:zod.z.string().nullish(),PlatformTemplate:jS.nullish(),Settings:zod.z.array(Fp).nullish(),FreePerDay:zod.z.number().nullish(),FreeLeftToday:zod.z.number().nullish()}).passthrough(),jp=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),WS).nullish()}).passthrough(),je={GetDefinitions:"GetDefinitions",GenerateText:"GenerateText",GetText:"GetText",GenerateImage:"GenerateImage",EditImage:"EditImage",GenerateVideo:"GenerateVideo",GetVideo:"GetVideo",GenerateAudio:"GenerateAudio",GenerateMusic:"GenerateMusic",GenerateThreeD:"GenerateThreeD",GetThreeD:"GetThreeD",ListGenerations:"ListGenerations",GetGeneration:"GetGeneration",GetImage:"GetImage",GetAudio:"GetAudio",GetMusic:"GetMusic",GenerateFromTemplate:"GenerateFromTemplate",EstimateTemplatePrice:"EstimateTemplatePrice"};var Wp="AI",HS=/^[A-Za-z0-9_-]{1,128}$/,KS=2e3,QS=5e3,$S=30*6e4;function JS(r,e){return new Promise(t=>{if(e?.aborted){t();return}let n=()=>{clearTimeout(i),e?.removeEventListener("abort",n),t();},i=setTimeout(n,r);e?.addEventListener("abort",n,{once:true});})}var Js=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(Wp,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.ai.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Wp,i.data),this.ctx.emitter.emit("ai:definitionsLoaded",i.data)),i}generateText(e,t,n){return this.generate(e,{Text:t},n,i=>this.ctx.api.ai.generateText(i))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,n){return this.generate(e,{Image:t},n,i=>this.ctx.api.ai.generateImage(i))}editImage(e,t,n){return this.generate(e,{ImageEdit:t},n,i=>this.ctx.api.ai.editImage(i))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,n){return this.generate(e,{Video:t},n,i=>this.ctx.api.ai.generateVideo(i))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,n){return this.generate(e,{Audio:t},n,i=>this.ctx.api.ai.generateAudio(i))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,n){return this.generate(e,{Music:t},n,i=>this.ctx.api.ai.generateMusic(i))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,n){return this.generate(e,{TemplateInputs:t},n,i=>this.ctx.api.ai.generateFromTemplate(i))}async estimateTemplatePrice(e,t,n){return e?this.ctx.auth.context?this.ctx.api.ai.estimateTemplatePrice({...this.ctx.buildAuthedBaseRequest(),FeatureKey:e,Params:t,Variables:n}):l:h("client","FeatureKey is required.")}generateThreeD(e,t,n){return this.generate(e,{ThreeD:t},n,i=>this.ctx.api.ai.generateThreeD(i))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):l}async getGeneration(e){if(!e)return h("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):l}isTerminal(e){return li(e)}async waitForGeneration(e,t={}){let n;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;n=p.data;}else {if(!e?.GenerationID)return h("client","GenerationID is required.");n=e;}let i=Date.now()+(t.timeoutMs??$S),s=Math.max(1,t.intervalMs??KS),o=Math.max(s,t.maxIntervalMs??QS);for(;!li(n.Status);){if(t.signal?.aborted)return h("client","Stopped waiting: the wait was aborted.");if(Date.now()+s>i)return h("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await JS(s,t.signal),t.signal?.aborted)return h("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(n);if(s=Math.min(o,Math.round(s*1.5)),!p.ok){if(p.reason==="connection")continue;return p}n=p.data,li(n.Status)||t.onUpdate?.(n);}return B(n)}pollFor(e){switch(e.Modality){case en.Text:return this.getText(e.GenerationID);case en.Image:return this.getImage(e.GenerationID);case en.Audio:return this.getAudio(e.GenerationID);case en.Music:return this.getMusic(e.GenerationID);case en.Video:return this.getVideo(e.GenerationID);case en.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,n,i){if(!e)return h("client","FeatureKey is required.");let s=n?.relatedEntityID;if(s!==void 0&&!HS.test(s))return h("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,Variables:n?.variables,Params:n?.params,Context:n?.context,RelatedEntityID:s??F()},p=await i(o);return p.ok&&!p.data.CreditsConfirmation&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return h("client","GenerationID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.GenerationID=e;let i=await t(n);return i.ok&&(await this.reconcileCharge(i.data,false),this.emitView(i.data)),i}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===fn.Completed&&!this.rewarded.has(e.GenerationID)&&(this.rewarded.add(e.GenerationID),await this.ctx.userService.getUserInventory()),!(!t||!e.Charge||this.charged.has(e.GenerationID))&&(this.charged.add(e.GenerationID),this.ctx.data.user.applyResourceOperation(e.Charge,this.ctx.data.config.itemDefinitions));}emitView(e){this.ctx.emitter.emit("ai:generationUpdated",e),e.Status===fn.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===fn.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var ja="Collection",Zs=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let n=e.cache.configSection(ja),i=Object.keys(n?.Collections??{});if(i.length===0||t)return false;let s=e.cache.configSection("Season");return Object.values(s?.Chains??{}).some(p=>(p?.Seasons??[]).some(m=>!!m?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==i[0]},refresh:async()=>{let n=await this.getUserState();return n.ok&&(t=true),n}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ja,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.collection.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(ja,i.data),this.ctx.emitter.emit("collection:definitionsLoaded",i.data)),i}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,n=1,i){let s=this.ctx.auth.context;if(!s)return l;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:n,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${s.userID}_${F()}`},p=await this.ctx.api.collection.openPack(o);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,n=1){let i=this.ctx.auth.context;if(!i)return l;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:n,RelatedEntityID:`open_chest_${e}_${t}_${i.userID}_${F()}`},o=await this.ctx.api.collection.openCollectionChest(s);return o.ok&&(this.ctx.data.user.applyResourcesWithDelta(o.data.Resources,o.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",o.data)),o}async useCollectibleJoker(e,t){let n=this.ctx.auth.context;if(!n)return l;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${n.userID}_${F()}`},s=await this.ctx.api.collection.useCollectibleJoker(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",s.data)),s}async claimSetReward(e,t){let n=this.ctx.auth.context;if(!n)return l;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${n.userID}_${F()}`},s=await this.ctx.api.collection.claimSetReward(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",s.data)),s}async claimSetRewardsBatch(e){if(!e||e.length===0)return h("client","sets is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},n=await this.ctx.api.collection.claimSetRewardsBatch(t);if(n.ok){let i=false;for(let s of n.data)!i&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",n.data);}return n}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${F()}`},i=await this.ctx.api.collection.claimGrandPrize(n);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",i.data)),i}async sendTradeOffer(e,t,n,i,s,o=false){let p=this.ctx.auth.context;if(!p)return l;let m={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:n,ReceiverUserID:i,RequestedCollectibleID:s,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${p.userID}_${i}_${F()}`},g=await this.ctx.api.collection.sendTradeOffer(m);return g.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",g.data)),g}async cancelTradeOffer(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${F()}`},n=await this.ctx.api.collection.cancelTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",n.data)),n}async acceptTradeOffer(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${F()}`},n=await this.ctx.api.collection.acceptTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",n.data)),n}async declineTradeOffer(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${F()}`},n=await this.ctx.api.collection.declineTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",n.data)),n}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return l;t.CollectionID=e;let n=await this.ctx.api.collection.getMyTradeOffers(t);return n.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",n.data),n}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return l;t.CollectionID=e;let n=await this.ctx.api.collection.getIncomingTradeOffers(t);return n.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",n.data),n}};var ZS=zod.z.object({}).passthrough().transform(r=>r),YS={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},XS={Active:"Active",Left:"Left",Replaced:"Replaced"},eb=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),tb=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ne.nullish(),BuildObjectsProgress:eb.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),nb=zod.z.object({Index:zod.z.number().nullish(),OwnerUserID:zod.z.string().nullish(),CurrentProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish(),IsCompleted:zod.z.boolean().nullish()}).passthrough(),ib=zod.z.object({Objects:zod.z.array(nb).nullish()}).passthrough(),Hp=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CoopChainID:zod.z.string().nullish(),CoopEventID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),Members:zod.z.array(tb).nullish(),BuildObjectsState:ib.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),Kp=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>Qp).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),sb=zod.z.string(),Wa=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Weight:zod.z.number().nullish(),MinProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish()}).passthrough(),rb=zod.z.object({Index:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxProgress:zod.z.number().nullish(),CompletionReward:$.nullish()}).passthrough(),ob=zod.z.object({Objects:zod.z.array(rb).nullish(),PriceOptions:de.nullish(),SpinnerTable:zod.z.array(Wa).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),Qp=zod.z.object({CoopEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),EventType:sb.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:ob.nullish(),GrandPrize:$.nullish()}).passthrough(),ab=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Ce.nullish(),Events:zod.z.array(Qp).nullish(),Gate:ee.nullish()}).passthrough(),Ys=zod.z.object({ServerTimeUtc:u.nullish(),UserState:ZS.nullish(),ActiveGroup:Hp.nullish()}),Ha=zod.z.object({ServerTimeUtc:u.nullish(),Group:Hp.nullish(),SecondsRemaining:Q.nullish()}),$p=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Resources:O.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:Wa.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(Wa).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:Q.nullish(),MaxProgress:Q.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),Ka=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Jp=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Xs=zod.z.object({Chains:zod.z.record(zod.z.string(),ab).nullish()}).passthrough(),vt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Zp="CoopEvent",Yp={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},er=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Yp,{schema:Ys,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Zp,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.coopEvent.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Zp,i.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",i.data)),i}async getActiveEvent(e){if(!e)return h("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.CoopChainID=e;let n=await this.ctx.api.coopEvent.getActiveEvent(t);return n.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",n.data),n}getUserState(e){return this.ctx.cache.read(Yp,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return h("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.GroupID=e;let n=await this.ctx.api.coopEvent.getGroupState(t);return n.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",n.data),n}async joinOrCreateGroup(e){if(!e)return h("client","CoopChainID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},n=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(n.ok){let i=n.data.Group;i&&this.ctx.data.user.patchCoopEventActiveGroup(i.GroupID??null,i.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",n.data);}return n}async spin(e,t,n=1,i,s){if(!e||!t)return h("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:n,SelectedOptionID:i,CreditsConfirmationID:s,RelatedEntityID:F()},p=await this.ctx.api.coopEvent.spin(o);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(p.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",p.data)),p}async claimObjectReward(e){if(!e)return h("client","GroupID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.claimObjectReward(t);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",n.data)),n}async claimGrandPrize(e){if(!e)return h("client","GroupID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.claimGrandPrize(t);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",n.data)),n}async leaveGroup(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.leaveGroup(t);return n.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",n.data)),n}};var lb={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},ub={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},cb=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:u.nullish(),CompletedAtUtc:u.nullish(),LastExecutedAtUtc:u.nullish(),NextAvailableAtUtc:u.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),pb=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),Xp=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:u.nullish(),ExhaustedAtUtc:u.nullish(),ExpiredAtUtc:u.nullish(),DismissedAtUtc:u.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:u.nullish(),Nodes:zod.z.record(zod.z.string(),cb).nullish(),Tracks:zod.z.record(zod.z.string(),pb).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),hb=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:u.nullish(),ActiveOfferExpiresAtUtc:u.nullish(),ActiveOffer:Xp.nullish(),NextCycleStartsAtUtc:u.nullish(),LastUpdatedUtc:u.nullish(),DismissSkipAvailableAtUtc:u.nullish(),LastDismissedAtUtc:u.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),db=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),mb=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:u.nullish(),LastActivatedAtUtc:u.nullish(),LastExhaustedAtUtc:u.nullish(),NodeCounts:zod.z.record(zod.z.string(),db).nullish()}).passthrough(),fb=zod.z.object({Slots:zod.z.record(zod.z.string(),hb).nullish(),OfferHistory:zod.z.record(zod.z.string(),mb).nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),gb={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},yb={Eq:"Eq",Gte:"Gte",Lte:"Lte"},Rb=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),tr=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),eh=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),th=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),Cb=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Behaviour:J.nullish()}).passthrough(),Sb=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:tr.nullish(),Availability:eh.nullish(),Behaviour:th.nullish(),Queue:zod.z.array(Rb).nullish(),Presets:Cb.nullish()}).passthrough(),bb=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),xb=zod.z.object({RewardedVideo:bb.nullish()}).passthrough(),Db=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),Ib=zod.z.object({Identity:J.nullish(),Graph:J.nullish(),Milestones:J.nullish()}).passthrough(),Pb=zod.z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish()}).passthrough(),vb=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),Ab=zod.z.object({TrackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),StartValue:zod.z.number().nullish(),MinValue:zod.z.number().nullish(),MaxValue:zod.z.number().nullish(),ClampToMin:zod.z.boolean().nullish(),ClampToMax:zod.z.boolean().nullish(),HiddenFromUI:zod.z.boolean().nullish()}).passthrough(),Tb=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(Db).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),nh=zod.z.object({Options:de.nullish()}).passthrough(),ih=zod.z.object({Grants:$.nullish(),TrackChanges:zod.z.array(vb).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),wb=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:tr.nullish(),Pricing:nh.nullish(),Reward:ih.nullish(),Action:xb.nullish(),UnlockRules:Tb.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:Pe.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:Pb.nullish()}).passthrough(),sh=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(wb).nullish(),Tracks:zod.z.array(Ab).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),rh=zod.z.object({Milestones:zod.z.record(zod.z.string(),Ve).nullish(),ClaimMode:zod.z.string().nullish(),Token:wt.nullish()}).passthrough(),oh=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:tr.nullish(),Graph:sh.nullish(),Milestones:rh.nullish(),Presets:Ib.nullish()}).passthrough(),kb=zod.z.object({Identity:zod.z.record(zod.z.string(),tr).nullish(),Availability:zod.z.record(zod.z.string(),eh).nullish(),Behaviour:zod.z.record(zod.z.string(),th).nullish(),Graph:zod.z.record(zod.z.string(),sh).nullish(),Milestones:zod.z.record(zod.z.string(),rh).nullish(),Pricing:zod.z.record(zod.z.string(),nh).nullish(),Reward:zod.z.record(zod.z.string(),ih).nullish()}).passthrough(),Qa=zod.z.object({Slots:zod.z.record(zod.z.string(),Sb).nullish(),Offers:zod.z.record(zod.z.string(),oh).nullish(),Presets:kb.nullish()}).passthrough(),ah=zod.z.object({DealOfferDefinitions:Qa.nullish()}),lh=zod.z.object({DealOffers:fb.nullish()}),zb=zod.z.object({EntityID:zod.z.string().nullish(),TotalEarned:zod.z.number().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),ReachedUnclaimedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Mb=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:oh.nullish(),ActivationState:Xp.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:u.nullish(),Cost:Gt.nullish(),Milestone:zb.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),nr=zod.z.object({Slots:zod.z.array(Mb).nullish()}),uh=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),ch=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),ph=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),hh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),dh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Mt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var Ob="DealOffer",mh={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},ir=class{constructor(e){this.ctx=e;e.cache.bindLoginView(mh,{schema:nr,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(Ob,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(mh,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return h("client","SlotID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${F()}`},n=await this.ctx.api.dealOffer.dismissDeal(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",n.data)),n}async executeNode(e,t,n,i){if(!e||!t)return h("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return l;let s=n&&n.trim().length>0?n.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:s??`deal_exec_${e}_${t}_${F()}`},p=await this.ctx.api.dealOffer.executeNode(o);return p.ok&&!p.data.CreditsConfirmation&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return h("client","SlotID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${F()}`},n=await this.ctx.api.dealOffer.recordShow(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",n.data)),n}async claimMilestone(e,t){if(!e||!t)return h("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${F()}`},i=await this.ctx.api.dealOffer.claimMilestone(n);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",i.data)),i}async claimMilestonesBatch(e,t){if(!e)return h("client","SlotID is required.");if(!this.ctx.auth.context)return l;let n=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:n,RelatedEntityID:`deal_milestone_batch_${e}_${F()}`},s=await this.ctx.api.dealOffer.claimMilestonesBatch(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",s.data)),s}};var fh="Referral",sr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(fh,e);if(t){let s={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",s),B(s)}let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.referral.getDefinitions(n);return i.ok&&i.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(fh,i.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",i.data)),i}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=dn.parseReferralCode(e)?.toUpperCase();if(!t)return h("client","ReferralCode is required.");let n=this.ctx.auth.context;if(!n)return l;let i={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${n.userID}`},s=await this.ctx.api.referral.activateReferralCode(i);if(s.ok){let o=s.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID,o.QualificationPending),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return s}async claimInviteReward(e){let t=e.trim();if(!t)return h("client","InviteRewardID is required.");let n=this.ctx.auth.context;if(!n)return l;let i={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${n.userID}`},s=await this.ctx.api.referral.claimInviteReward(i);if(s.ok){let o=s.data;o.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(o.RewardID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",o);}return s}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return h("client","InviteRewardIDs is required.");let n=this.ctx.auth.context;if(!n)return l;let i={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${n.userID}`},s=await this.ctx.api.referral.claimInviteRewardsBatch(i);if(s.ok){let o=s.data;for(let p of o.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return s}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.referral.checkQualification(e);return t.ok&&t.data.Qualification&&!t.data.QualificationPending&&await this.getUserState(),t}async checkQualificationIfPending(){this.ctx.data.user.state?.Referral?.QualificationPending===true&&await this.checkQualification();}};var gh=zod.z.object({ServerTimeUtc:u,SourceType:Tn,SourceID:zod.z.string(),TargetType:Tn,TargetID:zod.z.string(),SourceSpent:Q,FeeAmount:Q,RateApplied:ne,TargetCredited:Q}),yh=zod.z.object({ServerTimeUtc:u,SourceType:Tn,SourceID:zod.z.string(),TargetType:Tn,TargetID:zod.z.string(),SourceSpent:ne,FeeAmount:ne,RateApplied:ne,TargetCredited:ne}),Rh=zod.z.object({ServerTimeUtc:u,SpendID:zod.z.string(),Resources:O.nullish()}),ui={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},Eb={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},Ch=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),qb={Automatic:"Automatic",Manual:"Manual"},Ub=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),Lb=zod.z.object({ValueInUSD:ne.nullish(),ValueInUSDUpdatedAt:u.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),Bb=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),Gb=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),Nb=zod.z.object({TargetCurrencyType:Tn.nullish(),TargetCurrencyID:zod.z.string(),Rate:ne.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),Sh=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:Ub.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(Nb).nullish()}).passthrough(),bh=zod.z.object({CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough(),_b=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:Lb.nullish(),Recharge:Bb.nullish(),Conversion:Sh.nullish(),Permissions:Gb.nullish(),Audit:bh.nullish(),Status:Ch.nullish()}).passthrough(),Fb=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:ne.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),Vb=zod.z.object({DailyWithdrawUsd:ne.nullish(),MonthlyWithdrawUsd:ne.nullish(),KycRequiredAboveUsd:ne.nullish()}).passthrough(),jb=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),Wb=zod.z.object({Mode:zod.z.string().nullish(),FundingNetworkID:zod.z.string().nullish(),PerPlayerDailyTokens:zod.z.number().nullish(),TitleDailyTokens:zod.z.number().nullish(),RefuseOverCap:zod.z.boolean().nullish()}).passthrough(),$a=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),DisplayDecimals:zod.z.number().nullish(),ValueInUSD:ne.nullish(),ValueInUSDUpdatedAt:u.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:ne.nullish(),CommunityMarketingWithdrawalFeePercent:ne.nullish(),WithdrawalBurnPercent:ne.nullish(),PlayerTradeFeePercent:ne.nullish(),TradeShareCommunityMarketingPercent:ne.nullish(),Networks:zod.z.array(Fb).nullish(),Limits:Vb.nullish(),Permissions:jb.nullish(),Conversion:Sh.nullish(),Audit:bh.nullish(),Status:Ch.nullish(),ServerGrantPolicy:Wb.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),Hb=zod.z.object({SpendID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),PriceOptions:zod.z.record(zod.z.string(),ls).nullish()}).passthrough(),rr=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),_b).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),$a).nullish(),Spends:zod.z.record(zod.z.string(),Hb).nullish()}).passthrough(),Kb={Marketplace:"Marketplace",MailboxTransfer:"MailboxTransfer",Match:"Match",Workshop:"Workshop"},Qb={Pending:"Pending",Released:"Released",Voided:"Voided"},Rt=zod.z.object({PayoutID:zod.z.string().nullish(),Source:zod.z.string().nullish(),SourceRefID:zod.z.string().nullish(),Status:zod.z.enum(["Pending","Released","Voided"]).catch("Pending").nullish(),Amount:pe.nullish(),CreatedAt:u.nullish(),ReleaseAt:u.nullish(),ReturnedGoods:pe.nullish(),GoodsReturned:zod.z.boolean().nullish()}).passthrough(),xh=zod.z.object({Pending:zod.z.array(Rt).nullish(),Released:zod.z.array(Rt).nullish(),Voided:zod.z.array(Rt).nullish()}).passthrough();var $b={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Dh=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),Jb={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},Zb=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),Yb={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},Xb=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),ct={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},ex={Disabled:"MAILBOX_DISABLED",MessageNotFound:"MESSAGE_NOT_FOUND",MessageIDRequired:"MESSAGE_ID_REQUIRED",AlreadyClaimed:"ALREADY_CLAIMED",Expired:"EXPIRED",NoRewards:"NO_REWARDS",HasUnclaimedRewards:"HAS_UNCLAIMED_REWARDS",NotFriends:"NOT_FRIENDS",Blocked:"BLOCKED",RecipientNotFound:"RECIPIENT_NOT_FOUND",CannotGiftSelf:"CANNOT_GIFT_SELF",GiftNotFound:"GIFT_NOT_FOUND",GiftNotAllowed:"GIFT_NOT_ALLOWED",AlreadySent:"ALREADY_SENT",SendLimit:"SEND_LIMIT",NotEnoughResources:"NOT_ENOUGH_RESOURCES",AmountTooSmall:"AMOUNT_TOO_SMALL",RecipientLimit:"RECIPIENT_LIMIT",TransferDisabled:"TRANSFER_DISABLED",ResourceNotGiftable:"RESOURCE_NOT_GIFTABLE",AmountTooLarge:"AMOUNT_TOO_LARGE",AmountInvalid:"AMOUNT_INVALID",TooManyEntries:"TOO_MANY_ENTRIES",EntriesRequired:"ENTRIES_REQUIRED",FriendshipTooNew:"FRIENDSHIP_TOO_NEW",RequestIDRequired:"RELATED_ENTITY_ID_REQUIRED",CryptoForbidden:"CRYPTO_FORBIDDEN",ModuleRewardUnavailable:"MODULE_REWARD_UNAVAILABLE",Conflict:"CONFLICT"},tx=100,nx=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),Ih=zod.z.object({FeatureID:zod.z.string().nullish(),Args:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Url:zod.z.string().nullish(),Label:zod.z.string().nullish()}).passthrough(),ix=zod.z.object({Texts:zod.z.record(zod.z.string(),nx).nullish(),Category:Dh.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:Ih.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),sx=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:pe.nullish(),Cost:pe.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),SenderGate:ee.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),rx=zod.z.object({Type:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxAmountPerGift:zod.z.number().nullish()}).passthrough(),ox=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(rx).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),AllowItemInstances:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:pe.nullish(),SenderGate:ee.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),Ph=zod.z.object({Enabled:zod.z.boolean().nullish(),Capacity:zod.z.number().nullish(),RewardLetterDays:zod.z.number().nullish(),PlainLetterDays:zod.z.number().nullish(),ClaimedRetentionDays:zod.z.number().nullish(),DefaultLanguage:zod.z.string().nullish(),Templates:zod.z.record(zod.z.string(),ix).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),sx).nullish(),Transfer:ox.nullish()}).passthrough().nullish(),Integrations:zod.z.object({Leaderboard:zod.z.boolean().nullish(),CoopEvent:zod.z.boolean().nullish(),Season:zod.z.boolean().nullish(),Referral:zod.z.boolean().nullish()}).passthrough().nullish()}).passthrough(),ax=zod.z.object({MessageID:zod.z.string(),Source:Zb,Category:Dh,TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:Ih.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:$.nullish(),Instances:zod.z.array(Mn).nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:u,ExpiresAt:u.nullish(),ReadAt:u.nullish(),ClaimedAt:u.nullish()}).passthrough(),lx=zod.z.object({MessageID:zod.z.string(),Module:Xb,Key:zod.z.string(),TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:$.nullish()}).passthrough(),Ja=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),vh=zod.z.object({ServerTimeUtc:u.nullish(),Messages:zod.z.array(ax).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(lx).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),or=zod.z.object({ServerTimeUtc:u.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Za=zod.z.object({ServerTimeUtc:u.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(Ja).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),ux=zod.z.object({MessageID:zod.z.string(),Rewards:pe.nullish(),Instances:zod.z.array(Mn).nullish(),HeldPayout:Rt.nullish()}).passthrough(),ar=zod.z.object({ServerTimeUtc:u.nullish(),Claimed:zod.z.array(ux).default([]),Failed:zod.z.array(Ja).default([]),Resources:O.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Ah=zod.z.object({ServerTimeUtc:u.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(Ja).default([]),Resources:O.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough(),Th=zod.z.object({ServerTimeUtc:u.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish(),RecipientReceives:pe.nullish(),RecipientInstances:zod.z.array(Mn).nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),wh=zod.z.object({ServerTimeUtc:u.nullish(),ResetsAt:u.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:u.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough().nullish()}).passthrough();var Ya="Mailbox",Xa={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},lr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Xa,{schema:or,apply:t=>this.emitCounters(t)});}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}emitCounters(e){if(e.UnreadCount==null||e.UnclaimedCount==null)return;let t={UnreadCount:e.UnreadCount,UnclaimedCount:e.UnclaimedCount};this.ctx.cache.put(Xa,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Ya)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Ya,e);if(t)return B(t);let n=this.request();if(!n)return l;let i=await this.ctx.api.mailbox.getDefinitions(n);return i.ok&&this.ctx.data.config.patchSection(Ya,i.data),i}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return l;let n=await this.ctx.api.mailbox.getMessages(t);return n.ok&&(this.emitCounters(n.data),this.ctx.emitter.emit("mailbox:messagesLoaded",n.data)),n}getUnreadCount(e){return this.ctx.cache.read(Xa,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return l;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return l;let n=await this.ctx.api.mailbox.readMessages(t);return n.ok&&this.emitCounters(n.data),n}async claimReward(e){let t=e?.trim();if(!t)return h("client","MessageID is required.");let n=this.request({MessageID:t});return n?this.afterClaim(await this.ctx.api.mailbox.claimReward(n)):l}async claimRewards(e){let t=(e??[]).map(i=>i?.trim()).filter(Boolean);if(t.length===0)return h("client","MessageIDs are required.");let n=this.request({MessageIDs:t});return n?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(n)):l}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):l}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let n=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!n)return l;let i=await this.ctx.api.mailbox.deleteMessages(n);return i.ok&&this.emitCounters(i.data),i}async sendGift(e,t){if(!e?.trim())return h("client","GiftID is required.");let n=(t??[]).filter(Boolean);if(n.length===0)return h("client","Recipients are required.");let i=this.request({GiftID:e.trim(),RecipientUserIDs:n});if(!i)return l;let s=await this.ctx.api.mailbox.sendGift(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",s.data)),s}async sendTransfer(e,t,n){if(!e?.trim())return h("client","RecipientUserID is required.");if(!n?.requestID?.trim())return h("client","requestID is required.");let i=this.request({RecipientUserID:e.trim(),TransferEntries:t,TransferInstanceIDs:n.instanceIDs?.length?n.instanceIDs:void 0,Note:n.note,RelatedEntityID:n.requestID.trim()});if(!i)return l;let s=await this.ctx.api.mailbox.sendTransfer(i);return s.ok&&(s.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(s.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",s.data)),s}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):l}};var cx={Head:"Head",Torso:"Torso",Legs:"Legs"},ur=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),px={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},el=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),zh=zod.z.object({AttackTarget:ur,DefenseTarget:ur});var hx=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),dx=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:ur.nullish(),DefenseZone:ur.nullish(),HitType:hx.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),mx=zod.z.object({MaxHp:zod.z.number().nullish(),CurrentHp:zod.z.number().nullish(),Damage:zod.z.number().nullish(),AttackSpeed:zod.z.number().nullish(),CritChance:zod.z.number().nullish(),CritMultiplier:zod.z.number().nullish(),Armor:zod.z.number().nullish(),DodgeChance:zod.z.number().nullish()}).passthrough(),fx=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),kh=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:ai.nullish(),BattleStrategy:zod.z.array(zh).nullish(),UnstackableItems:zod.z.record(zod.z.string(),fx).nullish(),Stats:mx.nullish()}).passthrough(),ci=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:pe.nullish(),NetReward:pe.nullish(),BattleLog:zod.z.array(dx).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:kh.nullish(),P2BattleProfile:kh.nullish()}).passthrough(),Mh=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:u.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(zh).nullish(),TargetUserID:zod.z.string().nullish(),Entry:pe.nullish(),CreationCostPaid:pe.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:u.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:u.nullish(),Status:el.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:u.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:u.nullish()}).passthrough(),Oh=zod.z.object({Status:el,MatchID:zod.z.string(),Entry:pe.nullish(),Resources:O.nullish()}),Eh=zod.z.object({Match:Mh.nullish()}),qh=zod.z.object({MatchID:zod.z.string(),Status:el,Resources:O.nullish()}),Uh=zod.z.object({Battle:ci.nullish(),Resources:O.nullish(),ResourcesDual:Nt.nullish(),HeldPayout:Rt.nullish()}),tl=zod.z.object({Matches:zod.z.array(Mh).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),Ot={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var gx=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var yx=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),Rx=zod.z.object({HealthStatID:zod.z.string().nullish(),DamageStatID:zod.z.string().nullish(),ArmorStatID:zod.z.string().nullish(),AttackSpeedStatID:zod.z.string().nullish(),CritChanceStatID:zod.z.string().nullish(),CritDamageStatID:zod.z.string().nullish(),DodgeStatID:zod.z.string().nullish(),AllMightStatID:zod.z.string().nullish()}).passthrough(),Cx=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),Sx=zod.z.object({MaxRounds:zod.z.number().nullish(),BlockDamageMultiplier:zod.z.number().nullish(),MinHitDamage:zod.z.number().nullish(),DefaultCritMultiplier:zod.z.number().nullish(),MaxCritChance:zod.z.number().nullish(),MaxDodgeChance:zod.z.number().nullish(),ArmorMode:Cx.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),bx=zod.z.object({Kind:yx.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Je.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),xx=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(bx).nullish()}).passthrough(),gn=zod.z.object({Terms:zod.z.array(xx).nullish()}).passthrough(),Dx=zod.z.object({Health:gn.nullish(),Damage:gn.nullish(),Armor:gn.nullish(),AttackSpeed:gn.nullish(),CritChance:gn.nullish(),CritDamage:gn.nullish(),Dodge:gn.nullish()}).passthrough(),Lh=zod.z.object({StatMapping:Rx.nullish(),Combat:Sx.nullish(),Formula:Dx.nullish()}).passthrough(),Ix=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),pi=zod.z.object({Kind:gx.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:ki.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),Bh=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(pi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Gh=zod.z.object({PriceOptions:de.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:Pe.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),Px=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:Ix.nullish(),Entry:Bh.nullish(),Creation:Gh.nullish(),Settings:Lh.nullish()}).passthrough(),vx=zod.z.object({Rules:zod.z.record(zod.z.string(),Px).nullish(),Defaults:Lh.nullish(),EntryDefaults:Bh.nullish(),CreationDefaults:Gh.nullish()}).passthrough(),nl=zod.z.object({InstantBattle:vx.nullish()}).passthrough(),Nh=nl;var Ax={Open:"Open",Request:"Request",InviteOnly:"InviteOnly"},Tx=zod.z.enum(["Open","Request","InviteOnly"]).catch("Open"),wx={Application:"Application",Invite:"Invite"},kx={Invite:"invite",ManageApplications:"manage_applications",Kick:"kick",SetRole:"set_role",EditInfo:"edit_info",EditAnnouncement:"edit_announcement",ModerateChat:"moderate_chat",CreateRequest:"create_request",SpendTreasury:"spend_treasury",ManageProjects:"manage_projects",StartActivity:"start_activity",SelectQuests:"select_quests"},Le={GetDefinitions:"GetDefinitions",GetMyClans:"GetMyClans",SearchClans:"SearchClans",GetRecommendedClans:"GetRecommendedClans",GetClan:"GetClan",GetClanMembers:"GetClanMembers",GetRankings:"GetRankings",CreateClan:"CreateClan",UpdateClan:"UpdateClan",DisbandClan:"DisbandClan",JoinClan:"JoinClan",ApplyToClan:"ApplyToClan",CancelApplication:"CancelApplication",GetApplications:"GetApplications",AcceptApplication:"AcceptApplication",RejectApplication:"RejectApplication",InvitePlayer:"InvitePlayer",GetMyInvites:"GetMyInvites",AcceptInvite:"AcceptInvite",DeclineInvite:"DeclineInvite",LeaveClan:"LeaveClan",KickMember:"KickMember",SetMemberRole:"SetMemberRole",TransferLeadership:"TransferLeadership",GetClanLog:"GetClanLog",CreateRequest:"CreateRequest",Donate:"Donate",Help:"Help",ClaimRequest:"ClaimRequest",GetRequests:"GetRequests",GetGifts:"GetGifts",ClaimGift:"ClaimGift",ClaimAllGifts:"ClaimAllGifts",GetRewards:"GetRewards",ClaimRewards:"ClaimRewards",GetTreasury:"GetTreasury",DepositToTreasury:"DepositToTreasury",BuyTreasuryPurchase:"BuyTreasuryPurchase",GetProjects:"GetProjects",ContributeToProject:"ContributeToProject",SetRecommendedProject:"SetRecommendedProject",GetActivities:"GetActivities",StartActivity:"StartActivity",SubmitActivityScore:"SubmitActivityScore",ClaimActivityRewards:"ClaimActivityRewards",GetClanQuests:"GetClanQuests",SelectClanQuests:"SelectClanQuests",TakeClanQuest:"TakeClanQuest",AbandonClanQuest:"AbandonClanQuest",ClaimClanQuestRewards:"ClaimClanQuestRewards",GetCompetitions:"GetCompetitions",RegisterForCompetition:"RegisterForCompetition",GetBracket:"GetBracket",ClaimCompetitionRewards:"ClaimCompetitionRewards",StartWarAttack:"StartWarAttack",GetDiplomacy:"GetDiplomacy",SetDiplomacy:"SetDiplomacy",GetRevenges:"GetRevenges",TakeRevenge:"TakeRevenge",GetLeague:"GetLeague",ClaimSeasonReward:"ClaimSeasonReward"},zx={Disabled:"CLAN_DISABLED",UnknownKind:"CLAN_UNKNOWN_KIND",KindRequired:"CLAN_KIND_REQUIRED",NotFound:"CLAN_NOT_FOUND",NotMember:"CLAN_NOT_MEMBER",AlreadyInClan:"CLAN_ALREADY_IN_CLAN",Full:"CLAN_FULL",NoPermission:"CLAN_NO_PERMISSION",RankTooLow:"CLAN_RANK_TOO_LOW",RoleFull:"CLAN_ROLE_FULL",UnknownRole:"CLAN_UNKNOWN_ROLE",NameTaken:"CLAN_NAME_TAKEN",TagTaken:"CLAN_TAG_TAKEN",NameInvalid:"CLAN_NAME_INVALID",TagInvalid:"CLAN_TAG_INVALID",TextInvalid:"CLAN_TEXT_INVALID",TextBlocked:"CLAN_TEXT_BLOCKED",GateFailed:"CLAN_GATE_FAILED",RequirementsNotMet:"CLAN_REQUIREMENTS_NOT_MET",JoinModeMismatch:"CLAN_JOIN_MODE_MISMATCH",JoinCooldown:"CLAN_JOIN_COOLDOWN",RejoinCooldown:"CLAN_REJOIN_COOLDOWN",TooManyApplications:"CLAN_TOO_MANY_APPLICATIONS",ApplicationNotFound:"CLAN_APPLICATION_NOT_FOUND",InviteNotFound:"CLAN_INVITE_NOT_FOUND",PlayerNotFound:"CLAN_PLAYER_NOT_FOUND",LeaderMustTransfer:"CLAN_LEADER_MUST_TRANSFER",CannotTargetSelf:"CLAN_CANNOT_TARGET_SELF",KickLimit:"CLAN_KICK_LIMIT",RenameCooldown:"CLAN_RENAME_COOLDOWN",InvalidArgument:"CLAN_INVALID_ARGUMENT",FeatureDisabled:"CLAN_FEATURE_DISABLED",RequestNotFound:"CLAN_REQUEST_NOT_FOUND",RequestClosed:"CLAN_REQUEST_CLOSED",RequestCooldown:"CLAN_REQUEST_COOLDOWN",RequestLimit:"CLAN_REQUEST_LIMIT",RequestFilled:"CLAN_REQUEST_FILLED",DonateLimit:"CLAN_DONATE_LIMIT",AlreadyHelped:"CLAN_ALREADY_HELPED",NothingToClaim:"CLAN_NOTHING_TO_CLAIM",GiftNotFound:"CLAN_GIFT_NOT_FOUND",TenureRequired:"CLAN_TENURE_REQUIRED",Conflict:"CLAN_CONFLICT",SystemCapReached:"CLAN_SYSTEM_CAP_REACHED",ItemNotAllowed:"CLAN_ITEM_NOT_ALLOWED",ItemLevelTooHigh:"CLAN_ITEM_LEVEL_TOO_HIGH",ItemEquipped:"CLAN_ITEM_EQUIPPED",ItemWrongLevel:"CLAN_ITEM_WRONG_LEVEL",NotEnoughTreasury:"CLAN_NOT_ENOUGH_TREASURY",DepositLimit:"CLAN_DEPOSIT_LIMIT",PurchaseNotFound:"CLAN_PURCHASE_NOT_FOUND",BuffActive:"CLAN_BUFF_ACTIVE",LevelTooLow:"CLAN_LEVEL_TOO_LOW",ProjectNotFound:"CLAN_PROJECT_NOT_FOUND",ProjectLocked:"CLAN_PROJECT_LOCKED",ProjectMaxed:"CLAN_PROJECT_MAXED",ContributeLimit:"CLAN_CONTRIBUTE_LIMIT",ActivityNotFound:"CLAN_ACTIVITY_NOT_FOUND",ActivityNotActive:"CLAN_ACTIVITY_NOT_ACTIVE",ActivityRunning:"CLAN_ACTIVITY_RUNNING",ActivityCooldown:"CLAN_ACTIVITY_COOLDOWN",NoAttempts:"CLAN_NO_ATTEMPTS",ScoreRejected:"CLAN_SCORE_REJECTED",BossDefeated:"CLAN_BOSS_DEFEATED",BoardNotFound:"CLAN_BOARD_NOT_FOUND",QuestNotFound:"CLAN_QUEST_NOT_FOUND",QuestFull:"CLAN_QUEST_FULL",TakeLimit:"CLAN_TAKE_LIMIT",QuestNotTaken:"CLAN_QUEST_NOT_TAKEN",QuestDone:"CLAN_QUEST_DONE",AbandonCooldown:"CLAN_ABANDON_COOLDOWN",SelectionLocked:"CLAN_SELECTION_LOCKED",ClaimAfterEnd:"CLAN_CLAIM_AFTER_END",NotEligible:"CLAN_NOT_ELIGIBLE",ClaimExpired:"CLAN_CLAIM_EXPIRED",CompetitionNotFound:"CLAN_COMPETITION_NOT_FOUND",CompetitionNotActive:"CLAN_COMPETITION_NOT_ACTIVE",RegistrationClosed:"CLAN_REGISTRATION_CLOSED",NotRegistered:"CLAN_NOT_REGISTERED",TooFewMembers:"CLAN_TOO_FEW_MEMBERS",WarPreparation:"CLAN_WAR_PREPARATION",NotInRoster:"CLAN_NOT_IN_ROSTER",TargetInvalid:"CLAN_TARGET_INVALID",AttackPending:"CLAN_ATTACK_PENDING",AttackNotFound:"CLAN_ATTACK_NOT_FOUND",AttackExpired:"CLAN_ATTACK_EXPIRED",RelationExists:"CLAN_RELATION_EXISTS",RelationLimit:"CLAN_RELATION_LIMIT",RelationNotFound:"CLAN_RELATION_NOT_FOUND",RelationDisabled:"CLAN_RELATION_DISABLED"},Mx={Duel:"Duel",Battle:"Battle",League:"League",War:"War"},Ox={Ally:"Ally",Pact:"Pact",Enemy:"Enemy",None:"None"},cr="clan",yn=zod.z.array(zod.z.string()).nullish(),Z=zod.z.number().nullish(),Ex=zod.z.record(zod.z.string(),zod.z.number()).nullish(),qx=zod.z.object({NounKey:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SortOrder:Z}).passthrough(),Ux=zod.z.object({NameMinLength:Z,NameMaxLength:Z,TagRequired:zod.z.boolean().nullish(),TagMinLength:Z,TagMaxLength:Z,DescriptionMaxLength:Z,AnnouncementMaxLength:Z,Emblem:zod.z.object({Backgrounds:yn,Symbols:yn,Colors:yn}).passthrough().nullish(),Languages:yn,Attributes:zod.z.record(zod.z.string(),zod.z.object({NameKey:zod.z.string().nullish(),Values:yn,Required:zod.z.boolean().nullish()}).passthrough()).nullish(),RenameCooldownHours:Z}).passthrough(),Lx=zod.z.object({BaseCapacity:Z,JoinModes:zod.z.array(zod.z.string()).nullish(),DefaultJoinMode:zod.z.string().nullish(),ApplicationHours:Z,InviteHours:Z,JoinCooldownHours:Z,TenureHoursForRewards:Z,NoBoardAttacksOnClanmates:zod.z.boolean().nullish(),SuggestJoinAfterHours:Z,KickInactiveDays:Z}).passthrough(),Bx=zod.z.object({Rank:zod.z.number().catch(0),NameKey:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),MaxCount:Z,Permissions:yn}).passthrough(),Gx=zod.z.object({Enabled:zod.z.boolean().nullish(),Type:zod.z.string().catch("Resource"),NameKey:zod.z.string().nullish(),CooldownMinutes:Z,LifetimeHours:Z,MaxOpenPerMember:Z,Resources:zod.z.array(Tt.passthrough()).nullish(),Funding:zod.z.string().nullish(),MaxPerDonor:Z,MaxHelps:Z,MaxItemLevel:Z,MinMembershipHoursToDonate:Z}).passthrough(),Nx=zod.z.object({Enabled:zod.z.boolean().nullish(),Identity:qx.nullish(),Create:Ux.nullish(),Membership:Lx.nullish(),Roles:zod.z.object({Roles:zod.z.record(zod.z.string(),Bx).nullish(),LeaderRoleID:zod.z.string().nullish(),DefaultRoleID:zod.z.string().nullish()}).passthrough().nullish(),Rankings:zod.z.object({Metrics:yn,ByLanguage:zod.z.boolean().nullish(),ByRegion:zod.z.boolean().nullish()}).passthrough().nullish(),Counters:zod.z.record(zod.z.string(),zod.z.object({}).passthrough()).nullish(),Progression:zod.z.object({}).passthrough().nullish(),Requests:zod.z.record(zod.z.string(),Gx).nullish(),Gifts:zod.z.object({Gifts:zod.z.record(zod.z.string(),zod.z.object({}).passthrough()).nullish(),ShowSender:zod.z.boolean().nullish()}).passthrough().nullish(),Treasury:zod.z.object({Currencies:zod.z.record(zod.z.string(),zod.z.object({NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),Deposits:zod.z.array(zod.z.object({Resource:Tt.passthrough().nullish(),Gives:zod.z.number().catch(1)}).passthrough()).nullish(),DailyDepositCapPerMember:Z,Max:Z}).passthrough()).nullish(),Purchases:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),Cost:Ex,DurationHours:zod.z.number().catch(24),MinClanLevel:Z}).passthrough()).nullish()}).passthrough().nullish(),Projects:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SortOrder:Z,Inputs:zod.z.array(zod.z.object({Resource:Tt.passthrough().nullish(),TreasuryCurrencyID:zod.z.string().nullish(),PointsPerUnit:Z}).passthrough()).nullish()}).passthrough()).nullish(),Activities:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),Type:zod.z.string().catch("Goal"),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish()}).passthrough()).nullish(),Quests:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),Mode:zod.z.string().catch("Shared"),NameKey:zod.z.string().nullish()}).passthrough()).nullish(),Competitions:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),Type:zod.z.string().catch("Battle"),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),Registration:zod.z.string().nullish(),MinMembers:Z,BracketSize:Z,Phases:zod.z.array(zod.z.object({DurationHours:zod.z.number().catch(24),NameKey:zod.z.string().nullish()}).passthrough()).nullish(),War:zod.z.object({AttacksPerMember:Z,MaxStars:Z,RosterSize:Z,PreparationHours:Z,ResultSource:zod.z.string().nullish()}).passthrough().nullish()}).passthrough()).nullish(),Leagues:zod.z.object({StartRating:Z,Tiers:zod.z.array(zod.z.object({LeagueID:zod.z.string(),MinRating:zod.z.number().catch(0),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SeasonReward:$.nullish()}).passthrough()).nullish(),Season:zod.z.object({IntervalSeconds:Z,AnchorUtc:zod.z.string().nullish(),KeepPercent:Z}).passthrough().nullish()}).passthrough().nullish(),Revenge:zod.z.object({Enabled:zod.z.boolean().nullish(),WindowHours:Z,MaxPerMemberPerDay:Z}).passthrough().nullish(),ChatNotices:zod.z.object({Enabled:zod.z.boolean().nullish(),Events:zod.z.array(zod.z.string()).nullish()}).passthrough().nullish(),Diplomacy:zod.z.object({MaxAllies:Z,MaxPacts:Z,MaxEnemies:Z,ProposalHours:Z}).passthrough().nullish()}).passthrough(),_x=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Kinds:zod.z.record(zod.z.string(),Nx).nullish(),RefreshSeconds:Z}).passthrough(),sl=zod.z.record(zod.z.string(),zod.z.string()).nullish(),il=zod.z.record(zod.z.string(),zod.z.number()).nullish(),tn=zod.z.object({ClanID:zod.z.string(),KindID:zod.z.string().catch(cr),Name:zod.z.string().catch(""),Tag:zod.z.string().nullish(),Description:zod.z.string().nullish(),Announcement:zod.z.string().nullish(),Emblem:zod.z.object({Background:zod.z.string().nullish(),Symbol:zod.z.string().nullish(),Color:zod.z.string().nullish()}).passthrough().nullish(),Language:zod.z.string().nullish(),Country:zod.z.string().nullish(),Attributes:sl,JoinMode:Tx,MinPower:Z,MinLevel:Z,LeaderUserID:zod.z.string().nullish(),MemberCount:zod.z.number().catch(0),Capacity:zod.z.number().catch(0),Level:zod.z.number().catch(1),Xp:zod.z.number().catch(0),NextLevelXp:Z,GiftPoints:zod.z.number().catch(0),GiftLevel:zod.z.number().catch(0),Power:zod.z.number().catch(0),Trophies:zod.z.number().catch(0),Counters:il,Perks:il,Modifiers:zod.z.array(zod.z.object({}).passthrough()).nullish(),Treasury:il,RecommendedProjectID:zod.z.string().nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),CreatedAt:u.nullish(),ActiveAt:u.nullish()}).passthrough(),rl=zod.z.object({RoleID:zod.z.string().catch(""),JoinedAt:u.nullish(),Permissions:zod.z.array(zod.z.string()).catch([]),IsLeader:zod.z.boolean().catch(false),ContributionTotal:zod.z.number().catch(0),ContributionToday:zod.z.number().catch(0),ContributionWeek:zod.z.number().catch(0),DonatedTotal:zod.z.number().catch(0),RewardsFrom:u.nullish()}).passthrough(),Fx=zod.z.object({KindID:zod.z.string(),Clan:tn.nullish(),Membership:rl.nullish(),JoinAllowedAt:u.nullish(),InvitesCount:zod.z.number().catch(0),MyApplicationsCount:zod.z.number().catch(0),ClaimableRewards:zod.z.number().catch(0),ClaimableGifts:zod.z.number().catch(0),ClaimableCompetitions:zod.z.number().catch(0),SuggestJoin:zod.z.boolean().catch(false)}).passthrough(),Fh=zod.z.object({ServerTimeUtc:u.nullish(),RefreshSeconds:zod.z.number().catch(30),Kinds:zod.z.array(Fx).catch([])}).passthrough(),ol=zod.z.object({ServerTimeUtc:u.nullish(),Clans:zod.z.array(tn).catch([]),NextCursor:zod.z.string().nullish()}).passthrough(),Vh=zod.z.object({ServerTimeUtc:u.nullish(),Clan:tn,Membership:rl.nullish(),Applied:zod.z.boolean().catch(false)}).passthrough(),jh=zod.z.object({UserID:zod.z.string(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),PlayerLevel:zod.z.number().catch(0),RoleID:zod.z.string().catch(""),JoinedAt:u.nullish(),ActiveAt:u.nullish(),Power:zod.z.number().catch(0),Trophies:zod.z.number().catch(0),ContributionTotal:zod.z.number().catch(0),ContributionWeek:zod.z.number().catch(0),ContributionToday:zod.z.number().catch(0),DonatedTotal:zod.z.number().catch(0)}).passthrough(),Wh=zod.z.object({ServerTimeUtc:u.nullish(),ClanID:zod.z.string().nullish(),Members:zod.z.array(jh).catch([])}).passthrough(),_h=zod.z.object({Rank:zod.z.number().catch(0),Value:zod.z.number().catch(0),Clan:tn}).passthrough(),Hh=zod.z.object({ServerTimeUtc:u.nullish(),Metric:zod.z.string().nullish(),Slice:zod.z.string().nullish(),Rows:zod.z.array(_h).catch([]),Mine:_h.nullish()}).passthrough(),Vx=zod.z.object({ID:zod.z.string(),Type:zod.z.string().catch("Application"),KindID:zod.z.string().nullish(),ClanID:zod.z.string().nullish(),Clan:tn.nullish(),UserID:zod.z.string().nullish(),Player:jh.nullish(),InviterUserID:zod.z.string().nullish(),Message:zod.z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),al=zod.z.object({ServerTimeUtc:u.nullish(),Items:zod.z.array(Vx).catch([])}).passthrough(),jx=zod.z.object({Type:zod.z.string().catch(""),ActorUserID:zod.z.string().nullish(),TargetUserID:zod.z.string().nullish(),Params:sl,At:u.nullish()}).passthrough(),Kh=zod.z.object({ServerTimeUtc:u.nullish(),Entries:zod.z.array(jx).catch([]),NextCursor:zod.z.string().nullish()}).passthrough(),Qh=zod.z.object({RequestID:zod.z.string(),RequestKindID:zod.z.string().catch(""),Type:zod.z.string().catch("Resource"),UserID:zod.z.string().catch(""),Username:zod.z.string().nullish(),Resource:Tt.passthrough().nullish(),ItemLevel:zod.z.number().nullish(),Needed:zod.z.number().catch(0),Filled:zod.z.number().catch(0),Claimed:zod.z.number().catch(0),MyDonation:zod.z.number().catch(0),TaskKey:zod.z.string().nullish(),Helps:zod.z.number().catch(0),MaxHelps:zod.z.number().catch(0),HelpedByMe:zod.z.boolean().catch(false),Status:zod.z.string().catch("Open"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),$h=zod.z.object({ServerTimeUtc:u.nullish(),Requests:zod.z.array(Qh).catch([])}).passthrough(),Wx=zod.z.object({GiftUid:zod.z.string(),GiftID:zod.z.string().catch(""),SenderUserID:zod.z.string().nullish(),Level:zod.z.number().catch(0),Content:$.nullish(),Claimed:zod.z.boolean().catch(false),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),Jh=zod.z.object({ServerTimeUtc:u.nullish(),GiftLevel:zod.z.number().catch(0),GiftPoints:zod.z.number().catch(0),NextGiftLevelPoints:Z,Gifts:zod.z.array(Wx).catch([])}).passthrough(),pr=zod.z.object({Key:zod.z.string(),Source:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),RequiredProgress:zod.z.number().catch(0),Rewards:$.nullish(),ReachedAt:u.nullish(),Claimed:zod.z.boolean().catch(false),Claimable:zod.z.boolean().catch(false),Blocked:zod.z.string().nullish()}).passthrough(),Zh=zod.z.object({ServerTimeUtc:u.nullish(),Rewards:zod.z.array(pr).catch([])}).passthrough(),Yh=zod.z.object({AttackID:zod.z.string(),AttackerUserID:zod.z.string().nullish(),TargetUserID:zod.z.string().nullish(),Status:zod.z.string().catch("Pending"),Stars:zod.z.number().catch(0),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),Xh=zod.z.object({ClanID:zod.z.string(),Clan:tn.nullish(),Relation:zod.z.string().catch("None"),Status:zod.z.string().catch("Active"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),ed=zod.z.object({ServerTimeUtc:u.nullish(),Clan:tn.nullish(),Membership:rl.nullish(),Request:Qh.nullish(),Resources:O.nullish(),Inventory:K.nullish(),Done:zod.z.array(zod.z.string()).nullish(),Failed:sl,WarAttack:Yh.nullish(),WarBattle:ci.nullish(),Relation:Xh.nullish()}).passthrough(),td=zod.z.object({ServerTimeUtc:u.nullish(),Definitions:_x.nullish(),DefaultKindID:zod.z.string().nullish()}).passthrough(),Hx=zod.z.object({Target:zod.z.string().catch(""),Operation:zod.z.string().catch("AddPercent"),Value:zod.z.number().catch(0),Tag:zod.z.string().nullish()}).passthrough(),Kx=zod.z.object({PurchaseID:zod.z.string(),ExpiresAt:u.nullish(),Modifiers:zod.z.array(Hx).nullish()}).passthrough(),Qx=zod.z.object({CurrencyID:zod.z.string().catch(""),Delta:zod.z.number().catch(0),Kind:zod.z.string().nullish(),ActorUserID:zod.z.string().nullish(),RefID:zod.z.string().nullish(),At:u.nullish()}).passthrough(),nd=zod.z.object({ServerTimeUtc:u.nullish(),Balances:zod.z.record(zod.z.string(),zod.z.number()).catch({}),Buffs:zod.z.array(Kx).catch([]),Ledger:zod.z.array(Qx).catch([]),NextCursor:zod.z.string().nullish(),MyDepositsToday:zod.z.record(zod.z.string(),zod.z.number()).catch({})}).passthrough(),$x=zod.z.object({ProjectID:zod.z.string(),Points:zod.z.number().catch(0),Level:zod.z.number().catch(0),MaxLevel:zod.z.number().catch(0),NextLevelPoints:Z,Locked:zod.z.string().nullish(),MyPointsToday:zod.z.number().catch(0),DailyCap:Z,Recommended:zod.z.boolean().catch(false)}).passthrough(),id=zod.z.object({ServerTimeUtc:u.nullish(),RecommendedProjectID:zod.z.string().nullish(),Projects:zod.z.array($x).catch([])}).passthrough(),Jx=zod.z.object({ActivityID:zod.z.string(),Type:zod.z.string().catch("Goal"),Status:zod.z.string().catch("Idle"),InstanceKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),Points:zod.z.number().catch(0),MyPoints:zod.z.number().catch(0),MyPointsToday:zod.z.number().catch(0),BossLevel:zod.z.number().catch(0),BossHp:zod.z.number().catch(0),BossDamage:zod.z.number().catch(0),BossDefeated:zod.z.boolean().catch(false),AttemptsLeft:zod.z.number().catch(0),CanStart:zod.z.boolean().catch(false),StartAllowedAt:u.nullish(),Rewards:zod.z.array(pr).catch([])}).passthrough(),sd=zod.z.object({ServerTimeUtc:u.nullish(),Activities:zod.z.array(Jx).catch([])}).passthrough(),Zx=zod.z.object({ObjectiveID:zod.z.string().catch(""),Target:zod.z.number().catch(0),Progress:zod.z.number().catch(0),MyProgress:zod.z.number().catch(0)}).passthrough(),Yx=zod.z.object({QuestID:zod.z.string(),Identity:zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough().nullish(),Objectives:zod.z.array(Zx).catch([]),Reward:zod.z.object({Grant:$.nullish(),PointsReward:Z}).passthrough().nullish(),ClanXp:Z,Status:zod.z.string().catch("Available"),Takers:zod.z.number().catch(0),MyContribution:zod.z.number().catch(0),Claimable:zod.z.boolean().catch(false),Claimed:zod.z.boolean().catch(false),Blocked:zod.z.string().nullish()}).passthrough(),Xx=zod.z.object({BoardID:zod.z.string(),Mode:zod.z.string().catch("Shared"),CycleKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),Ended:zod.z.boolean().catch(false),Points:zod.z.number().catch(0),MyPoints:zod.z.number().catch(0),MyTaken:zod.z.number().catch(0),MaxTaken:zod.z.number().catch(0),TakeAllowedAt:u.nullish(),SelectedBy:zod.z.string().nullish(),CanSelect:zod.z.boolean().catch(false),Quests:zod.z.array(Yx).catch([]),Rewards:zod.z.array(pr).catch([])}).passthrough(),rd=zod.z.object({ServerTimeUtc:u.nullish(),Boards:zod.z.array(Xx).catch([])}).passthrough(),eD=zod.z.object({CompetitionID:zod.z.string(),Type:zod.z.string().catch("Battle"),Status:zod.z.string().catch("Idle"),InstanceKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),PhaseIndex:Z,PhaseEndsAt:u.nullish(),Registered:zod.z.boolean().catch(false),CanRegister:zod.z.boolean().catch(false),RegisterBlocked:zod.z.string().nullish(),RegistrationClosesAt:u.nullish(),BracketID:zod.z.string().nullish(),ClansInBracket:zod.z.number().catch(0),Score:zod.z.number().catch(0),Place:Z,Finalized:zod.z.boolean().catch(false),NoContest:zod.z.boolean().catch(false),RatingDelta:Z,MyPoints:zod.z.number().catch(0),MyPointsToday:zod.z.number().catch(0),AttacksLeft:Z,InRoster:zod.z.boolean().nullish(),AttacksFrom:u.nullish(),Rewards:zod.z.array(pr).catch([])}).passthrough(),od=zod.z.object({ServerTimeUtc:u.nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),Competitions:zod.z.array(eD).catch([])}).passthrough(),tD=zod.z.object({Place:zod.z.number().catch(0),Clan:tn.nullish(),Score:zod.z.number().catch(0),RatingDelta:Z,IsMine:zod.z.boolean().catch(false)}).passthrough(),nD=zod.z.object({UserID:zod.z.string(),ClanID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Power:zod.z.number().catch(0),BestStars:zod.z.number().catch(0),AttacksUsed:zod.z.number().catch(0)}).passthrough(),ad=zod.z.object({ServerTimeUtc:u.nullish(),BracketID:zod.z.string().nullish(),CompetitionID:zod.z.string().nullish(),Type:zod.z.string().catch("Battle"),InstanceKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),Finalized:zod.z.boolean().catch(false),NoContest:zod.z.boolean().catch(false),Rows:zod.z.array(tD).catch([]),War:zod.z.array(nD).nullish(),MyAttacks:zod.z.array(Yh).nullish()}).passthrough(),ld=zod.z.object({ServerTimeUtc:u.nullish(),CanManage:zod.z.boolean().catch(false),Relations:zod.z.array(Xh).catch([]),Limits:zod.z.record(zod.z.string(),zod.z.number()).catch({}),Counts:zod.z.record(zod.z.string(),zod.z.number()).catch({})}).passthrough(),iD=zod.z.object({RevengeID:zod.z.string(),VictimUserID:zod.z.string().nullish(),VictimName:zod.z.string().nullish(),AttackerUserID:zod.z.string().nullish(),AttackerName:zod.z.string().nullish(),AttackerAvatarUrl:zod.z.string().nullish(),Action:zod.z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish(),TakenBy:zod.z.string().nullish(),TakenByName:zod.z.string().nullish(),IsMine:zod.z.boolean().catch(false)}).passthrough(),ud=zod.z.object({ServerTimeUtc:u.nullish(),Revenges:zod.z.array(iD).catch([]),TakenToday:zod.z.number().catch(0),DailyLimit:zod.z.number().catch(0)}).passthrough(),sD=zod.z.object({Key:zod.z.string().nullish(),LeagueID:zod.z.string().nullish(),Rating:zod.z.number().catch(0),EndedAt:u.nullish(),Reward:$.nullish(),Claimable:zod.z.boolean().catch(false),Claimed:zod.z.boolean().catch(false)}).passthrough(),cd=zod.z.object({ServerTimeUtc:u.nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),SeasonKey:zod.z.string().nullish(),SeasonEndsAt:u.nullish(),LastSeason:sD.nullish()}).passthrough();var ll="Clan",hr=class{constructor(e){this.ctx=e;}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}get definitions(){return this.ctx.data.config.getSection(ll)}get enabled(){let e=this.definitions;return !e||e.IsEnabled===false?false:Object.values(e.Kinds??{}).some(t=>t?.Enabled!==false)}get kindIDs(){let e=this.definitions?.Kinds??{};return Object.entries(e).filter(([,t])=>t?.Enabled!==false).sort(([,t],[,n])=>(t?.Identity?.SortOrder??0)-(n?.Identity?.SortOrder??0)).map(([t])=>t)}kind(e){return (this.definitions?.Kinds??{})[e??this.kindIDs[0]??cr]}async getDefinitions(e){let t=this.ctx.cache.configSection(ll,e);if(t)return B(t);let n=this.request();if(!n)return l;let i=await this.ctx.api.clan.getDefinitions(n);if(!i.ok)return i;let s=i.data.Definitions??{};return this.ctx.data.config.patchSection(ll,s),B(s)}async getMyClans(){let e=this.request();if(!e)return l;let t=await this.ctx.api.clan.getMyClans(e);return t.ok&&this.ctx.emitter.emit("clan:myClansLoaded",t.data),t}async searchClans(e){let t=this.request({KindID:e?.kindID,Query:e?.query,OnlyOpen:e?.onlyOpen,NotFull:e?.notFull,Language:e?.language,PageSize:e?.pageSize});return t?this.ctx.api.clan.searchClans(t):l}async getRecommendedClans(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRecommendedClans(t):l}async getClan(e,t){if(!e?.trim())return h("client","ClanID is required.");let n=this.request({ClanID:e.trim(),KindID:t});return n?this.ctx.api.clan.getClan(n):l}async getMembers(e,t){let n=this.request({ClanID:e,KindID:t});return n?this.ctx.api.clan.getClanMembers(n):l}async getRankings(e){let t=this.request({KindID:e?.kindID,Metric:e?.metric,Slice:e?.slice,PageSize:e?.pageSize});return t?this.ctx.api.clan.getRankings(t):l}async getApplications(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getApplications(t):l}async getMyInvites(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getMyInvites(t):l}async getLog(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getClanLog(t):l}async getRequests(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRequests(t):l}async getGifts(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getGifts(t):l}async getRewards(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRewards(t):l}async getTreasury(e,t){let n=this.request({KindID:e,Cursor:t});return n?this.ctx.api.clan.getTreasury(n):l}async getProjects(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getProjects(t):l}async getActivities(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getActivities(t):l}async getClanQuests(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getClanQuests(t):l}async getCompetitions(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getCompetitions(t):l}async getBracket(e,t){let n=this.request({CompetitionID:e,BracketID:t?.bracketID,InstanceKey:t?.instanceKey,KindID:t?.kindID});return n?this.ctx.api.clan.getBracket(n):l}async getDiplomacy(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getDiplomacy(t):l}async getRevenges(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRevenges(t):l}async getLeague(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getLeague(t):l}async mutate(e,t){let n=this.request(t);if(!n)return l;let i=await this.ctx.api.clan.mutate(e,n);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("clan:changed",{action:e,...i.data})),i}info(e){return {ClanName:e.name,Tag:e.tag,Description:e.description,Announcement:e.announcement,Emblem:e.emblem,Language:e.language,Attributes:e.attributes,JoinMode:e.joinMode,MinPower:e.minPower,MinLevel:e.minLevel,PriceOptionID:e.priceOptionID}}createClan(e,t){return e?.name?.trim()?this.mutate("CreateClan",{KindID:t,...this.info(e)}):Promise.resolve(h("client","Name is required."))}updateClan(e,t){return this.mutate("UpdateClan",{KindID:t,...this.info(e)})}disbandClan(e){return this.mutate("DisbandClan",{KindID:e})}joinClan(e,t){return this.mutate("JoinClan",{ClanID:e,KindID:t})}applyToClan(e,t,n){return this.mutate("ApplyToClan",{ClanID:e,Message:t,KindID:n})}cancelApplication(e,t){return this.mutate("CancelApplication",{ClanID:e,KindID:t})}acceptApplication(e,t){return this.mutate("AcceptApplication",{TargetUserID:e,KindID:t})}rejectApplication(e,t){return this.mutate("RejectApplication",{TargetUserID:e,KindID:t})}invitePlayer(e,t,n){return this.mutate("InvitePlayer",{TargetUserID:e,Message:t,KindID:n})}acceptInvite(e,t){return this.mutate("AcceptInvite",{ClanID:e,KindID:t})}declineInvite(e,t){return this.mutate("DeclineInvite",{ClanID:e,KindID:t})}leaveClan(e){return this.mutate("LeaveClan",{KindID:e})}kickMember(e,t){return this.mutate("KickMember",{TargetUserID:e,KindID:t})}setMemberRole(e,t,n){return this.mutate("SetMemberRole",{TargetUserID:e,RoleID:t,KindID:n})}transferLeadership(e,t){return this.mutate("TransferLeadership",{TargetUserID:e,KindID:t})}createRequest(e,t){return this.mutate("CreateRequest",{RequestKindID:e,Resource:t?.resource,TaskKey:t?.taskKey,ItemInstanceID:t?.itemInstanceID,KindID:t?.kindID})}donateItems(e,t,n){return this.mutate("Donate",{RequestID:e,ItemInstanceIDs:t,KindID:n})}donate(e,t=1,n){return this.mutate("Donate",{RequestID:e,Amount:t,KindID:n})}help(e,t){return this.mutate("Help",{RequestID:e,KindID:t})}claimRequest(e,t){return this.mutate("ClaimRequest",{RequestID:e,KindID:t})}claimGift(e,t){return this.mutate("ClaimGift",{GiftUid:e,KindID:t})}claimAllGifts(e){return this.mutate("ClaimAllGifts",{KindID:e})}claimRewards(e,t){return this.mutate("ClaimRewards",{RewardKeys:e,KindID:t})}depositToTreasury(e,t,n=1,i){return this.mutate("DepositToTreasury",{CurrencyID:e,PayWith:t,Steps:n,KindID:i,RelatedEntityID:`clan_deposit_${F()}`})}buyTreasuryPurchase(e,t){return this.mutate("BuyTreasuryPurchase",{PurchaseID:e,KindID:t})}contributeToProject(e,t){return this.mutate("ContributeToProject",{ProjectID:e,Amount:t.amount,PayWith:t.payWith,FromTreasury:t.fromTreasury,CurrencyID:t.currencyID,KindID:t.kindID,RelatedEntityID:`clan_project_${F()}`})}setRecommendedProject(e,t){return this.mutate("SetRecommendedProject",{ProjectID:e??void 0,KindID:t})}startActivity(e,t){return this.mutate("StartActivity",{ActivityID:e,KindID:t})}submitActivityScore(e,t,n){return this.mutate("SubmitActivityScore",{ActivityID:e,Score:t,KindID:n})}claimActivityRewards(e){return this.mutate("ClaimActivityRewards",{ActivityID:e?.activityID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}selectClanQuests(e,t,n){return this.mutate("SelectClanQuests",{BoardID:e,QuestIDs:t,KindID:n})}takeClanQuest(e,t,n){return this.mutate("TakeClanQuest",{BoardID:e,QuestID:t,KindID:n})}abandonClanQuest(e,t,n){return this.mutate("AbandonClanQuest",{BoardID:e,QuestID:t,KindID:n})}claimClanQuestRewards(e){return this.mutate("ClaimClanQuestRewards",{BoardID:e?.boardID,QuestID:e?.questID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}registerForCompetition(e,t){return this.mutate("RegisterForCompetition",{CompetitionID:e,KindID:t})}claimCompetitionRewards(e){return this.mutate("ClaimCompetitionRewards",{CompetitionID:e?.competitionID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}startWarAttack(e,t,n){return this.mutate("StartWarAttack",{CompetitionID:e,TargetUserID:t,CharacterID:n?.characterID,KindID:n?.kindID})}setDiplomacy(e,t,n){return this.mutate("SetDiplomacy",{TargetClanID:e,Relation:t,KindID:n})}takeRevenge(e,t){return this.mutate("TakeRevenge",{RevengeID:e,KindID:t})}claimSeasonReward(e){return this.mutate("ClaimSeasonReward",{KindID:e})}};var Nn={GetDefinitions:"GetDefinitions",GetAvatars:"GetAvatars",GetShop:"GetShop",BuyItem:"BuyItem"},rD={TooManyUsers:"AVATAR_TOO_MANY_USERS",Disabled:"AVATAR_DISABLED",NotForSale:"AVATAR_ITEM_NOT_FOR_SALE"},dr=50,mr=zod.z.object({Enabled:zod.z.boolean().nullish(),Styles:zod.z.array(zod.z.string()).nullish(),BlockedSlots:zod.z.array(zod.z.string()).nullish(),HeightMin:zod.z.number().nullish(),HeightMax:zod.z.number().nullish()}).passthrough(),oD=48,aD=zod.z.object({UserID:zod.z.string(),Rev:zod.z.string(),NotModified:zod.z.boolean().nullish(),HasAvatar:zod.z.boolean(),Spec:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),pd=zod.z.object({id:zod.z.string(),slot:zod.z.string()}).passthrough(),hd=zod.z.object({Enabled:zod.z.boolean(),Avatars:zod.z.array(aD).nullish().transform(r=>r??[]),Items:zod.z.record(zod.z.string(),pd).nullish().transform(r=>r??{})}).passthrough(),lD=zod.z.object({ItemID:zod.z.string(),Slot:zod.z.string(),PriceCredits:zod.z.number(),OnSale:zod.z.boolean().nullish(),Name:zod.z.string().nullish(),Source:zod.z.enum(["platform","authors"]).nullish().catch(null),AuthorName:zod.z.string().nullish(),IsOwned:zod.z.boolean().nullish()}).passthrough(),dd=zod.z.object({Enabled:zod.z.boolean(),Offers:zod.z.array(lD).nullish().transform(r=>r??[]),Owned:zod.z.array(zod.z.string()).nullish().transform(r=>r??[]),LoginRequired:zod.z.boolean().nullish().transform(r=>r??false),Items:zod.z.record(zod.z.string(),pd).nullish().transform(r=>r??{}),Paged:zod.z.boolean().nullish(),Next:zod.z.string().nullish(),Slots:zod.z.array(zod.z.string()).nullish(),AuthorsOpen:zod.z.boolean().nullish()}).passthrough(),md=zod.z.object({ItemID:zod.z.string().nullish(),Owned:zod.z.boolean().nullish().transform(r=>r??false),TestPurchase:zod.z.boolean().nullish().transform(r=>r??false),CreditsConfirmation:ye.nullish()}).passthrough();var uD="Avatar",fr=class{constructor(e){this.ctx=e;e.emitter.on("auth:loggedOut",()=>{this.held.clear(),this.inflight.clear(),this.disabled=false;});}ctx;held=new Map;inflight=new Map;disabled=false;get definitions(){return this.ctx.cache.configSection(uD)??null}get enabled(){return this.definitions?.Enabled===true&&!this.disabled}peek(e){return this.held.get(e)}async getMine(){let e=this.ctx.auth.context?.userID;if(!e)return l;let t=await this.get([e]);return t.ok?B(t.data[0]??null):t}async get(e){if(!this.ctx.authedRequest())return l;let n=[...new Set(e.map(o=>o?.trim()).filter(o=>!!o))];if(n.length===0)return B([]);let i=new Set,s=[];for(let o of n){let p=this.inflight.get(o);p?i.add(p):s.push(o);}for(let o=0;o<s.length;o+=dr){let p=s.slice(o,o+dr),m=this.request(p);for(let g of p)this.inflight.set(g,m);m.finally(()=>{for(let g of p)this.inflight.get(g)===m&&this.inflight.delete(g);}),i.add(m);}for(let o of await Promise.all(i)){if(!o.ok)return o;if(!o.data.Enabled)return B([])}return B(n.map(o=>this.held.get(o)).filter(o=>!!o))}async getShop(){let e=this.ctx.authedRequest();return e?this.ctx.api.avatar.getShop(e):l}async browseShop(e={}){let t=this.ctx.authedRequest();if(!t)return l;t.Sort=e.sort??"new",e.slot&&(t.Slot=e.slot);let n=e.query?.trim();return n&&(t.Query=n),e.ownedOnly&&(t.OwnedOnly=true),e.source&&(t.Source=e.source),e.cursor&&(t.Cursor=e.cursor),this.ctx.api.avatar.getShop(t)}async buyItem(e,t,n){let i=this.ctx.authedRequest();return i?(i.ItemID=e,i.PriceCredits=t,n&&(i.CreditsConfirmationID=n),this.ctx.api.avatar.buyItem(i)):l}async request(e){let t=this.ctx.authedRequest();if(!t)return l;t.UserIDs=e;let n={};for(let s of e){let o=this.held.get(s);o&&(n[s]=o.rev);}Object.keys(n).length>0&&(t.KnownRevs=n);let i=await this.ctx.api.avatar.getAvatars(t);if(!i.ok)return i;if(this.disabled=!i.data.Enabled,!i.data.Enabled){for(let s of e)this.held.delete(s);return i}if(i.data.Avatars.some(s=>s.NotModified&&this.held.get(s.UserID)?.rev!==s.Rev)){for(let p of e)this.held.delete(p);let s=this.ctx.authedRequest();if(!s)return l;s.UserIDs=e;let o=await this.ctx.api.avatar.getAvatars(s);return o.ok?o.data.Avatars.some(p=>p.NotModified)?h("client","AVATAR_REVISION_MISMATCH"):(this.apply(o.data),o):o}return this.apply(i.data),i}apply(e){let t=[];for(let n of e.Avatars){if(n.NotModified)continue;let i=n.HasAvatar?n.Spec??null:null;this.held.set(n.UserID,{userID:n.UserID,rev:n.Rev,hasAvatar:n.HasAvatar&&!!i,spec:i,items:i?cD(i,e.Items):[]}),t.push(n.UserID);}t.length>0&&this.ctx.emitter.emit("avatar:changed",{userIDs:t});}};function cD(r,e){let t=r.wear;if(!t||typeof t!="object")return [];let n=[];for(let i of Object.values(t))typeof i=="string"&&e[i]&&n.push(e[i]);return n}var gr={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},ul="idos-app",fd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),Allowed:zod.z.boolean(),DenyReason:zod.z.string().nullish(),Message:zod.z.string().nullish(),RetryAfterSeconds:zod.z.number().nullish(),RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),AdUnitID:zod.z.string().nullish(),Type:zod.z.string().nullish(),ExpiresAtUtc:zod.z.string().nullish(),CreditsToAward:zod.z.number().nullish(),RequiresServerSideVerification:zod.z.boolean().nullish()}),gd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),RequestID:zod.z.string().nullish(),Status:zod.z.string(),CreditsAwarded:zod.z.number().nullish(),RetryAfterSeconds:zod.z.number().nullish(),ExpiresAtUtc:zod.z.string().nullish(),AlreadyProcessed:zod.z.boolean().nullish(),GrantedWithoutSsv:zod.z.boolean().nullish(),Resources:O.nullish()});var pD=new Set(["CANCELLED","DECLINED","CLOSED"]),hD=45e3,dD=r=>new Promise(e=>setTimeout(e,r)),yr=class{constructor(e){this.ctx=e;}ctx;get available(){return this.ctx.host.supports.rewardedAds}async showRewarded(e){if(!this.ctx.host.supports.rewardedAds)return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let n=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!n.ok)return {status:"unavailable",reason:n.error};let i=n.data;if(!i.Allowed)return {status:"denied",reason:i.DenyReason??void 0,retryAfterSeconds:i.RetryAfterSeconds??void 0};if(!i.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let s=null;if(i.ProviderID!==ul&&(s=this.titleProvider(i.ProviderID),!s))return {status:"unavailable",reason:"NO_WEB_ADS"};let o=await this.ctx.host.showRewardedAd({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:i.RequestID,placementID:e,adUnitID:i.AdUnitID,provider:s});return o.ok?{...await this.awaitReward(i.RequestID,o.via),requestID:i.RequestID}:{status:pD.has(o.error??"")?"cancelled":"unavailable",reason:o.error}}titleProvider(e){if(!this.ctx.host.supports.titleAds||!e)return null;let n=this.ctx.data.config.getSection("Advertising")?.Providers?.[e];if(!n||n.Enabled===false)return null;let i=this.ctx.host.getClientPlatform(),s=i===Ge.Android?n.AndroidAppID:i===Ge.Ios?n.IosAppID:n.WebAppID;return s?{id:e,kind:n.Kind??"AppLovinMax",appKey:s}:null}async awaitReward(e,t){let n=Date.now()+hD;for(;;){let i=this.ctx.authedRequest();if(!i)return {status:"pending",via:t};let s=await this.ctx.api.advertising.completeView({...i,RequestID:e});if(s.ok&&s.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:s.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((s.ok?s.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>n)return {status:"pending",via:t,reason:s.ok?void 0:s.error};await dD(o);}}};var jt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},mD={Client:"Client",Server:"Server",System:"System"},fD=zod.z.enum(["Client","Server","System"]).catch("Client"),cl=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:fD.nullish(),ExpiresAt:u.nullish()}).passthrough(),Rr=zod.z.record(zod.z.string(),cl),yd=zod.z.object({Version:zod.z.number().nullish(),Private:Rr.nullish(),Public:Rr.nullish(),ReadOnly:Rr.nullish()}),pl=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Rr.nullish()}),hl=zod.z.object({ServerTimeUtc:u.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),gD=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),Rd=zod.z.object({ServerTimeUtc:u.nullish(),Results:zod.z.array(gD).nullish()}),Cd=zod.z.object({ServerTimeUtc:u.nullish(),DeletedCount:zod.z.number().nullish()}),Sd=zod.z.object({Results:zod.z.array(pl).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),yD={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},RD=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),CD=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:RD.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Cr=zod.z.object({Keys:zod.z.record(zod.z.string(),CD).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),At={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var SD={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},bD={Title:"Title",Platform:"Platform"},bd=zod.z.object({UserID:zod.z.string(),PublicData:Ne.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()});var xD=zod.z.object({StageLevel:zod.z.number().nullish(),SpecialPlayedCount:zod.z.number().nullish()}),xd=zod.z.object({UserID:zod.z.string(),IsSelf:zod.z.boolean().nullish(),PublicData:Ne.nullish(),Characters:zod.z.record(zod.z.string(),ai).nullish(),StrongestCharacterID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),Board:xD.nullish(),PublicCustomData:zod.z.record(zod.z.string(),cl).nullish(),Relation:zod.z.enum(["None","Friend","RequestSent","RequestReceived"]).nullish(),FriendSource:zod.z.enum(["Title","Platform"]).nullish(),BlockedByMe:zod.z.boolean().nullish(),FriendRequestsAllowed:zod.z.boolean().nullish()});var hi=zod.z.object({Friends:zod.z.array(bd).nullish()}),DD=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),di=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:bd.nullish(),Counters:DD.nullish()}),ID={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},PD={Like:"Like",Favorite:"Favorite"},vD={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},AD={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},TD={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived",ArenaDefeat:"ArenaDefeat"},wD=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),kD=zod.z.object({Id:zod.z.string(),Verb:zod.z.string().nullish(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Count:zod.z.number().nullish(),LastActors:zod.z.array(wD).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),OccurredAt:u.nullish(),OwnerImpact:O.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),Dd=zod.z.object({Items:zod.z.array(kD).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),mi=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),zD=zod.z.object({Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),Followers:zod.z.number().nullish(),Following:zod.z.number().nullish(),Comments:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Posts:zod.z.number().nullish(),Dislikes:zod.z.number().nullish()}).passthrough(),nn=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:zD.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),Id=zod.z.object({Items:zod.z.array(nn).nullish()}).passthrough(),dl={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},MD=zod.z.object({UserID:zod.z.string(),PublicData:Ne.nullish(),Mutual:zod.z.boolean().nullish(),Since:u.nullish()}).passthrough(),Sr=zod.z.object({Items:zod.z.array(MD).nullish(),...dl}).passthrough(),OD=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:u.nullish()}).passthrough(),Pd=zod.z.object({Items:zod.z.array(OD).nullish(),...dl}).passthrough(),br=zod.z.object({CommentID:zod.z.string(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),ParentCommentID:zod.z.string().nullish(),AuthorUserID:zod.z.string().nullish(),AuthorPublicData:Ne.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:u.nullish(),EditedAt:u.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),vd=zod.z.object({Items:zod.z.array(br).nullish(),...dl,TotalCount:zod.z.number().nullish()}).passthrough(),Ad=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),Td=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),wd=zod.z.object({CommentsEnabled:zod.z.boolean().nullish(),CommentableTypes:zod.z.array(zod.z.string()).nullish(),CommentMaxLength:zod.z.number().nullish(),CommentMaxLinks:zod.z.number().nullish()}).passthrough(),ED="FRIENDS_FROM_PLATFORM",qD={Off:"Off",Default:"Default",Always:"Always"},UD={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},kd=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:zod.z.boolean().nullish()}).passthrough(),Ie={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report",GetPlayerProfile:"GetPlayerProfile"};var ml={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},xr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ml,{schema:mi,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return l;t.Limit=e;let n=await this.ctx.api.social.getRecommendedFriends(t);return n.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",n.data),n}async getPlayerProfile(e){if(!e)return h("client","TargetUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.getPlayerProfile(t);return n.ok&&this.ctx.emitter.emit("social:playerProfileLoaded",n.data),n}async sendFriendRequest(e){if(!e)return h("client","TargetUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.sendFriendRequest(t);return n.ok&&(n.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",n.data)),n}async acceptFriendRequest(e){if(!e)return h("client","RequesterUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.acceptFriendRequest(t);return n.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",n.data)),n}async declineFriendRequest(e){if(!e)return h("client","RequesterUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.declineFriendRequest(t);return n.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",n.data)),n}async removeFriend(e){if(!e)return h("client","FriendUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.removeFriend(t);return n.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRemoved",n.data)),n}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return l;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let n=await this.ctx.api.social.getInbox(t);return n.ok&&this.ctx.emitter.emit("social:inboxLoaded",n.data),n}getInboxUnread(e){return this.ctx.cache.read(ml,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(ml,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let n=this.ctx.authedRequest();return n?(n.ReactionKind=e,n.EntityType=t.entityType,this.applyPage(n,t.cursor,t.limit),this.ctx.api.social.getMyReactions(n)):l}async getEntityStates(e,t){if(!t?.length)return h("client","EntityIDs are required.");let n=this.ctx.authedRequest();return n?(n.EntityType=e,n.EntityIDs=t,this.ctx.api.social.getEntityStates(n)):l}async addComment(e,t,n,i){let s=this.targetRequest(e,t);if("ok"in s)return s;if(!n?.trim())return h("client","Text is required.");s.Text=n,s.ParentCommentID=i;let o=await this.ctx.api.social.addComment(s);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return h("client","CommentID is required.");if(!t?.trim())return h("client","Text is required.");let n=this.ctx.authedRequest();if(!n)return l;n.CommentID=e,n.Text=t;let i=await this.ctx.api.social.editComment(n);return i.ok&&this.ctx.emitter.emit("social:commentEdited",i.data),i}async deleteComment(e){if(!e)return h("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.CommentID=e;let n=await this.ctx.api.social.deleteComment(t);return n.ok&&this.ctx.emitter.emit("social:commentDeleted",n.data),n}async getComments(e,t,n={}){let i=this.targetRequest(e,t);return "ok"in i?i:(i.ParentCommentID=n.parentCommentID,this.applyPage(i,n.cursor,n.limit),this.ctx.api.social.getComments(i))}async report(e,t,n,i){let s=this.targetRequest(e,t);if("ok"in s)return s;if(!n)return h("client","ReportReason is required.");s.ReportReason=n,s.ReportComment=i;let o=await this.ctx.api.social.report(s);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,n,i){let s=this.targetRequest(t,n);if("ok"in s)return s;s.ReactionKind=i;let o=await this.ctx.api.social[e](s);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,n){let i=this.ctx.authedRequest();return i?(this.applyPage(i,t,n),this.ctx.api.social[e](i)):l}applyPage(e,t,n){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=n;}targetRequest(e,t){if(!e)return h("client","EntityType is required.");if(!t)return h("client","EntityID is required.");let n=this.ctx.authedRequest();return n?(n.EntityType=e,n.EntityID=t,n):l}};var zd="TimedBoost";function LD(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Dr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(zd,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),B(t);let n=this.ctx.authedRequest();if(!n)return l;let i=await this.ctx.api.timedBoost.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(zd,i.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",i.data)),i}async getActive(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let n=e.trim();if(!LD(n))return h("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),BoostID:n,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${n}_${F()}`},s=await this.ctx.api.timedBoost.activate(i);if(s.ok&&!s.data.CreditsConfirmation){let o=s.data;if(o.ActivatedBoost){let p=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,p);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return s}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var BD="UserCustomData";function Md(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Ir=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(BD,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return h("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.TargetUserID=t;let i=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(n);return i.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",i.data),i}async setPrivateData(e,t){return this.setData(e,t,jt.Private)}async setPublicData(e,t){return this.setData(e,t,jt.Public)}async setData(e,t,n){let i=e.trim();if(!Md(i))return h("client",'KeyID is required and must not contain "." or "$".');if(t==null)return h("client","Value is required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Value:t},p=await(n===jt.Private?this.ctx.api.userCustomData.setPrivateData(s):this.ctx.api.userCustomData.setPublicData(s));if(p.ok){let m=p.data;this.ctx.data.user.patchUserCustomDataKey(n,m.KeyID,t,m.Version??0,m.ExpiresAt),this.ctx.emitter.emit(n===jt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",m);}return p}async deleteKey(e,t){let n=e.trim();if(!Md(n))return h("client",'KeyID is required and must not contain "." or "$".');if(t!==jt.Private&&t!==jt.Public)return h("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Bucket:t},s=await this.ctx.api.userCustomData.deleteKey(i);return s.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,n),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),s}async batchSet(e){if(!e.length)return h("client","At least one item is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},n=await this.ctx.api.userCustomData.batchSet(t);if(n.ok){for(let i of n.data.Results??[]){let s=i.Bucket??jt.Private,o=e.find(p=>p.Bucket===s&&p.KeyID===i.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(s,i.KeyID,o.Value,i.Version??0,i.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",n.data);}return n}async batchDelete(e){if(!e.length)return h("client","At least one item is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},n=await this.ctx.api.userCustomData.batchDelete(t);if(n.ok){for(let i of e)this.ctx.data.user.removeUserCustomDataKey(i.Bucket,i.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",n.data);}return n}async batchGetPublicUserCustomDataOf(e){if(!e.length)return h("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return l;t.TargetUserIDs=e;let n=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return n.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",n.data),n}};var GD="TitleCustomDataDefinitions",Od=50;function ND(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function fl(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function _D(r){let e={};for(let[t,n]of Object.entries(r))fl(n)||(e[t]=n);return e}var Pr=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(GD,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return l;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let n=await this.ctx.api.titleCustomData.getPublicTitleData(t);return n.ok&&this.absorb(n.data),n}async getPublicTitleDataKeys(e){let t=e.map(s=>s.trim()).filter(s=>s.length>0);if(!t.length)return h("client","At least one KeyID is required.");if(t.some(s=>!ND(s)))return h("client",'KeyID must not contain "." or "$".');if(t.length>Od)return h("client",`At most ${Od} keys per call \u2014 request them in chunks.`);let n=this.ctx.authedRequest();if(!n)return l;n.KeyIDs=t;let i=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(n);return i.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",i.data),i}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!fl(t))return t.Value;let n=this.staticCache[e];if(n?.Value!=null&&!fl(n))return n.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=_D(this.runtimeCache),e.Runtime=this.runtimeCache):e.Runtime&&(this.runtimeCache=e.Runtime),e.RuntimeVersion!=null&&(this.lastRuntimeVersion=e.RuntimeVersion),this.ctx.emitter.emit("titleCustomData:publicDataLoaded",e);}};var vr=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var FD={Fast:"Fast",Sequential:"Sequential"},VD={Instant:"Instant",Timed:"Timed"};var jD={Hit:"Hit",Blocked:"Blocked"},WD=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),HD=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:$.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:$.nullish()}).passthrough();var KD=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:$.nullish()}).passthrough(),QD=zod.z.object({Reward:$.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough();zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(KD).nullish(),Rate:QD.nullish()}).passthrough();zod.z.object({PlayedCount:zod.z.number().nullish(),RewardsClaimedCount:zod.z.number().nullish(),InstantClaimsCount:zod.z.number().nullish(),EarlyClaimsCount:zod.z.number().nullish(),LateClaimsCount:zod.z.number().nullish(),AdViewsTotal:zod.z.number().nullish(),StatRewardClaimsCount:zod.z.number().nullish(),StatReportsClampedCount:zod.z.number().nullish(),StatReportsUnknownMetricCount:zod.z.number().nullish()}).passthrough();var Ed=zod.z.object({}).passthrough().transform(r=>r),qd=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Ye=zod.z.object({Operation:O.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),$D=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),JD=zod.z.object({ShieldChance:zod.z.number().nullish(),DamagedBuildingChance:zod.z.number().nullish(),RankMultiplierMin:zod.z.number().nullish(),RankMultiplierMax:zod.z.number().nullish(),RankOffsetMin:zod.z.number().nullish(),RankOffsetMax:zod.z.number().nullish(),StageLevelSpread:zod.z.number().nullish()}).passthrough(),ZD=zod.z.object({CostMatrixTemplatesByID:zod.z.record(zod.z.string(),zod.z.array(zod.z.array(zod.z.number()))).nullish(),PerBoardGrowth:zod.z.number().nullish(),VisualTemplateCycle:zod.z.array(zod.z.string()).nullish(),EconomyScaledResources:pe.nullish(),ScaleRaidStealWithEconomy:zod.z.boolean().nullish(),ScaleAttackRewardWithEconomy:zod.z.boolean().nullish(),AttackValueFromCostMatrix:zod.z.boolean().nullish(),AttackBlockedRewardFactor:zod.z.number().nullish(),ScaleVictimLossWithEconomy:zod.z.boolean().nullish(),ScaleVictimLossWithTier:zod.z.boolean().nullish(),SynthesizedBuildingSlots:zod.z.number().nullish(),SynthesizedBuildingMaxLevel:zod.z.number().nullish(),DifficultyGrowthPerBoard:zod.z.number().nullish()}).passthrough(),YD=zod.z.object({CostMatrix:zod.z.array(zod.z.array(zod.z.number())).nullish(),PerBoardGrowth:zod.z.number().nullish(),EconomyScale:zod.z.number().nullish(),ScaledResources:pe.nullish()}).passthrough(),Ud=zod.z.object({SlotIndex:zod.z.number().nullish(),Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxLevel:zod.z.number().nullish(),MaxLevelReward:$.nullish()}).passthrough(),XD=zod.z.object({Index:zod.z.number().nullish(),Type:zod.z.string().nullish(),CustomTypeID:zod.z.string().nullish(),RandomActionAttackWeight:zod.z.number().nullish(),RandomActionRaidWeight:zod.z.number().nullish(),ChanceTableID:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),eI=zod.z.object({Tiles:zod.z.record(zod.z.string(),XD).nullish()}).passthrough(),tI=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Ye.nullish(),Tag:zod.z.string().nullish()}).passthrough(),nI=zod.z.object({Weight:zod.z.number().nullish(),Tag:zod.z.string().nullish(),MinBonusCells:zod.z.number().nullish(),MaxBonusCells:zod.z.number().nullish(),BonusPool:zod.z.array(tI).nullish(),GuaranteedBonus:Ye.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),iI=zod.z.object({Variants:zod.z.array(nI).nullish()}).passthrough(),sI=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:Ye.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),rI=zod.z.object({Outcomes:zod.z.array(sI).nullish()}).passthrough(),Ld=zod.z.object({PerAdMultiplierRange:qd.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish(),PremiumMultiplier:zod.z.number().nullish(),MinPremiumTier:zod.z.number().nullish()}).passthrough(),oI=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Ye.nullish()}).passthrough(),aI=zod.z.object({Tiers:zod.z.array(oI).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Ye.nullish()}).passthrough(),lI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Ye.nullish()}).passthrough(),uI=zod.z.object({Reward:Ye.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),cI=zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(lI).nullish(),Rate:uI.nullish()}).passthrough(),Bd=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),cI).nullish()}).passthrough(),pI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Ye.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:de.nullish(),Multipliers:Ld.nullish(),Gradation:aI.nullish(),RunStats:Bd.nullish()}).passthrough(),hI=zod.z.object({Choices:zod.z.array(pI).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),dI=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Ye.nullish(),Tag:zod.z.string().nullish()}).passthrough(),mI=zod.z.object({OnPassStart:Ye.nullish(),OnTileLanding:zod.z.record(zod.z.string(),Ye).nullish(),OnAttack:zod.z.record(zod.z.string(),Ye).nullish(),OnRaid:zod.z.record(zod.z.string(),Ye).nullish(),OnBuild:Ye.nullish(),OnStageComplete:Ye.nullish(),OnAttackBonusDrops:zod.z.array(dI).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),rI).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),hI).nullish()}).passthrough(),Gd=zod.z.object({BaseAttackReward:$.nullish(),BaseRaidReward:$.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Ud).nullish(),HeistGridBonusConfig:iI.nullish(),StageOperations:mI.nullish(),TileLandingMultiplier:qd.nullish(),EconomyOverride:YD.nullish()}).passthrough(),fI=zod.z.object({Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BoardTemplateID:zod.z.string().nullish(),Buildings:zod.z.array(Ud).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:Gd.nullish()}).passthrough(),gI=zod.z.object({AttackCooldownSeconds:zod.z.number().nullish(),RaidCooldownSeconds:zod.z.number().nullish(),MaxRecentTargets:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),LiveOpponentPoolSize:zod.z.number().nullish(),LiveOpponentPoolCacheSeconds:zod.z.number().nullish(),MaxLiveCandidateReads:zod.z.number().nullish(),VictimImmunitySeconds:zod.z.number().nullish()}).passthrough(),yI=zod.z.object({Enabled:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),MaxPerCatchUp:zod.z.number().nullish(),Chance:zod.z.number().nullish(),AttackWeight:zod.z.number().nullish(),RaidWeight:zod.z.number().nullish(),MinBoardStageLevel:zod.z.number().nullish(),RaidLossMultiplier:zod.z.number().nullish()}).passthrough(),RI=zod.z.object({Enabled:zod.z.boolean().nullish(),Sources:zod.z.array(zod.z.string()).nullish(),AdMultiplier:zod.z.number().nullish(),PremiumMultiplier:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),AdDailyLimit:zod.z.number().nullish(),PremiumDailyLimit:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),MinPremiumTier:zod.z.number().nullish()}).passthrough(),Ar=zod.z.object({RollCurrencyID:zod.z.string().nullish(),ShieldCurrencyID:zod.z.string().nullish(),RaidMode:zod.z.string().nullish(),AllowedRollMultipliers:zod.z.array(zod.z.number()).nullish(),BoardTemplatesByID:zod.z.record(zod.z.string(),eI).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),Gd).nullish(),StagesByLevel:zod.z.record(zod.z.string(),fI).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:ZD.nullish(),Dice:$D.nullish(),Bots:JD.nullish(),Targeting:gI.nullish(),BotRaids:yI.nullish(),RewardBoost:RI.nullish()}).passthrough(),CI=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:u.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),GrandPrize:$.nullish()}).passthrough(),Tr=zod.z.object({Board:Ar.nullish(),CommunityChest:CI.nullish()}).passthrough(),Nd=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),pe).nullish()}).passthrough(),SI=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:Ne.nullish(),TargetBuildingStates:zod.z.array(WD).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:Nd.nullish()}).passthrough(),bI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Ye.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:de.nullish(),Multipliers:Ld.nullish(),RunStats:Bd.nullish()}).passthrough(),xI=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(bI).nullish()}).passthrough(),DI=zod.z.object({GroupID:zod.z.string().nullish(),Delta:Q.nullish(),NewProgress:Q.nullish(),MaxProgress:Q.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),_d=zod.z.object({UsedMultiplier:zod.z.number().nullish(),Steps:zod.z.number().nullish(),DiceValues:zod.z.array(zod.z.number()).nullish(),OldPosition:zod.z.number().nullish(),NewPosition:zod.z.number(),CyclesCompletedDelta:Q.nullish(),LandedTileType:zod.z.string().nullish(),Operation:O.nullish(),Inventory:K.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:SI.nullish(),SpecialModeOffer:xI.nullish(),CommunityChestContribution:DI.nullish()}).passthrough(),wr={Ad:"Ad",Premium:"Premium"},Fd=zod.z.object({BoostID:zod.z.string().nullish(),Source:zod.z.string().nullish(),ExpiresAtUtc:u.nullish(),AdMultiplier:zod.z.number().nullish(),PremiumMultiplier:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),MinPremiumTier:zod.z.number().nullish(),AdRemainingToday:zod.z.number().nullish(),PremiumRemainingToday:zod.z.number().nullish(),BaseEntries:zod.z.array(Tt).nullish()}).passthrough(),Vd=zod.z.object({BoostID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Multiplier:zod.z.number().nullish(),AlreadyApplied:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish(),AdRemainingToday:zod.z.number().nullish(),PremiumRemainingToday:zod.z.number().nullish()}).passthrough(),jd=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:Nt.nullish(),RewardBoost:Fd.nullish()}).passthrough(),gl=zod.z.object({Status:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),FoundSymbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),FoundBonus:$.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(HD).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:Nt.nullish(),RaidRewardPreview:Nd.nullish(),RewardBoost:Fd.nullish()}).passthrough(),Wd=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish()}).passthrough(),Hd=zod.z.object({CreditsConfirmation:ye.nullish(),Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:O.nullish(),Inventory:K.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish()}).passthrough(),Kd=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish(),PremiumApplied:zod.z.boolean().nullish()}).passthrough(),II=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),Qd=zod.z.object({FinalMultiplier:zod.z.number().nullish(),AdViewsUsed:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),IsEarlyClaim:zod.z.boolean().nullish(),ReachedTierIndex:zod.z.number().nullish(),Operation:O.nullish(),Inventory:K.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(II).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:$.nullish()}).passthrough(),PI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},$d=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),vI={Active:"Active",Left:"Left",Replaced:"Replaced"},AI=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),TI=zod.z.object({CurrentProgress:Q.nullish(),MaxProgress:Q.nullish()}).passthrough(),wI=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ne.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:Q.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),Wu).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:AI.nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),Jd=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(wI).nullish(),SharedProgress:TI.nullish(),Status:$d.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),kI=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:$d.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:u.nullish()}).passthrough(),zI=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(kI).nullish()}).passthrough(),Zd=zod.z.object({ServerTimeUtc:u.nullish(),UserState:zI.nullish(),ActiveGroup:Jd.nullish(),SecondsRemaining:Q.nullish()}),Yd=zod.z.object({ServerTimeUtc:u.nullish(),Group:Jd.nullish(),SecondsRemaining:Q.nullish()}),yl=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Xd=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),We={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",BoardRewardBoostApply:"BoardRewardBoostApply",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var MI=15,OI="GameLoop",em="BoardDefinition",fi="InventoryV2",EI="GameLoop",kr=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(OI,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let n=this.ctx.cache.configSection(em,t);if(n)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n),B(n);let i=this.ctx.authedRequest();if(!i)return l;let s=await this.ctx.api.gameLoop.getBoardDefinition(i,e);return s.ok&&(this.ctx.data.config.patchSection(em,s.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",s.data)),s}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return h("client","stageLevel must be > 0.");let n=this.ctx.authedRequest();if(!n)return l;n.StageLevel=e;let i=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(n,t);return i.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",i.data),i}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return l;let t=false,n=this.ctx.emitter.on("user:stateVersions",({versions:s})=>{s[fi]!==void 0&&(t=true);}),i;try{i=await this.ctx.api.gameLoop.getUserBoardState(e);}finally{n();}return i.ok&&(this.ctx.data.user.applyBoardState(i.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",i.data),t&&(this.ctx.cache.invalidateState([fi]),this.ctx.cache.ensureState([fi]),this.ctx.emitter.emit("user:changedElsewhere",{containers:[fi]}))),i}async boardLoopRoll(e=1){if(e<1)return h("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${F()}`},i=await this.ctx.api.gameLoop.boardLoopRoll(n);if(i.ok){let s=i.data,o=yc(new Date,MI);this.ctx.data.user.patchBoardState(p=>{p.Position=s.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(s.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),s.ActionRequired&&s.ActionData?p.Pending={Type:s.ActionRequired,TargetUserID:s.ActionData.TargetUserID,TargetPublicData:s.ActionData.PublicData,TargetBuildingStates:s.ActionData.TargetBuildingStates??void 0,TargetHasShield:s.ActionData.TargetHasShield??void 0,RollMultiplier:s.UsedMultiplier??1,ExpiresAtUtc:o}:s.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:s.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:s.SpecialModeOffer.ModeID??void 0,Choices:s.SpecialModeOffer.Choices??void 0}});}),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),s.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",s);}return i}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${F()}`},i=await this.ctx.api.gameLoop.boardLoopAttack(n);if(i.ok){let s=i.data;this.ctx.data.user.clearBoardPending(),s.IsBotTarget&&s.Operation?this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs):!s.IsBotTarget&&s.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(s.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",s);}else await this.getUserBoardState();return i}async boardLoopRaid(e,t){if(e<0||e>11)return h("client","digIndex must be between 0 and 11.");let n=this.ctx.auth.context;if(!n)return l;let i={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${n.userID}_${F()}`},s=await this.ctx.api.gameLoop.boardLoopRaid(i);if(s.ok){let o=s.data;o.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(o.RaidLayout,o.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(o)),this.ctx.emitter.emit("gameLoop:boardRaided",o);}else await this.getUserBoardState();return s}async boardLoopRaidFast(e){if(!e.length)return h("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${F()}`},i=await this.ctx.api.gameLoop.boardLoopRaidFast(n);if(i.ok){let s=i.data;s.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(s)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",s);}else await this.getUserBoardState();return i}async boardLoopBuild(e){if(e<0)return h("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${F()}`},i=await this.ctx.api.gameLoop.boardLoopBuild(n);if(!i.ok&&i.reason==="server"&&await this.ctx.cache.ensureState([fi,EI],{force:true}),i.ok){let s=i.data;s.StageComplete?this.ctx.data.user.patchBoardState(o=>{o.StageLevel=(o.StageLevel??1)+1,o.Position=0,o.Pending=null,o.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(s.BuiltIndex,o=>{s.NewLevel!=null&&(o.Level=s.NewLevel),o.IsDamaged=false,s.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",s);}return i}async boardSpecialChoose(e,t,n){if(!e)return h("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return l;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:n,RelatedEntityID:`special_choose_${i.userID}_${F()}`},o=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(o.ok&&!o.data.CreditsConfirmation){let p=o.data;p.Mode==="Instant"||p.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(g=>{g.ChoiceID=e,g.ChosenMode=p.Mode??"Timed",g.StartedAtUtc=p.StartedAtUtc??null,g.DurationSeconds=p.DurationSeconds??null,g.AdViewsUsed=0;}),p.Operation&&this.ctx.data.user.applyResourcesWithDelta(p.Operation,p.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",p);}return o}async boardSpecialApplyMultiplier(e,t=wr.Ad){let n=this.ctx.auth.context;if(!n)return l;let i=t===wr.Premium,s={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_${i?"vip":"ad"}_${n.userID}_${F()}`,...i?{BoostMode:wr.Premium}:{}},o=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(s);if(o.ok){let p=o.data;this.ctx.data.user.patchBoardSpecialPending(m=>{m.AdViewsUsed=p.AdViewsUsed??0,m.AccumulatedMultiplier=p.AccumulatedMultiplier??0,p.PremiumApplied&&(m.PremiumApplied=true);}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",p);}return o}async boardRewardBoostApply(e,t){if(!this.ctx.auth.context)return l;if(!e)return h("client","boostID must not be empty.");let i={...this.ctx.buildAuthedBaseRequest(),BoostID:e,BoostMode:t,RelatedEntityID:`boost_${e}_${t}`},s=await this.ctx.api.gameLoop.boardRewardBoostApply(i);if(s.ok){let o=s.data;!o.AlreadyApplied&&o.Operation&&this.ctx.data.user.applyResourcesWithDelta(o.Operation,o.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardRewardBoostApplied",o);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${F()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},i=await this.ctx.api.gameLoop.boardSpecialClaim(n);if(i.ok){let s=i.data;this.ctx.data.user.clearBoardPending(),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",s);}return i}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return l;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let n=t.data.Group;n?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:n.GroupID,ActiveRoundIndex:n.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return h("client","milestoneID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},i=await this.ctx.api.gameLoop.claimCommunityChestMilestone(n);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",i.data)),i}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",n.data)),n}async leaveCommunityChest(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.gameLoop.leaveCommunityChest(t);return n.ok&&(n.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",n.data)),n}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var zr=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,n,i){let s=e.trim();if(!s)return h("client","FunctionName is required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:s,FunctionParameter:t,RevisionSelection:n,SpecificRevision:i},p=await this.ctx.api.cloudCode.execute(o);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var qI={EVM:"EVM",Solana:"Solana"},UI=zod.z.enum(["EVM","Solana"]).catch("EVM"),LI={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},BI=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),GI={Token:"Token",Nft:"Nft"},tm=zod.z.enum(["Token","Nft"]).catch("Token"),NI={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},_I=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),FI={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},VI=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),jI={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Rl=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),nm={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Mr(r){let e=r?.trim();return e||nm.GameTopUp}var WI={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},im=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),HI=zod.z.object({ContractAddress:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),sm=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),KI=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:UI.nullish(),ChainID:zod.z.number().nullish(),ChainTicker:zod.z.string().nullish(),RewardPoolAddress:zod.z.string().nullish(),VaultDepositAddress:zod.z.string().nullish(),ChainConfigVersion:zod.z.number().nullish(),RequiredConfirmations:zod.z.number().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:sm.nullish(),NftCollections:zod.z.array(HI).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RpcUrl:zod.z.string().nullish(),GasPrice:zod.z.number().nullish(),NftBridgeAddress:zod.z.string().nullish(),SignatureEpoch:zod.z.number().nullish()}).passthrough(),QI=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:sm.nullish()}).passthrough(),$I=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),JI={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},ZI=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),rm=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:ne.nullish(),BalanceSource:ZI.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),YI=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),XI={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},gi=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),eP=zod.z.object({Mode:gi.nullish(),TokenGates:zod.z.array(rm).nullish()}).passthrough(),Cl=zod.z.object({SystemState:QI.nullish(),Networks:zod.z.record(zod.z.string(),KI).nullish(),AccountSafety:$I.nullish(),WalletLogin:YI.nullish(),PlayAccess:eP.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),tP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:u.nullish(),LastUsedAt:u.nullish(),LinkType:BI.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),om=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:tm.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:ne.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),nP=zod.z.object({Status:_I.nullish(),Tier:VI.nullish(),VerifiedAt:u.nullish(),ExpiresAt:u.nullish(),RejectedAt:u.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),iP=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:ne.nullish(),DepositsVolumeUsd:ne.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:ne.nullish(),WithdrawalsVolumeUsd:ne.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),sP=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:ne.nullish(),TotalWithdrawalsVolumeUsd:ne.nullish(),PerCurrency:zod.z.record(zod.z.string(),iP).nullish()}).passthrough(),rP=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),oP=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),PerCollection:zod.z.record(zod.z.string(),rP).nullish()}).passthrough(),aP=zod.z.object({Tokens:sP.nullish(),Nfts:oP.nullish()}).passthrough(),Sl=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:ne.nullish(),MinBalance:ne.nullish()}).passthrough(),sn=zod.z.object({Granted:zod.z.boolean(),Mode:gi.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:u.nullish(),Balances:zod.z.array(Sl).nullish()}).passthrough(),lP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:u.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:u.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(Sl).nullish()}).passthrough(),uP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),am=zod.z.object({Mode:gi.nullish(),TokenGates:zod.z.array(rm).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(uP).nullish(),Status:sn.nullish()}).passthrough(),cP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:u.nullish(),LoggedInAt:u.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(Sl).nullish()}).passthrough(),pP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:u.nullish()}).passthrough(),hP=zod.z.object({Version:zod.z.number().nullish(),Stats:aP.nullish(),LinkedWallets:zod.z.record(zod.z.string(),tP).nullish(),LastWalletLogin:cP.nullish(),PlayAccess:lP.nullish(),PendingWithdrawals:zod.z.array(om).nullish(),Kyc:nP.nullish(),FirstActivityAt:u.nullish(),LastActivityAt:u.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(pP).nullish()}).passthrough(),dP=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:ne,FrozenDelta:ne,UpdatedAt:u}).passthrough(),_n=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),dP).nullish(),PendingAdded:om.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),mP=zod.z.object({Amount:ne,Frozen:ne,CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough().transform(r=>r),fP=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:im.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:ne.nullish(),Status:Rl.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:ne.nullish(),NetPayoutAmount:ne.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:u.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:u.nullish(),RefundCheckedAt:u.nullish()}).passthrough(),gP=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:im.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:ne.nullish(),Status:Rl.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:u.nullish()}).passthrough(),lm=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),bl=zod.z.object({TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ContractAddress:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(lm).nullish(),Signature:zod.z.string().nullish()}).passthrough(),xl=zod.z.object({Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),ProgramID:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(lm).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),um=zod.z.object({Blockchain:Cl.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),$a).nullish()}).passthrough(),cm=zod.z.object({State:hP.nullish(),CryptoBalances:zod.z.record(zod.z.string(),mP).nullish()}).passthrough(),pm=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:ne.nullish(),AmountUsd:ne.nullish(),StateDelta:_n.nullish()}).passthrough(),hm=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),dm=zod.z.object({ServerTimeUtc:u.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:ne.nullish(),NetAmountNative:ne.nullish(),BurnAmountNative:ne.nullish(),AmountUsd:ne.nullish(),ExpiresAt:u.nullish(),EvmSignature:bl.nullish(),SolanaSignature:xl.nullish(),StateDelta:_n.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),mm=zod.z.object({ServerTimeUtc:u.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish(),EvmSignature:bl.nullish(),SolanaSignature:xl.nullish(),StateDelta:_n.nullish(),Inventory:K.nullish()}).passthrough(),fm=zod.z.object({TokenTransactions:zod.z.array(fP).nullish(),NFTTransactions:zod.z.array(gP).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Dl=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:ne.nullish(),AmountUsd:ne.nullish(),Target:zod.z.string().nullish()}).passthrough(),gm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:tm.nullish(),EvmSignature:bl.nullish(),SolanaSignature:xl.nullish()}).passthrough(),ym=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:Rl.nullish(),StateDelta:_n.nullish()}).passthrough(),it={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",DepositToken:"DepositToken",DepositNFT:"DepositNFT",RequestTokenWithdrawal:"RequestTokenWithdrawal",RequestNFTWithdrawal:"RequestNFTWithdrawal",GetTransactionHistory:"GetTransactionHistory",RetryWithdrawal:"RetryWithdrawal",ConfirmWithdrawal:"ConfirmWithdrawal",DonateToDeveloper:"DonateToDeveloper",DonateToUsersPool:"DonateToUsersPool",GetPlayAccess:"GetPlayAccess",ConfirmPlayAccess:"ConfirmPlayAccess"};var yP="Blockchain",Rm="Blockchain:Definitions",Or=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Rm,e);if(t)return B(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let n=this.ctx.authedRequest();if(!n)return l;let i=this.ctx.api.blockchain.getDefinitions(n).then(s=>(s.ok&&(this.ctx.data.config.patchSection(yP,s.data.Blockchain),this.ctx.data.config.patchSection(Rm,s.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",s.data)),s)).finally(()=>{this.definitionsInflight===i&&(this.definitionsInflight=null);});return this.definitionsInflight=i,i}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.depositToken(n);return i.ok&&(this.ctx.data.user.applyBlockchainStateDelta(i.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",i.data)),i}async depositNFT(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.depositNFT(n);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",i.data)),i}async requestTokenWithdrawal(e,t,n,i,s){if(!e)return h("client","CurrencyID is required.");if(!t)return h("client","NetworkID is required.");if(!n)return h("client","WalletAddress is required.");if(!i)return h("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return l;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=n,o.Amount=i,o.Category=Mr(s);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,n,i,s,o,p){if(!e)return h("client","ItemID is required.");if(!t)return h("client","NetworkID is required.");if(!n)return h("client","WalletAddress is required.");if(!i)return h("client","Amount is required.");let m=this.ctx.authedRequest();if(!m)return l;m.ItemID=e,m.NetworkID=t,m.WalletAddress=n,m.Amount=i,m.Category=Mr(s),o!==void 0&&(m.Level=o),p&&(m.ItemInstanceID=p);let g=await this.ctx.api.blockchain.requestNFTWithdrawal(m);return g.ok&&(this.ctx.data.user.applyBlockchainStateDelta(g.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(g.data.Resources,g.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",g.data)),g}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return l;t.Amount=String(e);let n=await this.ctx.api.blockchain.getTransactionHistory(t);return n.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",n.data),n}async retryWithdrawal(e){if(!e)return h("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.TitleTransactionID=e;let n=await this.ctx.api.blockchain.retryWithdrawal(t);return n.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",n.data),n}async confirmWithdrawal(e,t){if(!e)return h("client","TitleTransactionID is required.");if(!t)return h("client","On-chain TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.TitleTransactionID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.confirmWithdrawal(n);return i.ok&&(this.ctx.data.user.applyBlockchainStateDelta(i.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",i.data)),i}async donateToDeveloper(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.donateToDeveloper(n);return i.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",i.data),i}async donateToUsersPool(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.donateToUsersPool(n);return i.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",i.data),i}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.NetworkID=e);let n=await this.ctx.api.blockchain.confirmPlayAccess(t);return n.ok&&this.ctx.auth.setPlayAccess(n.data),n}};var RP={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Il=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),CP={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Pl=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),SP={Burn:"Burn",Ledger:"Ledger"},bP=zod.z.enum(["Burn","Ledger"]).catch("Burn"),qr={Item:"Item",VirtualCurrency:"VirtualCurrency"},vl=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),xP=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:Q.nullish()}).passthrough(),Ur=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(pi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Al=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:Q.nullish(),Sink:bP.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),xP).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),DP=zod.z.object({AllowedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedItemIDs:zod.z.array(zod.z.string()).nullish(),AllowUnstackableWithState:zod.z.boolean().nullish(),AllowedCurrencyIDs:zod.z.array(zod.z.string()).nullish(),DeniedCurrencyIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),IP=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:Pe.nullish(),BuyLimits:Pe.nullish(),ListingFeeOptions:de.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),PP=zod.z.object({Enabled:zod.z.boolean().nullish(),MinDurationHours:zod.z.number().nullish(),MaxDurationHours:zod.z.number().nullish(),AntiSnipeWindowSeconds:zod.z.number().nullish(),AntiSnipeExtensionSeconds:zod.z.number().nullish(),MaxAntiSnipeExtensions:zod.z.number().nullish(),MinBidStepPercent:zod.z.number().nullish(),MinBidStepAbsolute:Q.nullish(),BidLimits:Pe.nullish()}).passthrough(),vP=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:Pe.nullish(),FillLimits:Pe.nullish()}).passthrough(),AP=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:Pe.nullish()}).passthrough(),TP=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Tl=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:ee.nullish(),Schedule:Ce.nullish(),PricePolicy:Ur.nullish(),Commission:Al.nullish(),Tradability:DP.nullish(),Listings:IP.nullish(),Auctions:PP.nullish(),BuyOrders:vP.nullish(),DirectTrades:AP.nullish(),Matching:TP.nullish()}).passthrough(),Cm=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:Q.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:u.nullish()}).passthrough(),wP=zod.z.object({BidAxisType:wn.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:Q.nullish(),CurrentBid:Q.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(Cm).nullish()}).passthrough(),Er=zod.z.object({LastAt:u.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),kP=zod.z.object({Create:Er.nullish(),Buy:Er.nullish(),Sell:Er.nullish(),Bid:Er.nullish()}).passthrough(),zP=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),MP=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),EquippedSlot:zP.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Wt=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Il.nullish(),Status:Pl.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:Ne.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:vl.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:Q.nullish(),GoodsInstances:zod.z.array(MP).nullish(),Price:pe.nullish(),Auction:wP.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),OP=zod.z.object({GoodsType:vl.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(Il,Q).nullish()}).passthrough(),Sm=zod.z.object({Definitions:Tl.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),wl=zod.z.object({Offers:zod.z.array(Wt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),bm=zod.z.object({Groups:zod.z.array(OP).nullish()}).passthrough(),xm=zod.z.object({Offer:Wt.nullish()}).passthrough(),Ct=zod.z.object({OfferID:zod.z.string().nullish(),Status:Pl.nullish(),Settlement:Nt.nullish(),Resources:O.nullish(),CommissionTaken:pe.nullish(),HeldPayout:Rt.nullish()}).passthrough(),yi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:Wt.nullish(),Resources:O.nullish(),Matched:zod.z.boolean().nullish(),Settlement:Ct.nullish()}).passthrough(),Dm=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:Q.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish()}).passthrough(),Lr=zod.z.object({MyOffers:zod.z.array(Wt).nullish(),MyBids:zod.z.array(Wt).nullish(),MyBuyOrders:zod.z.array(Wt).nullish(),IncomingTrades:zod.z.array(Wt).nullish(),OutgoingTrades:zod.z.array(Wt).nullish(),Claimables:zod.z.array(Wt).nullish(),DrainedRefunds:zod.z.array(Cm).nullish(),Limits:kP.nullish(),PendingPayouts:zod.z.array(Rt).nullish(),ReleasedPayouts:zod.z.array(Rt).nullish(),VoidedPayouts:zod.z.array(Rt).nullish(),PayoutOperations:zod.z.array(O).nullish()}).passthrough(),EP=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Il.nullish(),FinalStatus:Pl.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:vl.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:Q.nullish(),PricePaid:pe.nullish(),CommissionTaken:pe.nullish(),CompletedAt:u.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),Im=zod.z.object({Entries:zod.z.array(EP).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Be={GetDefinitions:"GetDefinitions",GetGroupedOffers:"GetGroupedOffers",GetOffersByItem:"GetOffersByItem",GetOffer:"GetOffer",GetBuyOrders:"GetBuyOrders",GetMyState:"GetMyState",GetHistory:"GetHistory",CreateListing:"CreateListing",CancelListing:"CancelListing",Buy:"Buy",MarketBuy:"MarketBuy",MarketSell:"MarketSell",CreateAuction:"CreateAuction",PlaceBid:"PlaceBid",ClaimAuction:"ClaimAuction",CreateBuyOrder:"CreateBuyOrder",CancelBuyOrder:"CancelBuyOrder",FillBuyOrder:"FillBuyOrder",CreateDirectTrade:"CreateDirectTrade",RespondDirectTrade:"RespondDirectTrade",CancelDirectTrade:"CancelDirectTrade",ClaimBack:"ClaimBack"};var qP="Marketplace",Pm={key:"marketplace.myState",login:"MarketplaceMyState",ttlMs:6e4,dependsOn:["Marketplace"],invalidateOn:["marketplace:listingCreated","marketplace:listingCancelled","marketplace:bought","marketplace:marketBought","marketplace:marketSold","marketplace:auctionCreated","marketplace:bidPlaced","marketplace:auctionClaimed","marketplace:buyOrderCreated","marketplace:buyOrderCancelled","marketplace:buyOrderFilled","marketplace:directTradeCreated","marketplace:directTradeResponded","marketplace:directTradeCancelled","marketplace:claimedBack"]},Br=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Pm,{schema:Lr,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(qP,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,n,i=20){if(!e)return h("client","ItemID is required.");let s=this.ctx.authedRequest();if(!s)return l;s.ItemID=e,s.OfferTypeFilter=t,s.ContinuationToken=n,s.PageSize=i;let o=await this.ctx.api.marketplace.getOffersByItem(s);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.getOffer(t);return n.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",n.data),n}async getBuyOrders(e,t,n=20){let i=this.ctx.authedRequest();if(!i)return l;i.ItemID=e,i.ContinuationToken=t,i.PageSize=n;let s=await this.ctx.api.marketplace.getBuyOrders(i);return s.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",s.data),s}getMyState(e,t){return this.ctx.cache.read(Pm,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.MyBidsFilter=e);let n=await this.ctx.api.marketplace.getMyState(t);if(n.ok){for(let i of n.data.PayoutOperations??[])this.ctx.data.user.applyResourceOperation(i,this.ctx.data.config.itemDefinitions);this.applyMyState(n.data);}return n}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,n){let i=this.ctx.authedRequest();if(!i)return l;n&&(i.HistoryFilter=n),i.ContinuationToken=e,i.PageSize=t;let s=await this.ctx.api.marketplace.getHistory(i);return s.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",s.data),s}async createListing(e,t,n,i,s,o,p){if(!e)return h("client","ItemID is required.");if(!t)return h("client","CatalogID is required.");if(!i)return h("client","PriceBundle is required.");let m=this.ctx.authedRequest();if(!m)return l;m.ItemID=e,m.CatalogID=t,m.GoodsAmount=n,m.PriceBundle=i,m.DurationHours=s,m.ItemInstanceIDs=o,m.SelectedOptionID=p;let g=await this.ctx.api.marketplace.createListing(m);return this.applyCreateOfferResult(g,"marketplace:listingCreated"),g}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.buy(t);return n.ok&&(this.applyDualPartySettlement(n.data.Settlement),this.ctx.emitter.emit("marketplace:bought",n.data)),n}async marketBuy(e,t,n){if(!e||e<=0)return h("client","GoodsAmount must be positive.");if(!t)return h("client","PriceBundle is required.");let i=this.ctx.authedRequest();if(!i)return l;let s=this.applyGoodsSelector(i,n);if(s)return s;i.GoodsAmount=e,i.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(i);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,n){if(!e||e<=0)return h("client","GoodsAmount must be positive.");if(!t)return h("client","PriceBundle is required.");let i=this.ctx.authedRequest();if(!i)return l;let s=this.applyGoodsSelector(i,n);if(s)return s;i.GoodsAmount=e,i.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(i);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,n,i,s,o,p={}){if(!e)return h("client","ItemID is required.");if(!t)return h("client","CatalogID is required.");let m=this.ctx.authedRequest();if(!m)return l;m.ItemID=e,m.CatalogID=t,m.GoodsAmount=n,m.BidAxisType=i,m.BidCurrencyID=p.bidCurrencyID,m.BidCatalogID=p.bidCatalogID,m.BidItemID=p.bidItemID,m.StartingBid=s,m.DurationHours=o,m.ItemInstanceIDs=p.itemInstanceIDs,m.SelectedOptionID=p.selectedOptionID;let g=await this.ctx.api.marketplace.createAuction(m);return this.applyCreateOfferResult(g,"marketplace:auctionCreated"),g}async placeBid(e,t){if(!e)return h("client","OfferID is required.");if(!t||t<=0)return h("client","BidAmount must be positive.");let n=this.ctx.authedRequest();if(!n)return l;n.OfferID=e,n.BidAmount=t;let i=await this.ctx.api.marketplace.placeBid(n);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",i.data)),i}async claimAuction(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.claimAuction(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",n.data)),n}async createBuyOrder(e,t,n,i,s){if(!e)return h("client","ItemID is required.");if(!t)return h("client","CatalogID is required.");if(!i)return h("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return l;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=n,o.PriceBundle=i,o.DurationHours=s;let p=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.fillBuyOrder(t);return n.ok&&(this.applyDualPartySettlement(n.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",n.data)),n}async createDirectTrade(e,t,n,i,s){if(!e)return h("client","TargetUserID is required.");if(!t)return h("client","CatalogID is required.");if(!n)return h("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return l;o.TargetUserID=e,o.CatalogID=t,o.ItemID=n,o.ItemInstanceIDs=i,o.RequestedBundle=s;let p=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return h("client","OfferID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.OfferID=e,n.Accept=t;let i=await this.ctx.api.marketplace.respondDirectTrade(n);return i.ok&&(t&&(i.data.Settlement?this.applyDualPartySettlement(i.data.Settlement):i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",i.data)),i}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.claimBack(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",n.data)),n}async cancelOffer(e,t,n){if(!e)return h("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return l;i.OfferID=e;let s=await t(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(n,s.data)),s}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=qr.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=qr.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):h("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let n=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,n):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,n);}};var Gr=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return h("client","RoomName is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomName=e,n.Topology=t.topology,n.ChatMode=t.chatMode,n.MaxPlayers=t.maxPlayers,n.Visibility=t.visibility,n.JoinCode=t.joinCode,n.Mode=t.mode,n.Voice=t.voice;let i=await this.ctx.api.multiplayer.createRoom(n);return i.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",i.data),i}async joinRoom(e,t){if(!e)return h("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.JoinCode=t;let i=await this.ctx.api.multiplayer.joinRoom(n);return i.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",i.data),i}async leaveRoom(e,t={}){if(!e)return h("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.SuccessorUserID=t.successorUserID;let i=await this.ctx.api.multiplayer.leaveRoom(n,t.keepalive??false);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",i.data),i}async claimHost(e){if(!e)return h("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.RoomID=e;let n=await this.ctx.api.multiplayer.claimHost(t);return n.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",n.data),n}async kickMember(e,t,n=false){if(!e)return h("client","RoomID is required.");if(!t)return h("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return l;i.RoomID=e,i.TargetUserID=t,i.Ban=n;let s=await this.ctx.api.multiplayer.kickMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",s.data),s}async unbanMember(e,t){if(!e)return h("client","RoomID is required.");if(!t)return h("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.TargetUserID=t;let i=await this.ctx.api.multiplayer.unbanMember(n);return i.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",i.data),i}async listRooms(e=0,t=20){let n=this.ctx.authedRequest();if(!n)return l;n.Page=e,n.PageSize=t;let i=await this.ctx.api.multiplayer.listRooms(n);return i.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",i.data),i}async getRoom(e){if(!e)return h("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.RoomID=e;let n=await this.ctx.api.multiplayer.getRoom(t);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",n.data),n}async closeRoom(e){if(!e)return h("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.RoomID=e;let n=await this.ctx.api.multiplayer.closeRoom(t);return n.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",n.data),n}async poll(e,t){if(!e)return h("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.LastSeq=t;let i=await this.ctx.api.multiplayer.poll(n);return i.ok&&this.ctx.emitter.emit("multiplayer:polled",i.data),i}async sendSignal(e,t,n,i){if(!e)return h("client","RoomID is required.");if(!t)return h("client","TargetUserID is required.");if(!n)return h("client","SignalKind is required.");let s=this.ctx.authedRequest();if(!s)return l;s.RoomID=e,s.TargetUserID=t,s.SignalKind=n,s.Payload=i;let o=await this.ctx.api.multiplayer.sendSignal(s);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return h("client","RoomID is required.");if(!t)return h("client","ChatText is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.ChatText=t;let i=await this.ctx.api.multiplayer.sendChat(n);return i.ok&&this.ctx.emitter.emit("multiplayer:chatSent",i.data),i}async setMemberState(e,t,n){if(!e)return h("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return l;i.RoomID=e,i.Ready=t,i.MemberState=n;let s=await this.ctx.api.multiplayer.setMemberState(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",s.data),s}};var vm=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Nr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.ParentContentID=e.parentContentID,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):l}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return h("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):l}async getCreatorProfile(e,t,n){if(!e)return h("client","CreatorUserID is required.");let i=this.ctx.authedRequest();return i?(i.CreatorUserID=e,i.ContinuationToken=t,i.PageSize=n,this.ctx.api.workshop.getCreatorProfile(i)):l}async publish(e){if(!e.files||e.files.length===0)return h("client","At least one file is required.");let t=new Map,n=e.files.map((m,g)=>{if("sourceAssetUrl"in m)return {Role:m.role,ContentType:m.contentType,SourceAssetUrl:m.sourceAssetUrl};let j=Am(m.data,m.contentType);return t.set(g,j),{Role:m.role,ContentType:m.contentType,Size:j.size}}),i=e.thumbnail?Am(e.thumbnail.data,e.thumbnail.contentType):null,s=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:n,Thumbnail:e.thumbnail&&i?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:i.size}:void 0});if(!s.ok)return s;let o=s.data.Uploads??[];for(let m=0;m<o.length;m++){let g=o[m];if(!g||g.ServerCopy||!g.Url)continue;let j=t.get(m);if(!j)return h("client",`No bytes for file #${m+1}.`);let ce=await this.putBytes(g.Url,j,g.ContentType??j.type);if(!ce.ok)return ce}let p=s.data.ThumbnailUpload;if(p?.Url&&i){let m=await this.putBytes(p.Url,i,p.ContentType??i.type);if(!m.ok)return m}return this.ctx.credits.pay(m=>this.publishUploaded({CreditsConfirmationID:m,ContentID:s.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID}),e.credits)}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):l}async publishUploaded(e){if(!e.ContentID)return h("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return l;let n=await this.ctx.api.workshop.publish({...t,...e});return n.ok&&!n.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",n.data)),n}async updateContent(e,t){let n=this.contentRequest(e);if("ok"in n)return n;n.Title=t.title,n.Description=t.description,n.Tags=t.tags,n.Metadata=t.metadata,n.Visibility=t.visibility,n.Access=t.access;let i=await this.ctx.api.workshop.updateContent(n);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let n=await this.ctx.api.workshop.unpublish(t);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async getMyContent(e,t,n){let i=this.ctx.authedRequest();return i?(i.ContentType=e,i.ContinuationToken=t,i.PageSize=n,this.ctx.api.workshop.getMyContent(i)):l}async acquire(e,t){let n=this.contentRequest(e);if("ok"in n)return n;n.OptionID=t?.OptionID??void 0,n.ExpectedPrice=t?.Price??void 0;let i=await this.ctx.api.workshop.acquire(n);return i.ok&&(i.data.Settlement?this.applyDualPartySettlement(i.data.Settlement):this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",i.data)),i}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let n=[];for(let i of t.data.Files??[])if(i.Url)try{let s=await this.ctx.fetchImpl(i.Url);if(!s.ok)return h("connection",`Download failed (HTTP ${s.status}).`);n.push({role:i.Role??"main",contentType:i.ContentType??"application/octet-stream",data:await s.arrayBuffer()});}catch(s){return h("connection",`Download failed: ${s instanceof Error?s.message:String(s)}${vm}`)}return B({download:t.data,files:n})}async getMyLicenses(e,t){let n=this.ctx.authedRequest();return n?(n.ContinuationToken=e,n.PageSize=t,this.ctx.api.workshop.getMyLicenses(n)):l}async getMyFavorites(e,t){let n=this.ctx.authedRequest();return n?(n.ContinuationToken=e,n.PageSize=t,this.ctx.api.workshop.getMyFavorites(n)):l}async putBytes(e,t,n){try{let i=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":n},body:t});return i.ok?B(!0):h("connection",`Upload failed (HTTP ${i.status}).`)}catch(i){return h("connection",`Upload failed: ${i instanceof Error?i.message:String(i)}${vm}`)}}contentRequest(e){if(!e)return h("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):l}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let n=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,n):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,n);}};function Am(r,e){return r instanceof Blob?r:typeof r=="string"?new Blob([new TextEncoder().encode(r)],{type:e}):r instanceof Uint8Array?new Blob([r.slice().buffer],{type:e}):new Blob([r],{type:e})}var UP={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},LP=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),BP={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Tm=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),GP={Everyone:"Everyone",Owner:"Owner",Server:"Server"},wm=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),NP={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},_P=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),FP={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},VP=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),jP={Count:"Count",Sum:"Sum"},WP=zod.z.enum(["Count","Sum"]).catch("Count"),HP={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},KP=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),QP={Strict:"Strict",Loose:"Loose"},$P=zod.z.enum(["Strict","Loose"]).catch("Strict"),JP=zod.z.object({Kind:VP,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),ZP=zod.z.object({Type:Tm,ItemType:Tm.nullish(),Ref:JP.nullish(),Required:zod.z.boolean().optional(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),MaxItems:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish(),Unique:zod.z.boolean().optional(),UniqueIgnoreCase:zod.z.boolean().optional(),Indexed:zod.z.boolean().optional(),Visibility:wm.optional(),ClientWritable:zod.z.boolean().nullish(),Immutable:zod.z.boolean().optional(),Description:zod.z.string().nullish(),AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxFileBytes:zod.z.number().nullish()}),YP=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),_r=zod.z.object({Mode:_P,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),XP=zod.z.object({Read:zod.z.array(_r).nullish(),Create:zod.z.array(_r).nullish(),Update:zod.z.array(_r).nullish(),Delete:zod.z.array(_r).nullish()}),kl=zod.z.object({Cost:pe.nullish(),Grant:pe.nullish()}),ev=zod.z.object({ID:zod.z.string(),SortKey:zod.z.string(),PartitionField:zod.z.string().nullish(),PageSize:zod.z.number().optional(),MaxItems:zod.z.number().optional(),PublishItems:zod.z.boolean().optional()}),tv=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Namespace:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Enabled:zod.z.boolean().nullish(),Kind:LP,Mode:$P.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),ZP).nullish(),SortKeys:zod.z.array(YP).nullish(),Access:XP.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:KP.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:WP,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:wm.optional()})).nullish(),Economy:zod.z.object({OnCreate:kl.nullish(),OnUpdate:kl.nullish(),OnDelete:kl.nullish()}).nullish(),WriteGate:ee.nullish(),PublicViews:zod.z.array(ev).nullish(),AnonymousSearch:zod.z.boolean().nullish(),Integrations:zod.z.object({QuestMetricOnCreate:zod.z.string().nullish(),QuestMetricOnUpdate:zod.z.string().nullish(),QuestMetricOnDelete:zod.z.string().nullish(),AnalyticsEventOnCreate:zod.z.string().nullish(),AnalyticsEventOnUpdate:zod.z.string().nullish(),AnalyticsEventOnDelete:zod.z.string().nullish(),TriggerOnCreate:zod.z.string().nullish(),TriggerOnUpdate:zod.z.string().nullish(),TriggerOnDelete:zod.z.string().nullish()}).nullish(),Moderation:zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish()}).nullish()}),km=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),tv).default({})}),nv=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),zm=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),Fn=zod.z.object({Collection:zod.z.string(),ItemID:zod.z.string(),OwnerUserID:zod.z.string().nullish(),Data:zod.z.record(zod.z.string(),zod.z.unknown()).default({}),Version:zod.z.number(),CreatedAt:zod.z.string(),UpdatedAt:zod.z.string(),ExpireAt:zod.z.string().nullish(),Expanded:zod.z.record(zod.z.string(),zod.z.unknown()).nullish(),Files:zod.z.record(zod.z.string(),nv).nullish()}),zl=zod.z.object({Item:Fn}),Mm=zod.z.object({Items:zod.z.array(Fn).default([]),Missing:zod.z.array(zod.z.string()).default([])}),Ml=zod.z.object({Items:zod.z.array(Fn).default([]),NextCursor:zod.z.string().nullish()}),Om=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),Ol=zod.z.object({Item:Fn,AlreadyExists:zod.z.boolean().optional(),Economy:O.nullish()}),Em=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:O.nullish()}),qm=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),Um=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:Fn.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),Lm=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),Bm=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),Gm=zod.z.object({Version:zod.z.string(),Collection:zod.z.string(),View:zod.z.string(),SortKey:zod.z.string().nullish(),PageSize:zod.z.number(),UpdatedAt:zod.z.string(),BaseUrl:zod.z.string(),Partitions:zod.z.record(zod.z.string(),zod.z.object({Segment:zod.z.string(),Pages:zod.z.number(),Total:zod.z.number()})).default({})}),Nm=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(Fn).default([])}),iv={GetDefinitions:"GetDefinitions",Get:"Get",GetMany:"GetMany",Query:"Query",Count:"Count",Create:"Create",Update:"Update",Delete:"Delete",Batch:"Batch",GetCounter:"GetCounter",GetMyRoles:"GetMyRoles",BeginFileUpload:"BeginFileUpload"};var sv=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Vm=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,ql=100,_m=25,Fm=100;function rv(r,e,t){return {Field:r,Op:e,Value:t}}var Fr=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(l)}get(e,t,n={}){let i=pt(e)??Ri(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.get({...s,Collection:e,ItemID:t,Expand:n.expand}))}getMany(e,t,n={}){let i=pt(e);if(i)return Promise.resolve(i);let s=[...new Set(t.filter(o=>Vm.test(o)))];return s.length?s.length>Fm?Promise.resolve(h("client",`At most ${Fm} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:s,Expand:n.expand})):Promise.resolve(h("client","At least one valid item id is required."))}query(e,t={},n={}){let i=pt(e)??El(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.query({...s,Collection:e,Query:t,Expand:n.expand}))}async queryAll(e,t={},n={}){let i=Math.max(1,n.maxItems??500),s=[],o=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:o,Limit:t.Limit??ql},n);if(!p.ok)return p;if(s.push(...p.data.Items),o=p.data.NextCursor??void 0,!o||s.length>=i)return B(s.slice(0,i))}}count(e,t={}){let n=pt(e)??El(t);return n?Promise.resolve(n):this.call(i=>this.ctx.api.dataCollections.count({...i,Collection:e,Query:t}))}create(e,t,n={}){let i=pt(e)??(n.itemID?Ri(n.itemID):null);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.create({...s,Collection:e,ItemID:n.itemID,Data:t}))}update(e,t,n,i={}){let s=pt(e)??Ri(t);return s?Promise.resolve(s):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:n,ExpectedVersion:i.expectedVersion}))}set(e,t,n,i={}){return this.update(e,t,{Set:n},i)}increment(e,t,n,i=1){return this.update(e,t,{Inc:{[n]:i}})}delete(e,t,n={}){let i=pt(e)??Ri(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.delete({...s,Collection:e,ItemID:t,ExpectedVersion:n.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(h("client","Operations are empty."));if(e.length>_m)return Promise.resolve(h("client",`At most ${_m} operations per batch.`));let t=e.map(n=>pt(n.Collection)).find(n=>n!=null);return t?Promise.resolve(t):this.call(n=>this.ctx.api.dataCollections.batch({...n,Operations:e}))}getCounter(e,t,n){let i=pt(e);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.getCounter({...s,Collection:e,CounterID:t,Group:n}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,n,i){let s=pt(e);return s?Promise.resolve(s):t?i>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:n,FileSize:i})):Promise.resolve(h("client","File size must be positive.")):Promise.resolve(h("client","Field is required."))}async uploadFile(e,t,n,i={}){let s=i.contentType||n.type||"application/octet-stream",o=await this.beginFileUpload(e,t,s,n.size);if(!o.ok)return o;let p=await this.putBytes(o.data.UploadUrl,n,o.data.ContentType||s);return p.ok?o:p}async getPublicViews(e){let t=pt(e);if(t)return t;let n=this.publicViews.get(e);if(n)return B(n);let i=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return i.ok&&this.publicViews.set(e,i.data),i}async readPublicView(e,t,n={}){let i=await this.getPublicViews(e);if(!i.ok)return i;let s=i.data.Views[t];if(!s)return h("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(s,Gm);if(!o.ok)return o;let p=o.data.Partitions[n.partition??""],m=Math.max(1,n.page??1);if(!p||m>p.Pages)return B({pointer:o.data,page:{Page:m,HasMore:false,Items:[]}});let g=await this.fetchJson(`${o.data.BaseUrl}${p.Segment}/page-${m}.json`,Nm);return g.ok?B({pointer:o.data,page:g.data}):g}getPublic(e,t){let n=pt(e)??Ri(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let n=pt(e)??El(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(l)}async putBytes(e,t,n){try{let i=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":n},body:t});return i.ok?B(!0):h("connection",`Upload failed (HTTP ${i.status}).`)}catch(i){return h("connection",`Upload failed: ${i instanceof Error?i.message:String(i)}`)}}async fetchJson(e,t){let n;try{n=await this.ctx.fetchImpl(e);}catch{return h("connection","Internet Connection Error")}if(!n.ok)return h("server",`CDN answered ${n.status}.`);let i;try{i=await n.json();}catch{return h("server","CDN answer is not JSON.")}let s=t.safeParse(i);return s.success?B(s.data):h("server","CDN answer has an unexpected shape.")}};function pt(r){return sv.test(r??"")?null:h("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function Ri(r){return Vm.test(r??"")?null:h("client",`Item id '${r}' is invalid.`)}function El(r){return r.Limit!=null&&(r.Limit<1||r.Limit>ql)?h("client",`Limit must be 1..${ql}.`):(r.Where?.length??0)>8?h("client","At most 8 filters per query."):null}var Ul={Open:"Open",Declared:"Declared"},ov=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),av=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),jm=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),ov).nullish(),Dimensions:zod.z.array(av).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),rn={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Et={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Vr=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,lv={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},uv=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),Wm=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(uv).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Ll={LogEvents:"LogEvents"};function Hm(r,e=0){let t=r??"",n=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(n){let p=n[1]??"iPhone";return {osName:"iOS",osVersion:(n[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let i=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(i){let p=(i[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:i[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let s=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(s)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(s[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let o=/\bWindows NT (\d+\.\d+)/.exec(t);return o?{osName:"Windows",osVersion:o[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function Km(r){let e=typeof navigator>"u"?void 0:navigator,t=Hm(e?.userAgent??"",e?.maxTouchPoints??0),n={};r.appVersion&&(n.AppVersion=r.appVersion),t.osName&&(n.OsName=t.osName),t.osVersion&&(n.OsVersion=t.osVersion),t.deviceCategory&&(n.DeviceCategory=t.deviceCategory),t.deviceModel&&(n.DeviceModel=t.deviceModel);let i=r.locale||e?.language;return i&&(n.Language=i),n}var cv=25,pv=3e4,Qm=1800*1e3,$m=500,hv=5,dv=1e3,mv=3600*1e3,Jm="idos_analytics_queue",Bl="idos_analytics_pending",Gl="idos_analytics_opt_out",Zm="idos_analytics_first_open",Ym="idos_analytics_last_activity",Xm="idos_analytics_last_context",ef="idos_analytics_owner",jr=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;stopVisibility=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,n){return typeof e!="string"||!Vr.test(e)?h("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):fv(e)?h("client",`Event name "${e}" uses a reserved prefix (${Et.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,n,false))}logScreenView(e,t){if(!e)return h("client","screenName is required.");let n={screen_name:e};return t&&(n.screen_class=t),this.enqueue(rn.ScreenView,n,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return B(null);if(this.config()?.Enabled===false)return this.clear(),B(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return B(null);this.pending={BatchID:F(),Events:this.queue.splice(0,Et.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return l;let t=this.pending;this.flushing=true;try{let n=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return n.ok?(this.pending=null,n.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),n.data.Dropped&&n.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",n.data.Dropped),this.ctx.emitter.emit("analytics:flushed",n.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),n):(n.reason!=="throttled"&&t.Attempts++,(n.reason==="validation"||t.Attempts>=hv)&&(this.pending=null),this.persist(),n)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Gl);return}this.write(Gl,"1"),this.clear();}get isEnabled(){return this.read(Gl)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(ef);e&&t&&t!==e&&this.clear(),e&&this.write(ef,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},pv),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide),this.beginAutomatic(),this.flush();}async stop(){this.started&&(this.started=false,this.automaticDone=false,this.timer&&clearInterval(this.timer),this.drainTimer&&clearTimeout(this.drainTimer),this.timer=null,this.drainTimer=null,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null,this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),await this.flush());}beginAutomatic(){if(this.automaticDone||!this.started)return;if(this.config()?.Enabled!==true){this.stopWaitingForConfig??=this.ctx.emitter.on("title:publicConfigurationReceived",()=>this.beginAutomatic());return}this.automaticDone=true,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null;let e=Number(this.read(Ym)??"0");this.read(Zm)||(this.write(Zm,new Date().toISOString()),this.enqueue(rn.FirstOpen,void 0,void 0,true));let t=this.clientContext(),n=this.readJson(Xm);n?.AppVersion&&t.AppVersion&&n.AppVersion!==t.AppVersion&&this.enqueue(rn.AppUpdate,{previous_app_version:n.AppVersion},void 0,true),n?.OsVersion&&t.OsVersion&&n.OsVersion!==t.OsVersion&&this.enqueue(rn.OsUpdate,{previous_os_version:n.OsVersion},void 0,true),this.writeJson(Xm,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Qm)&&this.enqueue(rn.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=e=>{if(!e){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=Qm&&this.enqueue(rn.SessionStart,void 0,void 0,true),this.hiddenAt=null;};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,n,i){if(!this.isEnabled||this.disabledByServer)return B(null);let s=this.config();if(s?.Enabled===false)return B(null);if(i&&s?.AutomaticEvents===false)return B(null);if(s?.Events?.[e]?.Blocked)return h("client",`Event "${e}" is blocked by the title.`);if(!i&&s?.EventNaming?.toLowerCase()===Ul.Declared.toLowerCase()&&!s.Events?.[e])return h("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(n!==void 0&&!Number.isFinite(n))return h("client","value must be a finite number.");let o=gv(t);if(o.error)return h("client",o.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(p.Params=o.params),n!==void 0&&(p.Value=n),this.queue.push(p),this.queue.length>$m&&this.queue.splice(0,this.queue.length-$m),this.touch(),this.persist(),this.started&&this.queue.length>=cv&&this.flush(),B(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},dv));}dropStale(){let e=Date.now()-(Et.maxEventAgeMs-mv);this.queue=this.queue.filter(t=>{let n=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(n)||n>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=Km({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(Jm);Array.isArray(e)&&(this.queue=e.filter(n=>typeof n?.Name=="string").concat(this.queue));let t=this.readJson(Bl);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(Jm,this.queue),this.pending?this.writeJson(Bl,this.pending):this.remove(Bl);}touch(){this.write(Ym,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.host.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.host.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.host.storage.remove(this.key(e));}catch{}}readJson(e){let t=this.read(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}writeJson(e,t){this.write(e,JSON.stringify(t));}};function fv(r){let e=r.toLowerCase();return Et.reservedPrefixes.some(t=>e.startsWith(t))}function gv(r){if(!r)return {};let e=Object.keys(r);if(e.length===0)return {};if(e.length>Et.maxParams)return {error:`Too many parameters: ${e.length}, max ${Et.maxParams}.`};let t={};for(let n of e){if(!Vr.test(n))return {error:`Invalid parameter name "${n}".`};let i=r[n];typeof i=="string"?t[n]=i.length>Et.maxStringValueLength?i.slice(0,Et.maxStringValueLength):i:typeof i=="number"?Number.isFinite(i)&&(t[n]=i):typeof i=="boolean"&&(t[n]=i);}return {params:t}}var yv="idos_experiments",Wr=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return l;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let n=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),n.length>0&&this.ctx.emitter.emit("experiments:changed",n);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,n){let i=this.getParams(e)[t];if(i===void 0)return n;if(typeof n=="number"){let s=Number(i);return i.trim()!==""&&Number.isFinite(s)?s:n}if(typeof n=="boolean"){let s=i.trim().toLowerCase();return s==="true"||s==="1"?true:s==="false"||s==="0"?false:n}return i}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let i of e.Experiments??[])i?.ExperimentID&&t.set(i.ExperimentID,i);let n=[];for(let[i,s]of t){let o=this.views.get(i);(!o||o.VariantID!==s.VariantID||o.Status!==s.Status)&&n.push(s);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,n}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.host.storage.getString(this.key());if(!t)return;let n=JSON.parse(t);n?.UserID===e&&n.Data&&this.apply(n.Data);}catch{}}save(e,t){try{let n={UserID:e,Data:t};this.ctx.host.storage.setString(this.key(),JSON.stringify(n));}catch{}}key(){return `${yv}:${this.ctx.settings.titleID}`}};function on(r,e,t,n){let s=`api/v2/${r&&r.length>0?r:"0"}/Client/${e}/${t}`;return n==null?s:`${s}/${n}`}var _=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return on(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,n,i){return this.ctx.transport.post(this.endpoint(e,t),t,n,{...i,ticket:t.ClientSessionTicket})}};var Hr=class extends _{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Ll.LogEvents,e,Wm,{silent:true})}};var Rv=zod.z.object({VariantID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Weight:zod.z.number().nullish(),IsControl:zod.z.boolean().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Cv={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Sv=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),bv=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:Ce.nullish(),Gate:ee.nullish(),Variants:zod.z.array(Rv).nullish(),Salt:zod.z.string().nullish(),LayerID:zod.z.string().nullish(),StickyAssignment:zod.z.boolean().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Goals:zod.z.array(Sv).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),tf=zod.z.object({Experiments:zod.z.record(zod.z.string(),bv).nullish()}).passthrough(),xv={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Dv=zod.z.object({ExperimentID:zod.z.string().nullish(),VariantID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),nf=zod.z.object({Experiments:zod.z.array(Dv).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),Nl={GetExperiments:"GetExperiments"};var Kr=class extends _{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Nl.GetExperiments,e,nf)}};var Iv={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},sf=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Pv=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),rf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),Pv).nullish(),MissingKeyMode:sf.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),vv=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),of=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:vv.nullish()}).passthrough(),Qr={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Av=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),af=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:sf.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(Av).nullish()}).passthrough(),lf=zod.z.object({RequestedLocale:zod.z.string().nullish(),Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),NotModified:zod.z.boolean().nullish(),Entries:zod.z.record(zod.z.string(),zod.z.string()).nullish(),FallbackLocale:zod.z.string().nullish(),FallbackVersion:zod.z.number().nullish()}).passthrough();var Ci=zod.z.object({TitleConfigVersion:zod.z.string().nullish(),TitleConfigUrl:zod.z.string().nullish(),User:zod.z.unknown().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish(),Localization:of.nullish(),Views:zod.z.array(zod.z.object({Name:zod.z.string(),Key:zod.z.string().nullish(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().nullish()}).passthrough()).nullish(),PeerPayouts:xh.nullish()}).passthrough().transform(r=>r),uf=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(r=>r),cf=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),User:zod.z.unknown().nullish()}).passthrough().transform(r=>r),pf=zod.z.object({}).passthrough().transform(r=>r),hf=zod.z.object({}).passthrough().transform(r=>r),df=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:u.nullish(),LastActiveAt:u.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),mf=zod.z.object({Username:zod.z.string()}),St={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var ff=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:u.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,PlayAccess:sn.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:u.nullish(),ClientState:Ci.nullish()}),gf=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,RefreshToken:zod.z.string(),RefreshTokenExpiration:u.nullish(),PlayAccess:sn.nullish()}),Tv=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),yf=zod.z.object({Google:zod.z.object({Enabled:zod.z.boolean().nullish(),WebClientID:zod.z.string().nullish(),PlatformFallback:zod.z.boolean().nullish(),AndroidClientID:zod.z.string().nullish(),IosClientID:zod.z.string().nullish(),DesktopClientID:zod.z.string().nullish()}).passthrough().nullish(),Apple:zod.z.object({Enabled:zod.z.boolean().nullish(),BundleID:zod.z.string().nullish(),ServiceID:zod.z.string().nullish()}).passthrough().nullish(),PlayAccessMode:gi.nullish(),WalletLoginNetworks:zod.z.array(zod.z.object({NetworkID:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:zod.z.boolean().nullish(),NativeSso:Tv.nullish()}).passthrough(),Rf=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:u.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:sn.nullish()}).passthrough(),Cf=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:u.nullish(),PlayAccess:sn.nullish()}).passthrough(),Sf=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Ke=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:u.nullish()}),bf=zod.z.object({Message:zod.z.string(),ExpiresAt:u}),He={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",ResolvePlatformGameSession:"ResolvePlatformGameSession",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var $r=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return on(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,ff,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(He.RefreshSession),e,gf,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(He.GetAuthOptions),e,yf,{ticket:null})}linkWallet(e){return this.ctx.transport.post(on(this.ctx.settings.titleID,"Authentication",He.LinkWallet,e.UserID??""),e,Rf,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(on(this.ctx.settings.titleID,"Authentication",He.UnlinkWallet,e.UserID??""),e,Cf,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(He.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(He.LoginWithTelegram,e)}loginWithEmail(e){return this.login(He.LoginWithEmail,e)}loginWithGoogle(e){return this.login(He.LoginWithGoogle,e)}loginWithApple(e){return this.login(He.LoginWithApple,e)}loginWithSsoCode(e){return this.login(He.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(He.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(He.RegisterWithEmail),e,Sf,{ticket:null})}confirmEmailRegistration(e){return this.login(He.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(He.ResendVerificationCode),e,Ke,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(He.RequestWalletChallenge),e,bf,{ticket:null})}loginWithWallet(e){return this.login(He.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(He.ForgotPassword),e,Ke,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(He.ResetPassword),e,Ke,{ticket:null})}};var Jr=class extends _{constructor(e){super(e,"User");}getClientState(e){return this.send(St.GetClientState,e,Ci)}getClientStateExcept(e){return this.send(St.GetClientStateExcept,e,Ci)}getStateVersions(e){return this.send(St.GetStateVersions,e,uf)}getUserState(e){return this.send(St.GetUserState,e,cf)}getInventory(e){return this.send(St.GetInventory,e,pf)}getEventTokens(e){return this.send(St.GetEventTokens,e,hf)}getUsageTime(e){return this.send(St.GetUsageTime,e,df)}addUsageTime(e){return this.send(St.AddUsageTime,e,Ke,{silent:true})}deleteUserAccount(e){return this.send(St.DeleteUserAccount,e,Ke)}changeUsername(e){return this.send(St.ChangeUsername,e,mf)}};var Zr=class extends _{constructor(e){super(e,"Currency");}convert(e){return this.send(ui.Convert,e,gh)}spend(e){return this.send(ui.Spend,e,Rh)}cryptoConvert(e){return this.send(ui.CryptoConvert,e,yh)}};var wv=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),_l=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:O.nullish(),FodderConsumed:zod.z.array(wv).nullish()}),xf=zod.z.array(Oe(_l)),Yr={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},kv={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},zv=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Mv={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Ov=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Ev=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),qv=zod.z.object({Networks:zod.z.record(zod.z.string(),Ev).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),Uv=zod.z.object({FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),Lv=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),UseRequirements:zod.z.record(zod.z.string(),zod.z.number()).nullish(),AllowedCharacterIDs:zod.z.array(zod.z.string()).nullish(),AllowedSlotIDs:zod.z.array(zod.z.string()).nullish(),IdleRateBonus:zod.z.number().nullish()}).passthrough(),Bv=zod.z.object({ValuationMode:zv.nullish(),WeightCurve:Je.nullish(),Selection:Ov.nullish()}).passthrough(),Gv=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:de.nullish(),CostCurve:Je.nullish(),FlatBonusCurve:Je.nullish(),PercentBonusCurve:Je.nullish(),PowerCurve:Je.nullish(),Fodder:Bv.nullish()}).passthrough(),Nv=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),_v=zod.z.object({ItemID:zod.z.string(),CatalogID:zod.z.string(),ItemClass:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsStackable:zod.z.boolean().nullish(),IsTradable:zod.z.boolean().nullish(),Weight:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),NFT:qv.nullish(),Stats:Uv.nullish(),Equipment:Lv.nullish(),Upgrade:Gv.nullish(),Metadata:Nv.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),Fv=zod.z.object({Items:zod.z.record(zod.z.string(),_v).nullish()}).passthrough(),Vv={Cumulative:"Cumulative",HighestOnly:"HighestOnly"},jv=zod.z.enum(["Cumulative","HighestOnly"]).catch("Cumulative"),Wv=zod.z.object({Pieces:zod.z.number().nullish(),FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),Hv=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BonusMode:zod.z.enum(["Cumulative","HighestOnly"]).nullish().catch(null),Bonuses:zod.z.array(Wv).nullish()}).passthrough(),Kv=zod.z.object({BonusMode:jv.nullish()}).passthrough(),Xr=zod.z.object({Catalogs:zod.z.record(zod.z.string(),Fv).nullish(),Sets:zod.z.record(zod.z.string(),Hv).nullish(),SetSettings:Kv.nullish()}).passthrough();function we(r){return zod.z.unknown().transform((e,t)=>{let n=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(n!=null){let s=ye.safeParse(n);return s.success?{...e,CreditsConfirmation:s.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${s.error.message}`}),zod.z.NEVER)}let i=r.safeParse(e);return i.success?i.data:(t.addIssue({code:"custom",message:i.error.message}),zod.z.NEVER)})}var eo=class extends _{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(Yr.UpgradeLevel,e,we(_l))}upgradeLevelsBatch(e){return this.send(Yr.UpgradeLevelsBatch,e,xf)}};var to=class extends _{constructor(e){super(e,"Store");}purchase(e){return this.send(Ft.Purchase,e,Aa)}purchaseBatch(e){return this.send(Ft.PurchaseBatch,e,Ic)}getDefinitions(e){return this.send(Ft.GetDefinitions,e,cs)}getUserState(e){return this.send(Ft.GetUserState,e,Pc)}getStorefront(e){return this.send(Ft.GetStorefront,e,ps)}getCreditsConfirmation(e){return this.send(Ft.GetCreditsConfirmation,e,ye)}getCreditsBalance(e){return this.send(Ft.GetCreditsBalance,e,Dc)}};var Qv={Apple:"Apple",Google:"Google"},no=zod.z.object({PremiumID:zod.z.string().nullish(),PurchaseDate:zod.z.string().nullish(),ExpirationDate:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),IsAutoRenewEnabled:zod.z.boolean().nullish()}).passthrough(),io=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),no).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(r=>r),$v=zod.z.object({PremiumID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Tier:zod.z.number().nullish(),DurationDays:zod.z.number().nullish(),TrialDurationDays:zod.z.number().nullish(),PriceOptions:de.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Vl=zod.z.object({Definitions:zod.z.record(zod.z.string(),$v).nullish()}).passthrough(),Df=zod.z.object({Premium:Vl.nullish()}),If=zod.z.object({ServerTimeUtc:u.nullish(),Premium:io.nullish()}),so=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),Premium:io.nullish(),Subscription:no.nullish(),Resources:O.nullish()}),Rn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var Jv={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},Zv=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Pf=zod.z.object({StartUtc:u.nullish(),EndUtc:u.nullish(),Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),jl=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),Yv=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:$.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),Xv=zod.z.object({Rewards:J.nullish(),Rules:J.nullish(),Refund:J.nullish()}).passthrough(),eA=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:Zv.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:$.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:Pf.nullish(),Refund:jl.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:Yv.nullish(),Presets:Xv.nullish()}).passthrough(),tA=zod.z.object({StoreID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),PackageName:zod.z.string().nullish(),VerificationMode:zod.z.string().nullish(),PlayPublicKey:zod.z.string().nullish(),RequireCertificateChain:zod.z.boolean().nullish(),SecretName:zod.z.string().nullish(),IssuerID:zod.z.string().nullish(),KeyID:zod.z.string().nullish(),AcknowledgePurchases:zod.z.boolean().nullish(),NotificationPackageName:zod.z.string().nullish()}).passthrough(),nA=zod.z.object({Rewards:$.nullish()}).passthrough(),iA=zod.z.object({Rules:Pf.nullish()}).passthrough(),sA=zod.z.object({Refund:jl.nullish()}).passthrough(),rA=zod.z.object({Rewards:zod.z.record(zod.z.string(),nA).nullish(),Rules:zod.z.record(zod.z.string(),iA).nullish(),Refund:zod.z.record(zod.z.string(),sA).nullish()}).passthrough(),oA=zod.z.object({MaxPurchaseAgeDays:zod.z.number().nullish(),AllowSandbox:zod.z.boolean().nullish(),RequirePackageMatch:zod.z.boolean().nullish(),MaxReceiptsPerBatch:zod.z.number().nullish(),RefundCheckHorizonDays:zod.z.number().nullish(),RejectCrossUserReceipts:zod.z.boolean().nullish()}).passthrough(),aA=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),eA).nullish(),Stores:zod.z.record(zod.z.string(),tA).nullish(),Presets:rA.nullish(),Validation:oA.nullish(),Refund:jl.nullish()}).passthrough(),vf=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:u.nullish(),LastPurchasedAt:u.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Af=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:u.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:u.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:u.nullish()}).passthrough(),lA=zod.z.object({Products:zod.z.record(zod.z.string(),vf).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Af).nullish(),LastRefundCheckAt:u.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:u.nullish(),LastPurchaseAt:u.nullish()}).passthrough(),uA=zod.z.object({ProductID:zod.z.string(),Available:zod.z.boolean(),Owned:zod.z.boolean(),Blocked:zod.z.boolean(),Reason:zod.z.string().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Tf=zod.z.object({ServerTimeUtc:u,Purchase:aA.nullish(),Availability:zod.z.array(uA).nullish()}),wf=zod.z.object({ServerTimeUtc:u,Purchase:lA.nullish()}),cA={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},pA=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Wl=zod.z.object({ServerTimeUtc:u,Store:wi.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:pA.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish(),ProductState:vf.nullish(),Premium:io.nullish(),Subscription:no.nullish(),SubscriptionMirror:Af.nullish()}).passthrough(),kf=zod.z.object({ServerTimeUtc:u,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:u.nullish()}).passthrough(),zf=kt(Wl),Cn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var ro=class extends _{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(Cn.GetDefinitions,e,Tf)}getUserState(e){return this.send(Cn.GetUserState,e,wf)}validatePurchase(e){return this.send(Cn.ValidatePurchase,e,Wl)}validatePurchasesBatch(e){return this.send(Cn.ValidatePurchasesBatch,e,zf)}createTelegramInvoice(e){return this.send(Cn.CreateTelegramInvoice,e,kf)}};var hA=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Mf=zod.z.object({Reward:$.nullish(),Weight:zod.z.number().nullish(),AmountRange:hA.nullish()}).passthrough(),Vn=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(Mf).nullish()}).passthrough(),jn=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(Mf).nullish()}).passthrough(),dA=zod.z.object({RewardSlots:zod.z.array(Vn).nullish()}).passthrough(),mA=zod.z.object({PityRules:zod.z.array(jn).nullish()}).passthrough(),oo=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),dA).nullish(),PityPresets:zod.z.record(zod.z.string(),mA).nullish()}).passthrough();var fA=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),Of=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish(),Results:zod.z.array(O).nullish(),TriggeredPity:zod.z.array(fA).nullish()}),gA=zod.z.object({RewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),yA=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:Q.nullish()}).passthrough(),RA=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:de.nullish(),RewardSlots:zod.z.array(Vn).nullish(),PityRules:zod.z.array(jn).nullish(),Presets:gA.nullish(),RewardMultiplier:Ui.nullish(),SupplyLimits:zod.z.array(yA).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),CA=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Hl=zod.z.object({Definitions:zod.z.record(zod.z.string(),RA).nullish(),RewardPools:oo.nullish(),Settings:CA.nullish()}).passthrough(),Ef=zod.z.object({LootboxDefinitions:Hl.nullish()}),ao={GetDefinitions:"GetDefinitions",Open:"Open"};var lo=class extends _{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(ao.GetDefinitions,e,Ef)}open(e){return this.send(ao.Open,e,we(Of))}};var SA=zod.z.object({}).passthrough().transform(r=>r),bA=zod.z.object({}).passthrough().transform(r=>r),xA=zod.z.object({}).passthrough().transform(r=>r),DA=zod.z.object({}).passthrough().transform(r=>r),IA=zod.z.object({}).passthrough().transform(r=>r),PA=zod.z.object({}).passthrough().transform(r=>r),qf=zod.z.object({ServerTimeUtc:u,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:SA,Resources:O.nullish(),Inventory:K.nullish()}),Uf=zod.z.object({ServerTimeUtc:u,AccrualID:zod.z.string(),AccruedSeconds:Q.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:bA,Resources:O.nullish(),Inventory:K.nullish()}),Lf=zod.z.object({ServerTimeUtc:u,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:xA,Resources:O.nullish(),Inventory:K.nullish()}),Bf=zod.z.object({ServerTimeUtc:u,ClaimID:zod.z.string(),ClaimState:DA,Resources:O.nullish(),Inventory:K.nullish()}),vA={None:"None",Ad:"Ad",Vip:"Vip"},Gf=zod.z.object({ServerTimeUtc:u,WindowID:zod.z.string(),Boost:zod.z.string().nullish(),BaseAmount:Q.nullish(),Multiplier:zod.z.number().nullish(),Granted:Q.nullish(),WindowState:IA,Resources:O.nullish(),Inventory:K.nullish()}),Nf=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:Q.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),AA=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),TA=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:$.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Si=zod.z.object({Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),Kl=zod.z.object({Availability:J.nullish()}).passthrough(),wA=zod.z.object({Availability:zod.z.record(zod.z.string(),Si).nullish()}).passthrough(),kA=zod.z.object({CalendarID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Days:zod.z.array(TA).nullish(),IsLooping:zod.z.boolean().nullish(),MissBehavior:zod.z.string().nullish(),ResetByDays:zod.z.number().nullish(),MissThresholdMultiplier:zod.z.number().nullish(),ClaimMode:zod.z.string().nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),Availability:Si.nullish(),Presets:Kl.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),zA=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),MA=zod.z.object({BaseRatePerSecond:zod.z.number().nullish(),PowerCoefficient:zod.z.number().nullish(),BoardRankCoefficient:zod.z.number().nullish(),EquipmentBonusEnabled:zod.z.boolean().nullish(),EquipmentCharacterID:zod.z.string().nullish(),PremiumMultipliers:zod.z.array(zA).nullish()}).passthrough(),OA=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Si.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),EA=zod.z.object({AccrualID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rate:MA.nullish(),Rewards:$.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:OA.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),qA=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:$.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),UA=zod.z.object({ComebackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(qA).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Si.nullish(),Presets:Kl.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),LA=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxClaimsPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish(),TotalClaimLimit:zod.z.number().nullish()}).passthrough(),BA=zod.z.object({ClaimID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Mode:zod.z.string().nullish(),Rewards:$.nullish(),PremiumLimitOverrides:zod.z.array(LA).nullish(),Availability:Si.nullish(),Presets:Kl.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),GA=zod.z.object({CurrencyID:zod.z.string().nullish(),MaxBaseAmount:zod.z.number().nullish(),AdPlacementID:zod.z.string().nullish(),AdMultiplier:zod.z.number().nullish(),VipMultiplier:zod.z.number().nullish(),VipPremiumID:zod.z.string().nullish(),Limits:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),Ql=zod.z.object({TierRewards:AA.nullish(),MilestoneRewardMultiplier:Ui.nullish(),DailyCalendars:zod.z.record(zod.z.string(),kA).nullish(),IdleAccruals:zod.z.record(zod.z.string(),EA).nullish(),Comebacks:zod.z.record(zod.z.string(),UA).nullish(),Claims:zod.z.record(zod.z.string(),BA).nullish(),Windows:zod.z.record(zod.z.string(),GA).nullish(),Presets:wA.nullish()}).passthrough(),_f=zod.z.object({RewardDefinitions:Ql.nullish()}),Ff=zod.z.object({Rewards:PA.nullish()}),qt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var uo=class extends _{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(qt.GetRewardDefinitions,e,_f)}getUserRewardsState(e){return this.send(qt.GetUserRewardsState,e,Ff)}getMilestoneRewardMultiplier(e){return this.send(qt.GetMilestoneRewardMultiplier,e,Nf)}claimDailyReward(e){return this.send(qt.ClaimDailyReward,e,qf)}collectIdleAccrual(e){return this.send(qt.CollectIdleAccrual,e,Uf)}claimComebackReward(e){return this.send(qt.ClaimComebackReward,e,Lf)}claimReward(e){return this.send(qt.ClaimReward,e,Bf)}claimRewardWindow(e){return this.send(qt.ClaimRewardWindow,e,Gf)}};var co=class extends _{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(ft.GetTutorialDefinitions,e,rc)}getUserTutorialState(e){return this.send(ft.GetUserTutorialState,e,Gi)}startFlow(e){return this.send(ft.StartFlow,e,$t)}reportStepShown(e){return this.send(ft.ReportStepShown,e,$t)}completeStep(e){return this.send(ft.CompleteStep,e,$t)}completeStepsBatch(e){return this.send(ft.CompleteStepsBatch,e,lc)}skipStep(e){return this.send(ft.SkipStep,e,$t)}skipFlow(e){return this.send(ft.SkipFlow,e,$t)}claimFlowReward(e){return this.send(ft.ClaimFlowReward,e,ac)}resetFlow(e){return this.send(ft.ResetFlow,e,$t)}};var NA={Open:"Open",Application:"Application"},_A=zod.z.enum(["Open","Application"]).catch("Open"),FA={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Vf=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),VA={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},$l=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),jA={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var Sn={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},WA=zod.z.object({CampaignID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IsRunning:zod.z.boolean().nullish()}).passthrough(),jf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:_A.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:Vf.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(WA).nullish()}).passthrough(),HA=zod.z.object({Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),CountedMetrics:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ReachedMilestones:zod.z.array(zod.z.string()).nullish(),CappedBySubmissionLimit:zod.z.boolean().nullish(),CappedByCreatorLimit:zod.z.boolean().nullish(),NotPaidAsCopy:zod.z.boolean().nullish()}).passthrough(),KA=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:$l.nullish(),CurrencyID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),Granted:zod.z.number().nullish(),Paid:zod.z.number().nullish(),Overpaid:zod.z.number().nullish(),Claimable:zod.z.number().nullish(),BySubmission:zod.z.record(zod.z.string(),HA).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),QA=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:$l.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),Wf=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(KA).nullish(),Payouts:zod.z.array(QA).nullish()}).passthrough(),Hf=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:$l.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),$A=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),JA=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),Signature:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array($A).nullish()}).passthrough(),ZA=zod.z.object({Kind:zod.z.string().nullish(),Target:zod.z.string().nullish(),Required:zod.z.number().nullish(),Actual:zod.z.number().nullish(),Passed:zod.z.boolean().nullish()}).passthrough(),Kf=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:Vf.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(ZA).nullish()}).passthrough(),YA=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),XA=zod.z.object({ProgramID:zod.z.string().nullish(),Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(YA).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Qf=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:zod.z.number().nullish(),NetAmountNative:zod.z.number().nullish(),BurnAmountNative:zod.z.number().nullish(),AmountUsd:zod.z.number().nullish(),ExpiresAt:zod.z.string().nullish(),EvmSignature:JA.nullish(),SolanaSignature:XA.nullish(),StateDelta:_n.nullish()}).passthrough();var po=class extends _{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(Sn.GetCommunityMarketingState,e,jf)}getEarnings(e){return this.send(Sn.GetEarnings,e,Wf)}claim(e){return this.send(Sn.Claim,e,Hf)}checkJoinEligibility(e){return this.send(Sn.CheckJoinEligibility,e,Kf)}withdrawCryptoReward(e){return this.send(Sn.WithdrawCryptoReward,e,Qf)}};var ho=class extends _{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(tt.GetChatDefinitions,e,_c)}getChannels(e){return this.send(tt.GetChannels,e,Ds)}poll(e){return this.send(tt.Poll,e,Fc)}getHistory(e){return this.send(tt.GetHistory,e,Vc)}getConversations(e){return this.send(tt.GetConversations,e,Hc)}sendMessage(e){return this.send(tt.SendMessage,e,jc)}openDirectChannel(e){return this.send(tt.OpenDirectChannel,e,Wc)}markRead(e){return this.send(tt.MarkRead,e,Bn)}joinChannel(e){return this.send(tt.JoinChannel,e,Bn)}leaveChannel(e){return this.send(tt.LeaveChannel,e,Bn)}reportMessage(e){return this.send(tt.ReportMessage,e,Kc)}ignoreUser(e){return this.send(tt.IgnoreUser,e,Bn)}unignoreUser(e){return this.send(tt.UnignoreUser,e,Bn)}};var mo=class extends _{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(Gn.GetPushConfig,e,Jc)}subscribePush(e){return this.send(Gn.SubscribePush,e,ka)}unsubscribePush(e){return this.send(Gn.UnsubscribePush,e,Ke)}getPushSubscriptions(e){return this.send(Gn.GetPushSubscriptions,e,Zc)}};var fo=class extends _{constructor(e){super(e,"Localization");}send(e,t,n,i){let s=this.endpoint(e,t);return super.send(e,t,n,{throttleKey:t.Locale?`${s}:${t.Locale}`:s,...i})}getLocalizationManifest(e){return this.send(Qr.GetLocalizationManifest,e,af)}getLocalizationTable(e){return this.send(Qr.GetLocalizationTable,e,lf)}};var go=class extends _{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(It.GetQuestDefinitions,e,Bi)}getUserQuestState(e){return this.send(It.GetUserQuestState,e,Ku)}refreshQuestCycles(e){return this.send(It.RefreshQuestCycles,e,Ke)}claimQuestReward(e){return this.send(It.ClaimQuestReward,e,fa)}claimQuestRewardsBatch(e){return this.send(It.ClaimQuestRewardsBatch,e,Ju)}claimMilestoneReward(e){return this.send(It.ClaimMilestoneReward,e,ga)}claimMilestoneRewardsBatch(e){return this.send(It.ClaimMilestoneRewardsBatch,e,Zu)}claimGroupCompletionReward(e){return this.send(It.ClaimGroupCompletionReward,e,Qu)}addQuestProgress(e){return this.send(It.AddQuestProgress,e,$u)}};var yo=class extends _{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(yt.GetActiveEvents,e,ks)}getDefinitions(e){return this.send(yt.GetDefinitions,e,ws)}getUserLteState(e){return this.send(yt.GetUserLteState,e,tp)}grantTokens(e){return this.send(yt.GrantTokens,e,O)}spendTokens(e){return this.send(yt.SpendTokens,e,Oa)}claimMilestone(e){return this.send(yt.ClaimMilestone,e,Ea)}claimMilestonesBatch(e){return this.send(yt.ClaimMilestonesBatch,e,qa)}claimAllMilestones(e){return this.send(yt.ClaimAllMilestones,e,qa)}spendTokensBatch(e){return this.send(yt.SpendTokensBatch,e,np)}grantTokensBatch(e){return this.send(yt.GrantTokensBatch,e,ip)}};var Ro=class extends _{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ze.GetDefinitions,e,Ls)}getLeaderboard(e){return this.send(Ze.GetLeaderboard,e,oi)}getMyProgress(e){return this.send(Ze.GetMyProgress,e,Ms)}submitScore(e){return this.send(Ze.SubmitScore,e,Os)}submitScoreFromSource(e){return this.send(Ze.SubmitScoreFromSource,e,Os)}claimCycleReward(e){return this.send(Ze.ClaimCycleReward,e,Es)}claimMilestone(e){return this.send(Ze.ClaimMilestone,e,qs)}getFriendsLeaderboard(e){return this.send(Ze.GetFriendsLeaderboard,e,oi)}getLeaderboardsBatch(e){return this.send(Ze.GetLeaderboardsBatch,e,op)}getProgressBatch(e){return this.send(Ze.GetProgressBatch,e,Us)}claimCycleRewardsBatch(e){return this.send(Ze.ClaimCycleRewardsBatch,e,ap)}claimMilestonesBatch(e){return this.send(Ze.ClaimMilestonesBatch,e,lp)}submitScoresBatch(e){return this.send(Ze.SubmitScoresBatch,e,up)}claimAllRewardsBatch(e){return this.send(Ze.ClaimAllRewardsBatch,e,cp)}getOverviewBatch(e){return this.send(Ze.GetOverviewBatch,e,pp)}};var Co=class extends _{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Yt.GetDefinitions,e,Ns)}getActiveSeason(e){return this.send(Yt.GetActiveSeason,e,Gs)}getUserState(e){return this.send(Yt.GetUserState,e,Ua)}grantStatusTokens(e){return this.send(Yt.GrantStatusTokens,e,fp)}claimTierReward(e){return this.send(Yt.ClaimTierReward,e,La)}claimTierRewardsBatch(e){return this.send(Yt.ClaimTierRewardsBatch,e,gp)}};var So=class extends _{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Rn.GetDefinitions,e,Df)}getUserState(e){return this.send(Rn.GetUserState,e,If)}activateTrial(e){return this.send(Rn.ActivateTrial,e,so)}purchaseItemOrCurrency(e){return this.send(Rn.PurchaseWithResources,e,we(so))}purchaseRealMoney(e){return this.send(Rn.PurchaseRealMoney,e,so)}};var bo=class extends _{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send($e.GetCharacterDefinitions,e,js)}getUserCharacters(e){return this.send($e.GetUserCharacters,e,xp)}unlockCharacter(e){return this.send($e.UnlockCharacter,e,we(Na))}upgradeStatLevel(e){return this.send($e.UpgradeStatLevel,e,we(Ba))}upgradeCharacterLevel(e){return this.send($e.UpgradeCharacterLevel,e,we(Ga))}equipItems(e){return this.send($e.EquipItems,e,Dp)}unequipItems(e){return this.send($e.UnequipItems,e,Ip)}unequipAllCharacters(e){return this.send($e.UnequipAllCharacters,e,Pp)}unlockCharactersBatch(e){return this.send($e.UnlockCharactersBatch,e,zp)}upgradeCharacterLevelsBatch(e){return this.send($e.UpgradeCharacterLevelsBatch,e,Mp)}upgradeStatLevelsBatch(e){return this.send($e.UpgradeStatLevelsBatch,e,Op)}unlockSkin(e){return this.send($e.UnlockSkin,e,we(vp))}equipSkin(e){return this.send($e.EquipSkin,e,Ap)}unequipSkin(e){return this.send($e.UnequipSkin,e,Tp)}getCharacterSkins(e){return this.send($e.GetCharacterSkins,e,wp)}selectCharacter(e){return this.send($e.SelectCharacter,e,kp)}};var xo=class extends _{constructor(e){super(e,"Match");}createMatch(e){return this.send(Ot.CreateMatch,e,Oh)}updateMatch(e){return this.send(Ot.UpdateMatch,e,Eh)}cancelMatch(e){return this.send(Ot.CancelMatch,e,qh)}instantBattle(e){return this.send(Ot.InstantBattle,e,Uh)}saveStrategy(e){return this.send(Ot.SaveStrategy,e,Ke)}getMyMatches(e){return this.send(Ot.GetMyMatches,e,tl)}getAvailableMatches(e){return this.send(Ot.GetAvailableMatches,e,tl)}getDefinitions(e){return this.send(Ot.GetDefinitions,e,Nh)}};var eT={Arena:"Arena"},Jf=zod.z.string(),Wn={GetState:"GetState",RefreshOpponents:"RefreshOpponents",Attempt:"Attempt",ClaimMilestone:"ClaimMilestone"},tT=zod.z.object({TierID:zod.z.string().nullish(),MinPowerRatio:zod.z.number().nullish(),MaxPowerRatio:zod.z.number().nullish(),PointsOnWin:zod.z.number().nullish(),BotStatScale:zod.z.number().nullish()}).passthrough(),nT=zod.z.object({RuleID:zod.z.string().nullish(),Tiers:zod.z.array(tT).nullish(),RefreshCooldownSeconds:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),MaxCandidateReads:zod.z.number().nullish(),RevengeEnabled:zod.z.boolean().nullish(),RevengeCost:zod.z.number().nullish(),RevengePoints:zod.z.number().nullish(),WinReward:$.nullish()}).passthrough(),iT=zod.z.object({ChallengeID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),Mode:Jf.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AttemptCost:zod.z.number().nullish(),DailyAttemptLimit:zod.z.number().nullish(),Points:wt.nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),ClaimMode:zod.z.string().nullish(),Arena:nT.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),sT=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:Ce.nullish(),Challenges:zod.z.array(iT).nullish(),Ticket:wt.nullish(),Gate:ee.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Zf=zod.z.object({Chains:zod.z.record(zod.z.string(),sT).nullish()}).passthrough(),Yf=zod.z.object({TierID:zod.z.string().nullish(),OpponentID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Country:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BotStatScale:zod.z.number().nullish(),Defeated:zod.z.boolean().nullish()}).passthrough(),rT=zod.z.object({RevengeID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),AttackerUserID:zod.z.string().nullish(),AttackerName:zod.z.string().nullish(),AttackerAvatarUrl:zod.z.string().nullish(),AttackerPower:zod.z.number().nullish(),CreatedAtUtc:u.nullish(),Used:zod.z.boolean().nullish()}).passthrough(),oT=zod.z.object({AttemptID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),OpponentID:zod.z.string().nullish(),TierID:zod.z.string().nullish(),IsRevenge:zod.z.boolean().nullish(),Win:zod.z.boolean().nullish(),PointsGranted:zod.z.number().nullish(),TicketsSpent:zod.z.number().nullish(),AtUtc:u.nullish()}).passthrough(),aT=zod.z.object({Opponents:zod.z.array(Yf).nullish(),Revenges:zod.z.array(rT).nullish(),RevengeCost:zod.z.number().nullish(),RevengePoints:zod.z.number().nullish(),RefreshAvailableAtUtc:u.nullish()}).passthrough(),$f=zod.z.object({ChallengeID:zod.z.string().nullish(),Mode:Jf.nullish(),InstanceKey:zod.z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),AttemptCost:zod.z.number().nullish(),AttemptsToday:zod.z.number().nullish(),DailyAttemptLimit:zod.z.number().nullish(),PointsEarned:zod.z.number().nullish(),ClaimedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Arena:aT.nullish()}).passthrough(),lT=zod.z.object({ChainID:zod.z.string().nullish(),Tickets:zod.z.number().nullish(),Active:$f.nullish(),Ended:zod.z.array($f).nullish()}).passthrough(),uT=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),TicketsBurned:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),Converted:zod.z.number().nullish(),CarriedToInstanceKey:zod.z.string().nullish()}).passthrough(),Jl=zod.z.object({Chains:zod.z.array(lT).nullish(),ServerTimeUtc:u.nullish(),Burns:zod.z.array(uT).nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough(),Xf=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),Attempt:oT.nullish(),IsReplay:zod.z.boolean().nullish(),Battle:ci.nullish(),Opponent:Yf.nullish(),Tickets:zod.z.number().nullish(),PointsEarned:zod.z.number().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough(),eg=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough();var Do=class extends _{constructor(e){super(e,"Challenge");}getState(e){return this.send(Wn.GetState,e,Jl)}refreshOpponents(e){return this.send(Wn.RefreshOpponents,e,Jl)}attempt(e){return this.send(Wn.Attempt,e,Xf)}claimMilestone(e){return this.send(Wn.ClaimMilestone,e,eg)}};var cT={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},tg=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),pT={None:"None",Min:"Min",Average:"Average",Max:"Max",Weighted:"Weighted"},hT=zod.z.enum(["None","Min","Average","Max","Weighted"]).catch("None"),dT={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},mT=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),fT={Clamp:"Clamp",Reject:"Reject"},gT=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),yT=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),RT=zod.z.object({Index:zod.z.number().nullish(),BurnedItemIDs:zod.z.array(zod.z.string()).nullish(),RolledCollectionID:zod.z.string().nullish(),UsedCollections:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Output:Tt.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(yT).nullish()}),ng=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,Type:tg.nullish(),CraftID:zod.z.string(),CraftedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),InputRarity:zod.z.string().nullish(),OutputRarity:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish(),Results:zod.z.array(RT).nullish()}),CT=zod.z.object({CraftID:zod.z.string().nullish(),Type:tg.nullish(),CatalogID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),InputRarityID:zod.z.string().nullish(),OutputRarityID:zod.z.string().nullish(),RequiredItemCount:zod.z.number().nullish(),PriceOptions:de.nullish(),OutputLevelMode:hT.nullish(),OutputLevelWeightPower:zod.z.number().nullish(),InputSelection:mT.nullish(),OutputLevelOverflow:gT.nullish()}).passthrough(),Zl=zod.z.object({Definitions:zod.z.record(zod.z.string(),CT).nullish()}).passthrough(),ig=zod.z.object({ServerTimeUtc:u.nullish(),CraftDefinitions:Zl.nullish()}),Io={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Po=class extends _{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Io.GetDefinitions,e,ig)}craft(e){return this.send(Io.Craft,e,we(ng))}};var ST=2e5,vo=class extends _{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,we($s),{timeoutMs:ST,autoRetry:false})}readGeneration(e,t){return this.send(e,t,$s,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(je.GetDefinitions,e,jp)}generateText(e){return this.generate(je.GenerateText,e)}getText(e){return this.readGeneration(je.GetText,e)}generateImage(e){return this.generate(je.GenerateImage,e)}editImage(e){return this.generate(je.EditImage,e)}getImage(e){return this.readGeneration(je.GetImage,e)}generateVideo(e){return this.generate(je.GenerateVideo,e)}getVideo(e){return this.readGeneration(je.GetVideo,e)}generateAudio(e){return this.generate(je.GenerateAudio,e)}getAudio(e){return this.readGeneration(je.GetAudio,e)}generateMusic(e){return this.generate(je.GenerateMusic,e)}getMusic(e){return this.readGeneration(je.GetMusic,e)}generateFromTemplate(e){return this.generate(je.GenerateFromTemplate,e)}estimateTemplatePrice(e){return this.send(je.EstimateTemplatePrice,e,Vp,{throttleKey:`AI:EstimateTemplatePrice:${e.FeatureKey??""}:${JSON.stringify(e.Params??{})}`})}generateThreeD(e){return this.generate(je.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(je.GetThreeD,e)}listGenerations(e){return this.send(je.ListGenerations,e,_p)}getGeneration(e){return this.readGeneration(je.GetGeneration,e)}};var bT={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},xT=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),sg=zod.z.object({}).passthrough().transform(r=>r),Hn=zod.z.object({CollectibleID:zod.z.string(),Rarity:zod.z.number().nullish(),IsSpecial:zod.z.boolean().nullish(),IsDuplicate:zod.z.boolean().nullish(),CollectionCurrencyConverted:zod.z.number().nullish()}),rg=zod.z.object({GrantedCollectibles:zod.z.array(Hn).nullish(),DuplicateCollectibles:zod.z.array(Hn).nullish(),CollectionCurrencyEarned:Q.nullish()}),og=zod.z.object({CreditsConfirmation:ye.nullish(),OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(rg).nullish(),GrantedCollectibles:zod.z.array(Hn).nullish(),DuplicateCollectibles:zod.z.array(Hn).nullish(),CollectionCurrencyEarned:Q.nullish(),NewCollectionCurrencyBalance:Q.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),ag=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(rg).nullish(),GrantedCollectibles:zod.z.array(Hn).nullish(),DuplicateCollectibles:zod.z.array(Hn).nullish(),CollectionCurrencyEarned:Q.nullish(),NewCollectionCurrencyBalance:Q.nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),lg=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Yl=zod.z.object({SetID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish()}),ug=zod.z.array(Oe(Yl)),cg=zod.z.object({Resources:O.nullish(),Inventory:K.nullish()}),DT=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:Ne.nullish(),OfferedCollectibleID:zod.z.string().nullish(),OfferedCollectibleIsSpecial:zod.z.boolean().nullish(),ReceiverUserID:zod.z.string().nullish(),RequestedCollectibleID:zod.z.string().nullish(),RequestedCollectibleIsSpecial:zod.z.boolean().nullish(),Status:xT.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RespondedAtUtc:u.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),pg=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:u.nullish(),Resources:O.nullish()}),hg=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),dg=zod.z.object({OfferID:zod.z.string(),ReceivedCollectibleID:zod.z.string().nullish(),ReceivedIsSpecial:zod.z.boolean().nullish(),SentCollectibleID:zod.z.string().nullish(),SentCollectibleIsSpecial:zod.z.boolean().nullish(),Transfer:zod.z.unknown().nullish()}),mg=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),Xl=zod.z.object({Offers:zod.z.array(DT).nullish()}),IT=zod.z.object({CollectibleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rarity:zod.z.number().nullish(),HasSpecialVersion:zod.z.boolean().nullish(),SortOrder:zod.z.number().nullish()}).passthrough(),PT=zod.z.object({SetID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SortOrder:zod.z.number().nullish(),Collectibles:zod.z.array(IT).nullish(),SetCompletionReward:$.nullish()}).passthrough(),vT=zod.z.object({CollectionID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SeasonChainID:zod.z.string().nullish(),Sets:zod.z.array(PT).nullish(),GrandPrize:$.nullish()}).passthrough(),fg=zod.z.object({BonusRewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),AT=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:de.nullish(),BonusRewardSlots:zod.z.array(Vn).nullish(),PityRules:zod.z.array(jn).nullish(),Presets:fg.nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectibleCount:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),GuaranteeMaxRarity:zod.z.boolean().nullish(),RarityWeights:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ColorTier:zod.z.number().nullish()}).passthrough(),TT=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),wT=zod.z.object({CollectionChestID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectionCurrencyCost:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),MinCollectibleCount:zod.z.number().nullish(),MaxCollectibleCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),BonusRewardSlots:zod.z.array(Vn).nullish(),PityRules:zod.z.array(jn).nullish(),Presets:fg.nullish(),Tier:zod.z.number().nullish()}).passthrough(),kT=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),zT=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),Ao=zod.z.object({Collections:zod.z.record(zod.z.string(),vT).nullish(),PackTypes:zod.z.record(zod.z.string(),AT).nullish(),CollectionChests:zod.z.array(wT).nullish(),DuplicateConversions:zod.z.array(TT).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(kT).nullish(),RewardPools:oo.nullish(),Settings:zT.nullish()}).passthrough(),Xe={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var To=class extends _{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Xe.GetDefinitions,e,Ao)}getUserState(e){return this.send(Xe.GetUserState,e,sg)}openPack(e){return this.send(Xe.OpenPack,e,we(og))}openCollectionChest(e){return this.send(Xe.OpenCollectionChest,e,ag)}useCollectibleJoker(e){return this.send(Xe.UseCollectibleJoker,e,lg)}claimSetReward(e){return this.send(Xe.ClaimSetReward,e,Yl)}claimSetRewardsBatch(e){return this.send(Xe.ClaimSetRewardsBatch,e,ug)}claimGrandPrize(e){return this.send(Xe.ClaimGrandPrize,e,cg)}sendTradeOffer(e){return this.send(Xe.SendTradeOffer,e,pg)}cancelTradeOffer(e){return this.send(Xe.CancelTradeOffer,e,hg)}acceptTradeOffer(e){return this.send(Xe.AcceptTradeOffer,e,dg)}declineTradeOffer(e){return this.send(Xe.DeclineTradeOffer,e,mg)}getMyTradeOffers(e){return this.send(Xe.GetMyTradeOffers,e,Xl)}getIncomingTradeOffers(e){return this.send(Xe.GetIncomingTradeOffers,e,Xl)}};var wo=class extends _{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(vt.GetDefinitions,e,Xs)}getActiveEvent(e){return this.send(vt.GetActiveEvent,e,Kp)}getUserState(e){return this.send(vt.GetUserState,e,Ys)}getGroupState(e){return this.send(vt.GetGroupState,e,Ha)}joinOrCreateGroup(e){return this.send(vt.JoinOrCreateGroup,e,Ha)}spin(e){return this.send(vt.Spin,e,we($p))}claimObjectReward(e){return this.send(vt.ClaimObjectReward,e,Ka)}claimGrandPrize(e){return this.send(vt.ClaimGrandPrize,e,Ka)}leaveGroup(e){return this.send(vt.LeaveGroup,e,Jp)}};var ko=class extends _{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(Mt.GetDefinition,e,ah)}getUserState(e){return this.send(Mt.GetUserState,e,lh)}getActiveDeals(e){return this.send(Mt.GetActiveDeals,e,nr)}dismissDeal(e){return this.send(Mt.DismissDeal,e,ch)}executeNode(e){return this.send(Mt.ExecuteNode,e,we(uh))}recordShow(e){return this.send(Mt.RecordShow,e,ph)}claimMilestone(e){return this.send(Mt.ClaimMilestone,e,hh)}claimMilestonesBatch(e){return this.send(Mt.ClaimMilestonesBatch,e,dh)}};var MT=zod.z.object({}).passthrough().transform(r=>r),OT=zod.z.object({FeatureKey:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Rate:zod.z.number().nullish(),Basis:zod.z.string().nullish(),SourceCurrencyID:zod.z.string().nullish(),TargetCurrencyID:zod.z.string().nullish(),MinSourceAmount:zod.z.number().nullish(),MaxRewardPerOperation:zod.z.number().nullish(),Limits:Pe.nullish()}).passthrough(),eu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:$.nullish(),InviteRewards:zod.z.record(zod.z.string(),Ve).nullish(),SpendRewards:zod.z.array(OT).nullish(),Qualification:zod.z.object({}).passthrough().transform(r=>r).nullish()}).passthrough(),tu=zod.z.object({Pending:zod.z.boolean().nullish(),Qualified:zod.z.boolean().nullish(),Groups:zod.z.array(zod.z.object({GroupID:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Conditions:zod.z.array(zod.z.object({Type:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Current:zod.z.number().nullish(),Required:zod.z.number().nullish()}).passthrough()).nullish()}).passthrough()).nullish()}).passthrough(),gg=zod.z.object({ReferralDefinitions:eu.nullish()}).passthrough(),yg=zod.z.object({Referral:MT.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:tu.nullish()}).passthrough(),Rg=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:tu.nullish()}).passthrough(),Cg=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish(),QualificationPending:zod.z.boolean().nullish(),Qualification:tu.nullish()}).passthrough(),nu=zod.z.object({RewardID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),Sg=kt(nu),an={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var zo=class extends _{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(an.GetDefinitions,e,gg)}getUserState(e){return this.send(an.GetUserState,e,yg)}activateReferralCode(e){return this.send(an.ActivateReferralCode,e,Cg)}claimInviteReward(e){return this.send(an.ClaimInviteReward,e,nu)}claimInviteRewardsBatch(e){return this.send(an.ClaimInviteRewardsBatch,e,Sg)}checkQualification(e){return this.send(an.CheckQualification,e,Rg)}};var Mo=class extends _{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(ct.GetDefinitions,e,Ph)}getMessages(e){return this.send(ct.GetMessages,e,vh)}getUnreadCount(e){return this.send(ct.GetUnreadCount,e,or)}readMessages(e){return this.send(ct.ReadMessages,e,Za)}claimReward(e){return this.send(ct.ClaimReward,e,ar)}claimRewardsBatch(e){return this.send(ct.ClaimRewardsBatch,e,ar)}claimAll(e){return this.send(ct.ClaimAll,e,ar)}deleteMessages(e){return this.send(ct.DeleteMessages,e,Za)}sendGift(e){return this.send(ct.SendGift,e,Ah)}sendTransfer(e){return this.send(ct.SendTransfer,e,Th)}getGiftStatus(e){return this.send(ct.GetGiftStatus,e,wh)}};var Oo=class extends _{constructor(e){super(e,"Clan");}getDefinitions(e){return this.send(Le.GetDefinitions,e,td)}getMyClans(e){return this.send(Le.GetMyClans,e,Fh)}searchClans(e){return this.send(Le.SearchClans,e,ol)}getRecommendedClans(e){return this.send(Le.GetRecommendedClans,e,ol)}getClan(e){return this.send(Le.GetClan,e,Vh)}getClanMembers(e){return this.send(Le.GetClanMembers,e,Wh)}getRankings(e){return this.send(Le.GetRankings,e,Hh)}getApplications(e){return this.send(Le.GetApplications,e,al)}getMyInvites(e){return this.send(Le.GetMyInvites,e,al)}getClanLog(e){return this.send(Le.GetClanLog,e,Kh)}getRequests(e){return this.send(Le.GetRequests,e,$h)}getGifts(e){return this.send(Le.GetGifts,e,Jh)}getRewards(e){return this.send(Le.GetRewards,e,Zh)}getTreasury(e){return this.send(Le.GetTreasury,e,nd)}getProjects(e){return this.send(Le.GetProjects,e,id)}getActivities(e){return this.send(Le.GetActivities,e,sd)}getClanQuests(e){return this.send(Le.GetClanQuests,e,rd)}getCompetitions(e){return this.send(Le.GetCompetitions,e,od)}getBracket(e){return this.send(Le.GetBracket,e,ad)}getDiplomacy(e){return this.send(Le.GetDiplomacy,e,ld)}getRevenges(e){return this.send(Le.GetRevenges,e,ud)}getLeague(e){return this.send(Le.GetLeague,e,cd)}mutate(e,t){return this.send(e,t,ed)}};var Eo=class extends _{constructor(e){super(e,"Avatar");}getDefinitions(e){return this.send(Nn.GetDefinitions,e,mr)}getAvatars(e){return this.send(Nn.GetAvatars,e,hd)}getShop(e){return this.send(Nn.GetShop,e,dd)}buyItem(e){return this.send(Nn.BuyItem,e,md)}};var qo=class extends _{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(gr.RequestAdPermit,e,fd)}completeView(e){return this.send(gr.CompleteView,e,gd)}};var Uo=class extends _{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Ie.GetFriendsList,e,hi)}getIncomingRequests(e){return this.send(Ie.GetIncomingRequests,e,hi)}getOutgoingRequests(e){return this.send(Ie.GetOutgoingRequests,e,hi)}getRecommendedFriends(e){return this.send(Ie.GetRecommendedFriends,e,hi)}sendFriendRequest(e){return this.send(Ie.SendFriendRequest,e,di)}acceptFriendRequest(e){return this.send(Ie.AcceptFriendRequest,e,di)}declineFriendRequest(e){return this.send(Ie.DeclineFriendRequest,e,di)}removeFriend(e){return this.send(Ie.RemoveFriend,e,di)}getPlayerProfile(e){return this.send(Ie.GetPlayerProfile,e,xd)}getInbox(e){return this.send(Ie.GetInbox,e,Dd)}markInboxSeen(e){return this.send(Ie.MarkInboxSeen,e,mi)}getInboxUnread(e){return this.send(Ie.GetInboxUnread,e,mi)}follow(e){return this.send(Ie.Follow,e,nn)}unfollow(e){return this.send(Ie.Unfollow,e,nn)}getFollowers(e){return this.send(Ie.GetFollowers,e,Sr)}getFollowing(e){return this.send(Ie.GetFollowing,e,Sr)}block(e){return this.send(Ie.Block,e,nn)}unblock(e){return this.send(Ie.Unblock,e,nn)}getBlocked(e){return this.send(Ie.GetBlocked,e,Sr)}react(e){return this.send(Ie.React,e,nn)}unreact(e){return this.send(Ie.Unreact,e,nn)}getMyReactions(e){return this.send(Ie.GetMyReactions,e,Pd)}getEntityStates(e){return this.send(Ie.GetEntityStates,e,Id)}addComment(e){return this.send(Ie.AddComment,e,br)}editComment(e){return this.send(Ie.EditComment,e,br)}deleteComment(e){return this.send(Ie.DeleteComment,e,Ad)}getComments(e){return this.send(Ie.GetComments,e,vd)}report(e){return this.send(Ie.Report,e,Td)}};var ET={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var bn=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),qT=zod.z.object({BoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:de.nullish(),Effect:bn.nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),Lo=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),iu=zod.z.object({Availability:J.nullish(),Effects:J.nullish()}).passthrough(),UT=zod.z.object({ScheduledBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Effects:zod.z.array(bn).nullish(),Availability:Lo.nullish(),Presets:iu.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),LT=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(bn).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),BT=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Phases:zod.z.array(LT).nullish(),Availability:Lo.nullish(),Presets:iu.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),GT=zod.z.object({TriggeredBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Sources:zod.z.array(mt).nullish(),Effects:zod.z.array(bn).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:Lo.nullish(),Presets:iu.nullish()}).passthrough(),NT=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),_T=zod.z.object({Effects:zod.z.array(bn).nullish()}).passthrough(),FT=zod.z.object({Availability:zod.z.record(zod.z.string(),Lo).nullish(),Effects:zod.z.record(zod.z.string(),_T).nullish()}).passthrough(),VT=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),NT).nullish()}).passthrough(),Bo=zod.z.object({Definitions:zod.z.record(zod.z.string(),qT).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),UT).nullish(),BoostChains:zod.z.record(zod.z.string(),BT).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),GT).nullish(),Settings:VT.nullish(),Presets:FT.nullish()}).passthrough(),bg=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:bn.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:u.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:u.nullish()}).passthrough();var xg=zod.z.object({ServerTimeUtc:u.nullish(),Active:zod.z.record(zod.z.string(),bg).nullish()}),Dg=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:bg.nullish(),Resources:O.nullish()}),jT={Scheduled:"Scheduled",Chain:"Chain"},WT=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),Effects:zod.z.array(bn).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ig=zod.z.object({ServerTimeUtc:u.nullish(),Windows:zod.z.array(WT).nullish()}),xn={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Go=class extends _{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(xn.GetDefinitions,e,Bo)}getActive(e){return this.send(xn.GetActive,e,xg)}getActiveWindows(e){return this.send(xn.GetActiveWindows,e,Ig)}activate(e){return this.send(xn.Activate,e,we(Dg))}cleanupExpired(e){return this.send(xn.CleanupExpired,e,Ke)}};var No=class extends _{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(At.GetUserCustomDataDefinitions,e,Cr)}getMyUserCustomData(e){return this.send(At.GetMyUserCustomData,e,yd)}getPublicUserCustomDataOf(e){return this.send(At.GetPublicUserCustomDataOf,e,pl)}setPrivateData(e){return this.send(At.SetPrivateData,e,hl)}setPublicData(e){return this.send(At.SetPublicData,e,hl)}deleteKey(e){return this.send(At.DeleteKey,e,Ke)}batchSet(e){return this.send(At.BatchSet,e,Rd)}batchDelete(e){return this.send(At.BatchDelete,e,Cd)}batchGetPublicUserCustomDataOf(e){return this.send(At.BatchGetPublicUserCustomDataOf,e,Sd)}};var HT={Static:"Static",Runtime:"Runtime"},KT={Public:"Public",Private:"Private"},QT=zod.z.enum(["Client","Server","System"]).catch("Client"),$T=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),JT=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:QT.nullish(),ExpiresAt:u.nullish()}).passthrough(),Pg=zod.z.record(zod.z.string(),JT),su=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:Pg.nullish(),Runtime:Pg.nullish(),NotModified:zod.z.boolean().nullish()}),ZT=zod.z.object({KeyID:zod.z.string(),Scope:zod.z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:zod.z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:$T.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),_o=zod.z.object({Keys:zod.z.record(zod.z.string(),ZT).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),bi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Fo=class extends _{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(bi.GetTitleCustomDataDefinitions,e,_o)}getPublicTitleData(e){return this.send(bi.GetPublicTitleData,e,su)}getPublicTitleDataKeys(e){return this.send(bi.GetPublicTitleDataKeys,e,su)}};var vg=zod.z.object({Theme:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Radius:zod.z.number().nullish(),ButtonRadius:zod.z.number().nullish(),Outline:zod.z.number().nullish(),Background:zod.z.string().nullish(),MotionSpeed:zod.z.number().nullish(),MotionIntensity:zod.z.number().nullish(),Particles:zod.z.boolean().nullish(),SoundSet:zod.z.string().nullish()}).passthrough();var YT={Mesh:"Mesh",Host:"Host"},ru=zod.z.enum(["Mesh","Host"]).catch("Mesh"),XT={ServerRelay:"ServerRelay",P2P:"P2P"},ou=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),ew={Public:"Public",Private:"Private"},tw=zod.z.enum(["Public","Private"]).catch("Public"),nw={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},iw=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Ag=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),sw=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Tg=zod.z.object({SystemState:sw.nullish(),DefaultTopology:ru.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:ou.nullish(),AllowCreatorChatOverride:zod.z.boolean().nullish(),MaxPlayersPerRoom:zod.z.number().nullish(),RoomTtlSeconds:zod.z.number().nullish(),MaxRoomLifetimeSeconds:zod.z.number().nullish(),HeartbeatIntervalMs:zod.z.number().nullish(),MemberTimeoutMs:zod.z.number().nullish(),MaxSignalPayloadBytes:zod.z.number().nullish(),MaxChatTextLength:zod.z.number().nullish(),RoomLogCap:zod.z.number().nullish(),VoiceEnabled:zod.z.boolean().nullish(),RecordVoices:zod.z.boolean().nullish(),IceServers:zod.z.array(Ag).nullish()}).passthrough(),rw=zod.z.object({UserID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),Ready:zod.z.boolean().nullish(),State:zod.z.record(zod.z.string(),zod.z.string()).nullish(),JoinedAt:zod.z.number().nullish(),IsHost:zod.z.boolean().nullish(),LastSeenMs:zod.z.number().nullish()}).passthrough(),ow=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:ru.nullish(),ChatMode:ou.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),aw=zod.z.object({Seq:zod.z.number().nullish(),Type:iw.nullish(),FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Payload:zod.z.string().nullish(),Ts:zod.z.number().nullish()}).passthrough(),xi=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:ru.nullish(),ChatMode:ou.nullish(),Visibility:tw.nullish(),Status:zod.z.string().nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),Members:zod.z.array(rw).nullish(),IceServers:zod.z.array(Ag).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),wg=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),kg=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),au=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),zg=zod.z.object({Rooms:zod.z.array(ow).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Mg=zod.z.object({Envelopes:zod.z.array(aw).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Vo=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),st={CreateRoom:"CreateRoom",JoinRoom:"JoinRoom",LeaveRoom:"LeaveRoom",ListRooms:"ListRooms",GetRoom:"GetRoom",CloseRoom:"CloseRoom",Poll:"Poll",SendSignal:"SendSignal",SendChat:"SendChat",SetMemberState:"SetMemberState",ClaimHost:"ClaimHost",KickMember:"KickMember",UnbanMember:"UnbanMember"};var lu=zod.z.object({TitleCustomData:_o.nullish(),Character:js.nullish(),Item:Xr.nullish(),Currency:rr.nullish(),Store:cs.nullish(),Lootbox:Hl.nullish(),Quest:Bi.nullish(),TimedEvent:ws.nullish(),Leaderboard:Ls.nullish(),Season:Ns.nullish(),Reward:Ql.nullish(),Collection:Ao.nullish(),Craft:Zl.nullish(),DealOffer:Qa.nullish(),Premium:Vl.nullish(),TimedBoost:Bo.nullish(),CoopEvent:Xs.nullish(),GameLoop:Tr.nullish(),Match:nl.nullish(),Challenge:Zf.nullish(),Experiment:tf.nullish(),Blockchain:Cl.nullish(),Marketplace:Tl.nullish(),Multiplayer:Tg.nullish(),UserCustomData:Cr.nullish(),Referral:eu.nullish(),Localization:rf.nullish(),Analytics:jm.nullish(),Social:wd.nullish(),PlatformBridge:kd.nullish(),GameSpec:zod.z.string().nullish(),Look:vg.nullish(),Avatar:mr.nullish()}).passthrough();var Dn={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var jo=class extends _{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(Dn.GetTitlePublicConfiguration,e,lu)}getTitlePublicConfigurationExcept(e){return this.send(Dn.GetTitlePublicConfigurationExcept,e,lu)}getCurrencyDefinitions(e){return this.send(Dn.GetCurrencyDefinitions,e,rr)}getItemDefinitions(e){return this.send(Dn.GetItemDefinitions,e,Xr)}getServerTime(e){return this.send(Dn.GetServerTime,e,Ke)}};var Wo=class extends _{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(We.GetGameLoops,e,Tr)}getBoardDefinition(e,t=false){return this.send(We.GetBoardDefinition,e,Ar,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(We.GetBoardDefinitionForLevel,e,Ar,{silent:t})}getUserBoardState(e){return this.send(We.GetUserBoardState,e,Ed)}boardLoopRoll(e){return this.send(We.BoardLoopRoll,e,_d)}boardLoopAttack(e){return this.send(We.BoardLoopAttack,e,jd)}boardLoopRaid(e){return this.send(We.BoardLoopRaid,e,gl)}boardLoopRaidFast(e){return this.send(We.BoardLoopRaidFast,e,gl)}boardLoopBuild(e){return this.send(We.BoardLoopBuild,e,Wd)}boardSpecialChoose(e){return this.send(We.BoardSpecialChoose,e,we(Hd))}boardSpecialApplyMultiplier(e){return this.send(We.BoardSpecialApplyMultiplier,e,Kd)}boardRewardBoostApply(e){return this.send(We.BoardRewardBoostApply,e,Vd)}boardSpecialClaim(e){return this.send(We.BoardSpecialClaim,e,Qd)}getCommunityChestState(e){return this.send(We.GetCommunityChestState,e,Zd)}joinOrCreateCommunityChest(e){return this.send(We.JoinOrCreateCommunityChest,e,Yd)}claimCommunityChestMilestone(e){return this.send(We.ClaimCommunityChestMilestone,e,yl)}claimCommunityChestGrandPrize(e){return this.send(We.ClaimCommunityChestGrandPrize,e,yl)}leaveCommunityChest(e){return this.send(We.LeaveCommunityChest,e,Xd)}};var lw={Live:"Live",Latest:"Latest",Specific:"Specific"},uw={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},cw=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),pw={None:"None",Disabled:"Disabled",NoActiveRevision:"NoActiveRevision",RevisionNotFound:"RevisionNotFound",InvalidFieldName:"InvalidFieldName",RateLimited:"RateLimited",HandlerNotFound:"HandlerNotFound",HandlerDisabled:"HandlerDisabled",Timeout:"Timeout",StatementCountExceeded:"StatementCountExceeded",StackOverflow:"StackOverflow",ApiCallLimitExceeded:"ApiCallLimitExceeded",JavaScriptException:"JavaScriptException",ExecutionError:"ExecutionError"},hw=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),dw=zod.z.object({Level:cw,Message:zod.z.string().nullish(),Data:Xt.nullish()}),mw=zod.z.object({Error:hw,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Eg=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:Xt.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(dw).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:mw.nullish()}),uu={Execute:"Execute"};var Ho=class extends _{constructor(e){super(e,"CloudCode");}execute(e){return this.send(uu.Execute,e,Eg)}};var Ko=class extends _{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(it.GetDefinitions,e,um)}getUserState(e){return this.send(it.GetUserState,e,cm)}depositToken(e){return this.send(it.DepositToken,e,pm)}depositNFT(e){return this.send(it.DepositNFT,e,hm)}requestTokenWithdrawal(e){return this.send(it.RequestTokenWithdrawal,e,dm)}requestNFTWithdrawal(e){return this.send(it.RequestNFTWithdrawal,e,mm)}getTransactionHistory(e){return this.send(it.GetTransactionHistory,e,fm)}retryWithdrawal(e){return this.send(it.RetryWithdrawal,e,gm)}confirmWithdrawal(e){return this.send(it.ConfirmWithdrawal,e,ym)}donateToDeveloper(e){return this.send(it.DonateToDeveloper,e,Dl)}donateToUsersPool(e){return this.send(it.DonateToUsersPool,e,Dl)}getPlayAccess(e){return this.send(it.GetPlayAccess,e,am)}confirmPlayAccess(e){return this.send(it.ConfirmPlayAccess,e,sn)}};var Qo=class extends _{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Be.GetDefinitions,e,Sm)}getGroupedOffers(e){return this.send(Be.GetGroupedOffers,e,bm)}getOffersByItem(e){return this.send(Be.GetOffersByItem,e,wl)}getOffer(e){return this.send(Be.GetOffer,e,xm)}getBuyOrders(e){return this.send(Be.GetBuyOrders,e,wl)}getMyState(e){return this.send(Be.GetMyState,e,Lr)}getHistory(e){return this.send(Be.GetHistory,e,Im)}createListing(e){return this.send(Be.CreateListing,e,yi)}cancelListing(e){return this.send(Be.CancelListing,e,Ct)}buy(e){return this.send(Be.Buy,e,Ct)}marketBuy(e){return this.send(Be.MarketBuy,e,Ct)}marketSell(e){return this.send(Be.MarketSell,e,Ct)}createAuction(e){return this.send(Be.CreateAuction,e,yi)}placeBid(e){return this.send(Be.PlaceBid,e,Dm)}claimAuction(e){return this.send(Be.ClaimAuction,e,Ct)}createBuyOrder(e){return this.send(Be.CreateBuyOrder,e,yi)}cancelBuyOrder(e){return this.send(Be.CancelBuyOrder,e,Ct)}fillBuyOrder(e){return this.send(Be.FillBuyOrder,e,Ct)}createDirectTrade(e){return this.send(Be.CreateDirectTrade,e,yi)}respondDirectTrade(e){return this.send(Be.RespondDirectTrade,e,Ct)}cancelDirectTrade(e){return this.send(Be.CancelDirectTrade,e,Ct)}claimBack(e){return this.send(Be.ClaimBack,e,Ct)}};var $o=class extends _{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(st.CreateRoom,e,xi)}joinRoom(e){return this.send(st.JoinRoom,e,xi)}leaveRoom(e,t=false){return this.send(st.LeaveRoom,e,au,{keepalive:t})}listRooms(e){return this.send(st.ListRooms,e,zg)}getRoom(e){return this.send(st.GetRoom,e,xi)}closeRoom(e){return this.send(st.CloseRoom,e,au)}poll(e){return this.send(st.Poll,e,Mg)}sendSignal(e){return this.send(st.SendSignal,e,Vo,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(st.ClaimHost,e,xi)}kickMember(e){return this.send(st.KickMember,e,wg)}unbanMember(e){return this.send(st.UnbanMember,e,kg)}sendChat(e){return this.send(st.SendChat,e,Vo)}setMemberState(e){return this.send(st.SetMemberState,e,Vo)}};var fw={Free:"Free",Price:"Price",Holding:"Holding"},cu=zod.z.enum(["Free","Price","Holding"]).catch("Free"),gw={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},yw=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),Rw={All:"All",Any:"Any"},Cw=zod.z.enum(["All","Any"]).catch("All"),Sw={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},bw=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),xw={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},Dw=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),Iw={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Ug=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),Pw={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},vw={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},Aw=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),Tw=zod.z.object({Type:wn.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),MinLevel:zod.z.number().nullish()}).passthrough(),ww=zod.z.object({Requirements:zod.z.array(Tw).nullish(),Match:Cw.nullish(),Mode:yw.nullish()}).passthrough(),kw=zod.z.object({OptionID:zod.z.string().nullish(),Mode:cu.nullish(),Price:pe.nullish(),Holding:ww.nullish()}).passthrough(),zw=zod.z.object({AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxBytes:zod.z.number().nullish(),MaxCount:zod.z.number().nullish(),Required:zod.z.boolean().nullish()}).passthrough(),Mw=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),zw).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(cu).nullish(),PricePolicy:Ur.nullish(),PublishGate:ee.nullish(),PublishFeeOptions:de.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),Ow=zod.z.object({Allowed:zod.z.array(pi).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),Ew=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),qw=zod.z.object({MaxTitleLength:zod.z.number().nullish(),MaxDescriptionLength:zod.z.number().nullish(),MaxTags:zod.z.number().nullish(),MaxTagLength:zod.z.number().nullish(),MaxMetadataKeys:zod.z.number().nullish(),MaxMetadataValueLength:zod.z.number().nullish(),MaxAccessOptions:zod.z.number().nullish(),ThumbnailMaxBytes:zod.z.number().nullish()}).passthrough(),Uw=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Schedule:Ce.nullish(),Gate:ee.nullish(),Order:zod.z.number().nullish()}).passthrough(),Lw=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:ee.nullish(),Schedule:Ce.nullish(),ContentTypes:zod.z.record(zod.z.string(),Mw).nullish(),PricePolicy:Ur.nullish(),Commission:Al.nullish(),HoldingPolicy:Ow.nullish(),Moderation:Ew.nullish(),Limits:qw.nullish(),Featured:zod.z.array(Uw).nullish()}).passthrough(),Bw=zod.z.object({Acquisitions:zod.z.number().nullish(),Downloads:zod.z.number().nullish(),Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),ReportCount:zod.z.number().nullish(),Remixes:zod.z.number().nullish()}).passthrough(),In=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:Ne.nullish(),Title:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Metadata:zod.z.record(zod.z.string(),zod.z.string()).nullish(),ThumbnailUrl:zod.z.string().nullish(),Visibility:bw.nullish(),Access:zod.z.array(kw).nullish(),Status:Dw.nullish(),ModerationNote:zod.z.string().nullish(),Stats:Bw.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),PublishedAt:u.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),Gw=zod.z.object({OptionID:zod.z.string().nullish(),Mode:cu.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),Lg=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Order:zod.z.number().nullish()}).passthrough(),Bg=zod.z.object({Definitions:Lw.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish(),CanPublish:zod.z.record(zod.z.string(),zod.z.boolean()).nullish(),Collections:zod.z.array(Lg).nullish()}).passthrough(),Jo=zod.z.object({Items:zod.z.array(In).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Gg=zod.z.object({Content:In.nullish(),AccessState:zod.z.array(Gw).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Ng=zod.z.object({Collection:Lg.nullish(),Items:zod.z.array(In).nullish()}).passthrough(),_g=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:Ne.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(In).nullish()}).passthrough(),qg=zod.z.object({Role:zod.z.string().nullish(),Index:zod.z.number().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish(),ServerCopy:zod.z.boolean().nullish()}).passthrough(),Fg=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(qg).nullish(),ThumbnailUpload:qg.nullish(),ExpiresAt:u.nullish()}).passthrough(),Vg=zod.z.object({CreditsConfirmation:ye.nullish(),Content:In.nullish(),Resources:O.nullish()}).passthrough(),pu=zod.z.object({Content:In.nullish()}).passthrough(),jg=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Ug.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:Nt.nullish(),Resources:O.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Nw=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),Wg=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:Aw.nullish(),Files:zod.z.array(Nw).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:u.nullish()}).passthrough(),_w=zod.z.object({ContentID:zod.z.string().nullish(),Source:Ug.nullish(),OptionID:zod.z.string().nullish(),PricePaid:pe.nullish(),AcquiredAt:u.nullish(),Content:In.nullish()}).passthrough(),Hg=zod.z.object({Licenses:zod.z.array(_w).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),et={GetDefinitions:"GetDefinitions",Browse:"Browse",GetContent:"GetContent",GetCollection:"GetCollection",GetCreatorProfile:"GetCreatorProfile",BeginUpload:"BeginUpload",Publish:"Publish",UpdateContent:"UpdateContent",Unpublish:"Unpublish",GetMyContent:"GetMyContent",Acquire:"Acquire",GetDownload:"GetDownload",GetMyLicenses:"GetMyLicenses",GetMyFavorites:"GetMyFavorites"};var Zo=class extends _{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(et.GetDefinitions,e,Bg)}browse(e){return this.send(et.Browse,e,Jo)}getContent(e){return this.send(et.GetContent,e,Gg)}getCollection(e){return this.send(et.GetCollection,e,Ng)}getCreatorProfile(e){return this.send(et.GetCreatorProfile,e,_g)}beginUpload(e){return this.send(et.BeginUpload,e,Fg)}publish(e){return this.send(et.Publish,e,we(Vg))}updateContent(e){return this.send(et.UpdateContent,e,pu)}unpublish(e){return this.send(et.Unpublish,e,pu)}getMyContent(e){return this.send(et.GetMyContent,e,Jo)}acquire(e){return this.send(et.Acquire,e,jg)}getDownload(e){return this.send(et.GetDownload,e,Wg)}getMyLicenses(e){return this.send(et.GetMyLicenses,e,Hg)}getMyFavorites(e){return this.send(et.GetMyFavorites,e,Jo)}};var Yo=class extends _{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,n,i){return this.send(e,t,n,{throttleKey:`${this.endpoint(e,t)}|${i}`})}sendPublic(e,t,n,i){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,n,{throttleKey:`${o}|${i}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,km,"defs")}get(e){return this.sendKeyed("Get",e,zl,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Mm,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,Ml,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Om,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,Ol,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,Ol,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Em,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,Um,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,qm,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,Lm,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,zm,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Bm,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,zl,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,Ml,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Xo=class{settings;emitter;host;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;credits;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;challenge;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;clan;avatar;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.host=e.host??pa(),this.settings=gu(e,this.host),this.emitter=new $n,this.clientPlatform=e.clientPlatform??this.host.getClientPlatform(),this.acquisition=new dn(this.host),this.acquisition.capture(),this.playtime=new ii(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{}),this.host.supports.storePurchases&&this.purchase.restorePending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new Wi({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e.fetch,debugLogging:this.settings.debugLogging,throttleMs:e.throttleMs,maxRequestsPerSecond:e.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new $i(this.emitter),this.cache=new Zi(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:n})=>{this.userService.noteStateVersions(t,n);}),this.authStore=new Yi(this.host.storage,this.settings.titleID),this.api={authentication:new $r(this),user:new Jr(this),currency:new Zr(this),item:new eo(this),store:new to(this),purchase:new ro(this),lootbox:new lo(this),reward:new uo(this),quest:new go(this),tutorial:new co(this),communityMarketing:new po(this),chat:new ho(this),push:new mo(this),localization:new fo(this),timedEvent:new yo(this),leaderboard:new Ro(this),season:new Co(this),premium:new So(this),character:new bo(this),match:new xo(this),challenge:new Do(this),craft:new Po(this),ai:new vo(this),collection:new To(this),coopEvent:new wo(this),dealOffer:new ko(this),referral:new zo(this),mailbox:new Mo(this),clan:new Oo(this),avatar:new Eo(this),advertising:new qo(this),social:new Uo(this),timedBoost:new Go(this),userCustomData:new No(this),titleCustomData:new Fo(this),title:new jo(this),gameLoop:new Wo(this),cloudCode:new Ho(this),blockchain:new Ko(this),marketplace:new Qo(this),multiplayer:new $o(this),workshop:new Zo(this),dataCollections:new Yo(this),analytics:new Hr(this),experiment:new Kr(this)},this.userService=new ss(this),this.cache.attachState(this.userService),this.auth=new es(this),this.currency=new os(this),this.item=new as(this),this.store=new hs(this),this.credits=new ds(this),this.purchase=new ms(this),this.checkout=new fs(this),this.lootbox=new gs(this),this.reward=new Rs(this),this.quest=new Ts(this),this.tutorial=new Ss(this),this.communityMarketing=new bs(this),this.chat=new Is(this),this.push=new Ps(this),this.localization=new As(this),this.timedEvent=new zs(this),this.leaderboard=new Bs(this),this.season=new _s(this),this.premium=new Fs(this),this.character=new Ws(this),this.match=new Hs(this),this.challenge=new Ks(this),this.craft=new Qs(this),this.ai=new Js(this),this.collection=new Zs(this),this.coopEvent=new er(this),this.dealOffer=new ir(this),this.referral=new sr(this),this.mailbox=new lr(this),this.clan=new hr(this),this.avatar=new fr(this),this.ads=new yr(this),this.social=new xr(this),this.timedBoost=new Dr(this),this.userCustomData=new Ir(this),this.titleCustomData=new Pr(this),this.title=new vr(this),this.gameLoop=new kr(this),this.cloudCode=new zr(this),this.blockchain=new Or(this),this.marketplace=new Br(this),this.multiplayer=new Gr(this),this.workshop=new Nr(this),this.dataCollections=new Fr(this),this.analytics=new jr(this),this.experiments=new Wr(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.host.getFullURL(),RelatedEntityID:F()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var ea=class{ctx;constructor(e){this.ctx=new Xo(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,n={}){let i=this.ctx.buildAuthedBaseRequest(),s=on(this.ctx.settings.titleID,e,t,i.UserID??"");return this.ctx.transport.post(s,{...i,...n},zod.z.unknown(),{ticket:i.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get challenge(){return this.ctx.challenge}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get clan(){return this.ctx.clan}get avatar(){return this.ctx.avatar}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get host(){return this.ctx.host}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function Vw(r){return new ea(r)}var Kg="idos_sso",Qg="state",hu="idos:sso:state",jw="https://idosgames.com/sso/",Ww=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],Hw=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function Kw(){if(typeof window>"u")return false;let{origin:r}=window.location;return Ww.includes(r)||Hw.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function Qw(){if(typeof window>"u")return null;let r=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!r)return null;let e=new URLSearchParams(r),t=e.get(Kg);if(!t)return null;let n=e.get(Qg)??"",i=Xw();return tk(e),ek(),i&&n!==i?null:{code:t,state:n}}function $w(r){if(typeof window>"u")return;let e=r.returnTo??Jw(),t=Zw();Yw(t);let n=new URL(r.ssoUrl??jw);n.searchParams.set("title",r.titleID),n.searchParams.set("return_to",e),n.searchParams.set("state",t),window.location.assign(n.toString());}function Jw(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function Zw(){let r=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(r);else for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*256);return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function Yw(r){try{window.sessionStorage.setItem(hu,r);}catch{}}function Xw(){try{return window.sessionStorage.getItem(hu)}catch{return null}}function ek(){try{window.sessionStorage.removeItem(hu);}catch{}}function tk(r){r.delete(Kg),r.delete(Qg);let e=r.toString(),{pathname:t,search:n}=window.location;window.history.replaceState(null,"",`${t}${n}${e?`#${e}`:""}`);}var nk={EMAIL_SENDER_NOT_CONFIGURED:"Sign-in by e-mail is unavailable in this game right now. Try another way to sign in.",INVALID_VERIFICATION_CODE:"That code is not right. Check the e-mail and try again.",VERIFICATION_CODE_ATTEMPTS_EXCEEDED:"Too many wrong attempts. Ask for a new code.",INCORRECT_EMAIL_OR_PASSWORD:"Wrong e-mail or password.",INCORRECT_EMAIL:"That does not look like an e-mail address.",PASSWORD_LENGTH_INVALID:"The password must be 8 to 100 characters long.",TOO_MANY_FAILED_ATTEMPTS:"Too many attempts. Please try again a little later.",RATE_LIMIT_EXCEEDED:"Too many requests. Please try again in a moment.",APPLE_EMAIL_MISSING:"Apple did not share an e-mail address. Try again and allow it, or use another way to sign in.",INVALID_WALLET_SIGNATURE:"The signature does not match the wallet. Please try again.",WALLET_CHALLENGE_EXPIRED:"The request expired. Please try again.",WALLET_CHANGES_TOO_FREQUENT:"Too many wallets were changed this week. Try again in a few days.",WALLET_UNLINK_COOLDOWN:"This wallet was unlinked from another account less than 7 days ago. Try again after the 7 days.",PLAY_ACCESS_GUEST_DISABLED:"Guest play is off in this game. Sign in to link a crypto wallet.",PLAY_ACCESS_WALLET_LOGIN_ONLY:"This game can only be entered with a crypto wallet or your iDos Games account.",PLAY_ACCESS_WALLET_USED_BY_ANOTHER_ACCOUNT:"This wallet already plays with another account.",PLAY_ACCESS_WALLET_REQUIRED:"Link a crypto wallet to play.",PLAY_ACCESS_WALLET_NETWORK_NOT_GATED:"This wallet's network is not accepted here. Link a wallet of the required network.",PLAY_ACCESS_REQUIRED:"Check your balance to continue.",PLAY_ACCESS_CHECK_FAILED:"Could not check your balance right now. Please try again in a moment."};function ik(r,e="Something went wrong. Please try again."){return r?nk[r]??r:e}function sk(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function rk(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function ok(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function Jg(r,e,t,n=1){if(!r)return e;let i=r.Base??e,s=Math.max(0,t-n),o;switch(r.Shape??"Flat"){case "PerStep":o=i+(r.PerStep??0)*s;break;case "PerStepRate":o=i*(1+(r.PerStepRate??0)*s);break;case "Geometric":o=i*Math.pow(1+(r.GrowthRate??0),s);break;case "Table":o=i*$g(r,t,1);break;case "TableAbsolute":o=$g(r,t,i);break;default:o=i;break}return Number.isNaN(o)?i:(r.MinResult!=null&&o<r.MinResult&&(o=r.MinResult),r.MaxResult!=null&&o>r.MaxResult&&(o=r.MaxResult),o)}function ak(r,e,t=1){return Jg(r,1,e,t)}function lk(r){if(!r)return false;switch(r.Shape??"Flat"){case "PerStep":return (r.PerStep??0)!==0;case "PerStepRate":return (r.PerStepRate??0)!==0;case "Geometric":return (r.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return Zg(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function uk(r){if(Number.isNaN(r)||r<=0)return 0;if(!Number.isFinite(r))return Number.MAX_SAFE_INTEGER;let e=Math.round(r);return Math.abs(r-e)<=1e-9*Math.max(1,Math.abs(r))?e:Math.ceil(r)}function Zg(r){if(!r)return [];let e=[];for(let t of r)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function $g(r,e,t){let n=Zg(r.Points);if(n.length===0)return t;let i=null,s=null,o=null;for(let p of n)(o===null||p.AtStep>o.AtStep)&&(o=p),p.AtStep<=e&&(i===null||p.AtStep>=i.AtStep)&&(i=p),p.AtStep>e&&(s===null||p.AtStep<s.AtStep)&&(s=p);if(i===null)return t;if(s===null){let p=r.TailGrowthRate??0;return p===0?o.Value:o.Value*Math.pow(1+p,e-o.AtStep)}switch(r.Interpolation??"Step"){case "Linear":{let p=(e-i.AtStep)/(s.AtStep-i.AtStep);return i.Value+p*(s.Value-i.Value)}case "Geometric":{if(i.Value<=0||s.Value<=0){let m=(e-i.AtStep)/(s.AtStep-i.AtStep);return i.Value+m*(s.Value-i.Value)}let p=(e-i.AtStep)/(s.AtStep-i.AtStep);return i.Value*Math.pow(s.Value/i.Value,p)}default:return i.Value}}function Yg(r,e){return e?.BonusMode??r?.SetSettings?.BonusMode??"Cumulative"}function Xg(r,e,t){if(!r?.Bonuses||e<=0)return [];let n=r.Bonuses.filter(i=>!!i&&(i.Pieces??0)>0&&(i.Pieces??0)<=e).sort((i,s)=>(i.Pieces??0)-(s.Pieces??0));if(n.length===0)return [];if(t==="HighestOnly"){let i=n[n.length-1]?.Pieces??0;return n.filter(s=>(s.Pieces??0)===i)}return n}function ck(r,e){let t=e?.Sets,n=e?.Catalogs;if(!t||!r||!n||Object.keys(t).length===0)return [];let i=new Map;for(let[p,m]of Object.entries(r)){if(!p||p.startsWith("@")||!m?.ItemID)continue;let j=hk(n,m.ItemID,m.CatalogID??null)?.Metadata?.CollectionID;!j||!(j in t)||i.set(j,(i.get(j)??0)+1);}let s=[...i.keys()].sort((p,m)=>p<m?-1:p>m?1:0),o=[];for(let p of s){let m=t[p];if(!m)continue;let g=i.get(p)??0,j=Yg(e,m);o.push({SetID:p,Definition:m,Pieces:g,Mode:j,ActiveTiers:Xg(m,g,j)});}return o}function pk(r,e){if(!r||!e)return 0;let t=0;for(let n of Object.values(r))for(let i of Object.values(n?.Items??{}))i?.Metadata?.CollectionID===e&&t++;return t}function hk(r,e,t){if(t){let i=r[t]?.Items?.[e];if(i)return i}let n=null;for(let i of Object.values(r)){let s=i?.Items?.[e];if(s){if(n)return null;n=s;}}return n}var dk={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},du=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),mk={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},fk=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),gk=zod.z.object({PlacementID:zod.z.string().nullish(),Type:du.nullish(),Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),CreditsRewarded:zod.z.number().nullish(),AllowedProviderIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),yk=zod.z.object({DefaultCreditsPerView:zod.z.number().nullish(),MaxCreditsBalance:zod.z.number().nullish(),DailyCreditEarnCap:zod.z.number().nullish(),DailyViewCap:zod.z.number().nullish(),MinSecondsBetweenViews:zod.z.number().nullish()}).passthrough(),Rk=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),Ck=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:fk.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),Sk=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),bk=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),xk=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),DisableInterstitials:zod.z.boolean().nullish(),DisableBanners:zod.z.boolean().nullish(),DisableAppOpen:zod.z.boolean().nullish()}).passthrough(),Dk=zod.z.object({RequirePersonalizedAdsConsent:zod.z.boolean().nullish(),RequireTrackingConsent:zod.z.boolean().nullish(),CurrentPolicyVersion:zod.z.string().nullish(),RegulatedRegions:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ik=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),Pk=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:du.nullish()}).passthrough(),vk={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},Ak=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),Tk=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:Ak.nullish(),Enabled:zod.z.boolean().nullish(),Priority:zod.z.number().nullish(),AndroidAppID:zod.z.string().nullish(),IosAppID:zod.z.string().nullish(),WebAppID:zod.z.string().nullish(),Units:zod.z.record(zod.z.string(),Pk).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),gk).nullish(),Providers:zod.z.record(zod.z.string(),Tk).nullish(),RewardedVideo:yk.nullish(),Interstitial:Rk.nullish(),Banner:Ck.nullish(),AppOpen:Sk.nullish(),FrequencyCapping:bk.nullish(),PremiumAdReductions:zod.z.array(xk).nullish(),Consent:Dk.nullish(),Verification:Ik.nullish()}).passthrough();var wk=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),kk=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:u.nullish(),LastCompletedAt:u.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),zk=zod.z.object({Date:u.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),Mk=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:u.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),Ok=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:u.nullish(),ConsentRevokedAt:u.nullish()}).passthrough(),Ek=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:du.nullish(),IssuedAt:u.nullish(),ExpiresAt:u.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),qk=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:u.nullish()}).passthrough();zod.z.object({Credits:wk.nullish(),Placements:zod.z.record(zod.z.string(),kk).nullish(),Daily:zk.nullish(),Session:Mk.nullish(),LastImpressionAt:u.nullish(),LastInterstitialAt:u.nullish(),LastRewardedAt:u.nullish(),LastAppOpenAt:u.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:u.nullish(),Consent:Ok.nullish(),PendingRequests:zod.z.record(zod.z.string(),Ek).nullish(),FraudFlags:qk.nullish(),UpdatedAt:u.nullish()}).passthrough();
|
|
2
|
+
exports.AIAction=je;exports.AIErrorCode=LS;exports.AIGenerationStatus=fn;exports.AIModality=en;exports.AVATAR_MAX_USERS=dr;exports.AVATAR_SHOP_PAGE_SIZE=oD;exports.AcquisitionCapture=dn;exports.AdProviderKind=vk;exports.AdType=dk;exports.AdvertisingAction=gr;exports.AnalyticsAction=Ll;exports.AnalyticsDropReason=lv;exports.AnalyticsEventNaming=Ul;exports.AnalyticsLimits=Et;exports.AttackOutcome=jD;exports.AuthType=qe;exports.AuthenticationAction=He;exports.AutomaticEvent=rn;exports.AvatarAction=Nn;exports.AvatarErrors=rD;exports.BannerPosition=mk;exports.BlockchainAction=it;exports.BlockchainNetworkType=qI;exports.BlockchainOperationCategory=nm;exports.BlockchainTransactionStatus=jI;exports.BlockchainTransactionType=GI;exports.BodyPart=cx;exports.BoostWindowKind=jT;exports.BrowserFileStore=ln;exports.BrowserStorage=un;exports.CLAN_DEFAULT_KIND_ID=cr;exports.ChallengeAction=Wn;exports.ChallengeMode=eT;exports.CharacterAction=$e;exports.ChatAction=tt;exports.ChatAuthorType=PC;exports.ChatBlockedTermAction=DC;exports.ChatChannelType=RC;exports.ChatDirectAudience=bC;exports.ChatPartitioning=CC;exports.ChatReportReason=AC;exports.ClanAction=Le;exports.ClanCompetitionType=Mx;exports.ClanErrors=zx;exports.ClanInviteType=wx;exports.ClanJoinMode=Ax;exports.ClanPermission=kx;exports.ClanRelation=Ox;exports.ClientPlatform=Ge;exports.CloudCodeAction=uu;exports.CloudCodeErrorCode=pw;exports.CloudCodeLogLevel=uw;exports.CloudCodeRevisionSelection=lw;exports.CollectionAction=Xe;exports.CommissionSink=SP;exports.CommunityChestMemberStatus=vI;exports.CommunityChestStatus=PI;exports.CommunityCreatorStatus=FA;exports.CommunityMarketingAction=Sn;exports.CommunityMetricKind=jA;exports.CommunityParticipationMode=NA;exports.CommunityPayoutCurrencyKind=VA;exports.ConversionRateMode=qb;exports.CoopEventAction=vt;exports.CoopGroupStatus=YS;exports.CoopMemberStatus=XS;exports.CraftAction=Io;exports.CraftInputSelectionMode=dT;exports.CraftOutputLevelMode=pT;exports.CraftOutputLevelOverflow=fT;exports.CraftType=cT;exports.CreditsConfirmationStatus=ri;exports.CreditsError=JR;exports.CurrencyAction=ui;exports.CurrencyStatus=Eb;exports.CurrencyType=xt;exports.CurveInterpolation=By;exports.CurveShape=Uy;exports.CustomDataBucket=jt;exports.CustomDataValueType=yD;exports.CustomDataWriter=mD;exports.DEFAULT_BASE_URL=fu;exports.DataAccessMode=NP;exports.DataCollectionKind=UP;exports.DataCollectionSchemaMode=QP;exports.DataCollectionsAction=iv;exports.DataCounterKind=jP;exports.DataFieldType=BP;exports.DataFieldVisibility=GP;exports.DataOwnerDeletedPolicy=HP;exports.DataRefKind=FP;exports.DealComparisonOperator=yb;exports.DealNodeRuntimeStatus=ub;exports.DealNodeType=gb;exports.DealOfferAction=Mt;exports.DealOfferActivationStatus=lb;exports.EVENT_NAME_PATTERN=Vr;exports.EnvelopeType=nw;exports.EventTokenType=iy;exports.ExperimentAction=Nl;exports.ExperimentGoalKind=Cv;exports.FRIENDS_FROM_PLATFORM=ED;exports.FodderSelectionMode=Mv;exports.FodderValuationMode=kv;exports.FriendActionStatus=SD;exports.FriendSource=bD;exports.GameLoopAction=We;exports.IDosGamesClient=ea;exports.IapProductType=Jv;exports.IapPurchaseStatus=cA;exports.IapStoreValues=ny;exports.ItemAction=Yr;exports.ItemSetBonusMode=Vv;exports.KycStatus=NI;exports.KycTier=FI;exports.LeaderboardAction=Ze;exports.LocalizationAction=Qr;exports.LocalizationMissingKeyMode=Iv;exports.LootboxAction=ao;exports.MAILBOX_COUNTER_CAP=tx;exports.MailboxAction=ct;exports.MailboxCategory=$b;exports.MailboxErrors=ex;exports.MailboxLetterSource=Jb;exports.MailboxRewardModule=Yb;exports.MarketGoodsType=qr;exports.MarketOfferStatus=CP;exports.MarketOfferType=RP;exports.MarketplaceAction=Be;exports.MatchAction=Ot;exports.MatchStatus=px;exports.MemoryFileStore=Pn;exports.MemoryHost=Xn;exports.MemoryStorage=Zn;exports.MultiplayerAction=st;exports.MultiplayerChatMode=XT;exports.MultiplayerTopology=YT;exports.NATIVE_HOST_GLOBAL=Ru;exports.NATIVE_HOST_PROTOCOL=na;exports.NativeHost=ti;exports.OFFER_NOT_IN_ROTATION=gC;exports.PLATFORM_AD_MESSAGES=ua;exports.PLATFORM_AD_PROVIDER=ul;exports.PLATFORM_BRIDGE_ACK=xu;exports.PLATFORM_CREDITS_CONFIRM_FINAL=yy;exports.PLATFORM_CREDITS_CONFIRM_MESSAGES=ca;exports.PLATFORM_ORIGINS=Lt;exports.PLATFORM_PAGE_UNAVAILABLE=Du;exports.PLATFORM_SIGN_IN_MESSAGES=oa;exports.PLATFORM_TOPUP_MESSAGES=la;exports.PeerPayoutSource=Kb;exports.PeerPayoutStatus=Qb;exports.PlatformFriendsMode=UD;exports.PlatformProfileMode=qD;exports.PlayAccessMode=XI;exports.PlayerExperimentStatus=xv;exports.PlaytimeTracker=ii;exports.PremiumAction=Rn;exports.PurchaseAction=Cn;exports.PushAction=Gn;exports.PushPermissionState=nt;exports.PushTopic=_C;exports.PushTransport=GC;exports.QuestAction=It;exports.QuestObjectiveSource=$y;exports.QuestPrerequisiteMode=Zy;exports.QuestStatus=Hy;exports.RaidMode=FD;exports.ReferralAction=an;exports.ResourceEntryType=Ai;exports.RewardAction=qt;exports.RewardWindowBoost=vA;exports.RoomVisibility=ew;exports.SITE_FRAME_HIDDEN_MESSAGE=Ou;exports.SKIN_ALREADY_OWNED=qS;exports.SKIN_SLOT=Fa;exports.ScheduleMode=sy;exports.SeasonAction=Yt;exports.SocialAction=Ie;exports.SocialContentStatus=AD;exports.SocialEntityType=ID;exports.SocialInboxVerb=TD;exports.SocialReactionKind=PD;exports.SocialReportReason=vD;exports.SpecialChoiceMode=VD;exports.StoreAction=Ft;exports.StoreRotationMode=XR;exports.StoreType=Qv;exports.TimedBoostAction=xn;exports.TimedBoostStackingPolicy=ET;exports.TimedEventAction=yt;exports.TitleAction=Dn;exports.TitleCustomDataAction=bi;exports.TitleDataBucket=KT;exports.TitleDataScope=HT;exports.TradeOfferStatus=bT;exports.TransactionDirection=WI;exports.TutorialAction=ft;exports.TutorialBoardAction=hR;exports.TutorialFlowStatus=uR;exports.TutorialGateMode=ky;exports.TutorialRestartPolicy=aR;exports.TutorialScriptModule=pR;exports.TutorialStepCompletionMode=rR;exports.TypedEmitter=$n;exports.UserAction=St;exports.UserCustomDataAction=At;exports.WalletGateBalanceSource=JI;exports.WalletLinkType=LI;exports.WebHost=ni;exports.WorkshopAccessMode=fw;exports.WorkshopAccessVia=vw;exports.WorkshopAction=et;exports.WorkshopContentStatus=xw;exports.WorkshopHoldingMatch=Rw;exports.WorkshopHoldingMode=gw;exports.WorkshopLicenseSource=Iw;exports.WorkshopSort=Pw;exports.WorkshopVisibility=Sw;exports.activeSetTiers=Xg;exports.askPlatformPage=Bt;exports.authErrorText=ik;exports.beginSsoRedirect=$w;exports.claimedMilestoneIDs=rk;exports.countSetMembers=pk;exports.createDefaultHost=pa;exports.createIDosGamesClient=Vw;exports.cryptoShortfallFromError=En;exports.curveMultiplier=ak;exports.defineView=qR;exports.describeUserAgent=Hm;exports.effectiveSetMode=Yg;exports.evaluateCurve=Jg;exports.getTelegramWebApp=Kt;exports.grantedPremiumTiers=ok;exports.isAIGenerationTerminal=li;exports.isCurveConfigured=lk;exports.isFail=vy;exports.isMilestoneClaimed=sk;exports.isOk=Py;exports.isPlatformParentOrigin=cn;exports.isReservedSlot=IS;exports.isSsoAvailable=Kw;exports.normalizeBlockchainCategory=Mr;exports.parseAIErrorCode=BS;exports.readNativeHostGlobal=ia;exports.readSsoCodeFromUrl=Qw;exports.resolveItemSets=ck;exports.roundAmount=uk;exports.shareFallbackText=ei;exports.where=rv;exports.zPaymentProof=$R;exports.zPriceOption=ls;exports.zPriceOptions=de;
|