@idosgames/core 0.26.7 → 0.26.9
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 +9 -0
- package/dist/{GameHost-gNo-pSSn.d.cts → GameHost-CkI6loS9.d.cts} +19 -1
- package/dist/{GameHost-gNo-pSSn.d.ts → GameHost-CkI6loS9.d.ts} +19 -1
- package/dist/{VoiceController-B_LTQg7Y.d.cts → VoiceController-Bwa5nrlo.d.ts} +58 -12
- package/dist/{VoiceController-lifo36Qx.d.ts → VoiceController-Q7ykZCdU.d.cts} +58 -12
- package/dist/chunk-TFBN7PEL.js +2 -0
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/platform/index.cjs +2 -2
- package/dist/platform/index.d.cts +15 -3
- package/dist/platform/index.d.ts +15 -3
- 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-S24V5BGG.js +0 -2
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var zod=require('zod'),dn=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var dn__default=/*#__PURE__*/_interopDefault(dn);var Qn=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 du(r){return {get:e=>r.getString(e),set:(e,t)=>r.setString(e,t),remove:e=>r.remove(e)}}var mu="https://api.idosgames.com";function fu(r,e){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??mu).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??du(e.storage),locale:r.locale??e.getLanguage(),appVersion:r.appVersion??""}}function _(){return crypto.randomUUID()}var Yg="idos-host-files",xi="files";function Di(r){return new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function Xg(r){return r.slice().buffer}var In=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)}},an=class{db=null;fallback=new In;open(){return this.db||(this.db=(async()=>{try{if(typeof indexedDB>"u")return null;let e=indexedDB.open(Yg,1);return e.onupgradeneeded=()=>{e.result.objectStoreNames.contains(xi)||e.result.createObjectStore(xi,{keyPath:"key"});},await Di(e)}catch{return null}})()),this.db}async store(e){let t=await this.open();if(!t)return null;try{return t.transaction(xi,e).objectStore(xi)}catch{return null}}async read(e){let t=await this.store("readonly");if(!t)return this.fallback.read(e);try{let n=await Di(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:Xg(t),size:t.byteLength,updatedAt:Date.now()};return await Di(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 Di(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 $n(){return typeof document<"u"&&typeof document.createElement=="function"}function Ii(r={}){return $n()?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 gu="idos_device_id",ea="idos:platformSignIn:declined:",dt="UNAVAILABLE",Pn=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}),Wt=class{storage;files;visible=true;visibilityListeners=new Set;linkListeners=new Set;constructor(e,t=new In){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(gu);return e||(e=this.newDeviceID(),this.storage.setString(gu,e)),e}newDeviceID(){return _()}setSignInDeclined(e,t){t?this.storage.setString(ea+e,"1"):this.storage.remove(ea+e);}isSignInDeclined(e){return this.storage.getString(ea+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 Pi(r){return (typeof r=="number"?[r]:[...r]).map(t=>Math.max(0,Math.round(t)))}var ln=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{}}},Jn=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 bt={Virtual:"Virtual",Crypto:"Crypto"},An=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),vi={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},Tn=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),Ge={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Ai=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),ey={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Ti=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),ty={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Challenge:"Challenge",ChallengePoints:"ChallengePoints"},wi=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season","Challenge","ChallengePoints"]).catch("TimedEvent"),ny={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},Zn=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 Yn=class extends Wt{id="memory";supports;clientPlatform;deviceId;constructor(e={}){let t="getString"in e?{storage:e}:e;super(t.storage??new Jn),this.supports=Object.freeze({...Pn,...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 Xn(r){return [r.text,r.url].filter(e=>!!e).join(" ")}function ki(){return globalThis.crossOriginIsolated===true&&typeof SharedArrayBuffer<"u"}function zi(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 ta=1,yu="__IDOS_HOST__";function na(){let r=globalThis[yu];return !r||typeof r!="object"||r.protocol!==1||typeof r.post!="function"?null:r}var iy={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 sy(r){switch((r??"").toLowerCase()){case "android":return Ge.Android;case "ios":return Ge.Ios;case "web":return Ge.Web;default:return Ge.Unknown}}var ei=class extends Wt{id;supports;shell;pending=new Map;nextId=1;constructor(e,t=new ln){super(t,new an),this.shell=e,this.id=`native:${e.id??"unknown"}`;let n=e.capabilities??{},i=s=>n[s]??Pn[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:ki(),filePicker:$n(),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"});},iy[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 sy(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(Xn(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 Ii(e)}async shareFile(e){let t=await this.request("shareFile",{name:e.name,mime:e.mime,data:ry(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:Pi(e)});}createWorker(e,t){return zi(e,t)}};function ry(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)}function Ht(){return globalThis.Telegram?.WebApp??null}function Cu(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return Ru(e);let t=r.cordova?.platformId;return t?Ru(t):r.navigator?.userAgent??""?Ge.Web:Ge.Unknown}function Ru(r){let e=r.toLowerCase();return e==="android"?Ge.Android:e==="ios"?Ge.Ios:e==="web"?Ge.Web:Ge.Unknown}var Ut=["https://idosgames.com","https://www.idosgames.com"],Mi="https://platform.idosgames.com",Su=/^[a-z0-9]{8}-preview\.idos\.games$/;function ia(r){return r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r.endsWith(".localhost")}function sa(){if(typeof window>"u")return false;let r=window.location.hostname.toLowerCase();return Su.test(r)?true:ia(r)&&globalThis.__IDOS_PREVIEW__!=null}function un(r){if(typeof window<"u"&&Su.test(window.location.hostname.toLowerCase()))return r===Mi;if(Ut.includes(r))return true;if(typeof window>"u"||!ia(window.location.hostname))return false;try{return ia(new URL(r).hostname)}catch{return false}}var bu="IDOS_PLATFORM_WALLET_ACK",xu="PLATFORM_WALLET_UNAVAILABLE",oy=5e3,ay=18e4;function ly(){if(un(Mi))return [Mi];let r=[...Ut],e=window.location.ancestorOrigins?.[0];return e&&!r.includes(e)&&un(e)&&r.push(e),r}function uy(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Lt(r,e,t,n={}){let i={ok:false,error:xu,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=uy(),p=n.answerTimeoutMs??ay;return new Promise(m=>{let g=false,V,ce=de=>{g||(g=true,window.removeEventListener("message",ve),clearTimeout(V),m(de));},ve=de=>{if(!un(de.origin))return;let be=de.data;if(!(!be||be.requestId!==o)){if(be.type===bu){clearTimeout(V),V=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});}};V=setTimeout(()=>ce(i),oy),window.addEventListener("message",ve);for(let de of ly())try{s.postMessage({type:r,requestId:o,...t},de);}catch{}})}var ra={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},cy=30*6e4;function Du(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(sa())return false;let r=window.location.ancestorOrigins?.[0];if(r&&!Ut.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 oa(){if(typeof window>"u"||!sa())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function Iu(r){let e=await Lt(ra.request,ra.response,{titleID:r,supports:["pgs"]},{answerTimeoutMs:cy}),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 aa={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},py=15*6e4,hy=/^[a-z0-9]{8}-preview\.idos\.games$/;function wn(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !hy.test(window.location.hostname.toLowerCase())}async function Pu(r){let e=await Lt(aa.request,aa.response,{titleID:r.titleID,userID:r.userID,currencyID:r.currencyID,amount:r.amount},{answerTimeoutMs:py});return e.ok?{ok:true}:{ok:false,error:e.error}}var la={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},dy=5*6e4;function vu(){return wn()}async function Au(r){let e=await Lt(la.request,la.response,{titleID:r.titleID,userID:r.userID,requestID:r.requestID,placementID:r.placementID,adUnitID:r.adUnitID??null},{answerTimeoutMs:dy});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var ua={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},my=10*6e4,fy=["DECLINED","NOT_ENOUGH_CREDITS"];function Tu(){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 wu(){return wn()}async function ku(r){let e=await Lt(ua.request,ua.response,{titleID:r.titleID,confirmationID:r.confirmationID},{answerTimeoutMs:my});return e.ok?{ok:true}:{ok:false,error:e.error}}var Mu="IDOS_APP_FRAME_HIDDEN";function cn(){return globalThis.navigator??null}function Oi(){return typeof window<"u"}function zu(){if(!Oi())return false;try{return window.self!==window.top}catch{return true}}var ti=class extends Wt{id;supports;hiddenBySite=false;documentHidden=false;constructor(e=new ln){if(super(e,new an),!Oi()){this.id="web",this.supports=Pn;return}let t=cn(),n=Du();this.supports=Object.freeze({autoSignIn:n,signIn:n||oa(),rewardedAds:vu(),titleAds:false,storePurchases:false,creditsPayments:Tu(),creditsConfirm:wu(),cryptoTopUp:wn(),sceneCaptureRequests:zu(),share:typeof t?.share=="function",vibration:typeof t?.vibrate=="function",sharedMemory:ki(),filePicker:$n(),pushNotifications:false}),this.id=Ht()?"telegram":oa()?"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();})),zu()&&window.addEventListener("message",e=>{let t=e.data;!t||t.type!==Mu||un(e.origin)&&(this.hiddenBySite=t.hidden===true,this.update());}),this.update();}update(){this.setVisible(!this.documentHidden&&!this.hiddenBySite);}getPlatform(){return Ht()?.platform??"Web"}getClientPlatform(){return Cu()}getFullURL(){return Oi()?window.location.href:""}getStartParameter(){let e=Ht()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){return typeof document>"u"?null:document.referrer||null}getTelegramInitDataRaw(){let e=Ht()?.initData;return e&&e.length>0?e:null}getDeviceModel(){return cn()?.userAgent||"Web"}getLanguage(){return cn()?.language||""}async signIn(e){return this.supports.signIn?Iu(e):{error:dt}}async showRewardedAd(e){return this.supports.rewardedAds?Au(e):{ok:false,error:dt}}async confirmCredits(e){return this.supports.creditsConfirm?ku(e):{ok:false,error:dt}}async topUp(e){return this.supports.cryptoTopUp?Pu(e):{ok:false,error:dt}}openInvoice(e){let t=Ht();if(t?.openInvoice){t.openInvoice(e);return}this.openUrl(e);}openUrl(e){let t=Ht();if(t?.openTelegramLink&&/^https:\/\/t\.me\//i.test(e)){t.openTelegramLink(e);return}Oi()&&window.open(e,"_blank","noopener");}async share(e){let t=cn();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(Xn(e))?"copied":"unavailable"}pickFiles(e){return Ii(e)}async shareFile(e){if(typeof document>"u"||typeof Blob>"u")return "unavailable";let t=new Blob([e.bytes],{type:e.mime}),n=cn();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=cn();if(t?.clipboard)try{return await t.clipboard.writeText(e),!0}catch{}return gy(e)}vibrate(e){try{cn()?.vibrate?.(Pi(e));}catch{}}createWorker(e,t){return zi(e,t)}};function gy(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 ca(){let r=na();return r?new ei(r):typeof window>"u"?new Yn:new ti}var pa="idos_acq",Ou=["gclid","fbclid","ttclid","msclkid","yclid"],yy=["ref","r"],Ry=["ref_","ref-","ref=","r_","r-"];var hn=class{constructor(e){this.host=e;}host;capture(){let e=this.readFromEnvironment();Cy(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),n=t?{...t.signal}:{},i=xy(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(pa);}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=Uu(qu(t));if(n)return n}return Ei(t)}readFromEnvironment(){let e={},t=qu(this.host.getFullURL());pn(e,"UtmSource",t.get("utm_source")),pn(e,"UtmMedium",t.get("utm_medium")),pn(e,"UtmCampaign",t.get("utm_campaign")),pn(e,"UtmTerm",t.get("utm_term")),pn(e,"UtmContent",t.get("utm_content")),pn(e,"ClaimToken",t.get("idos_click"));for(let g of Ou){let V=t.get(g);if(V){e.ClickID=V;break}}let n=this.host.getStartParameter()??"",i=by(n);if(i){for(let g of Sy)pn(e,g,i.get(Lu[g])??null);for(let g of Ou){let V=i.get(g);if(V){e.ClickID=V;break}}}let s=Ei(i?i.get("ref")??i.get("r")??"":n),o=Uu(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(pa);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(pa,JSON.stringify(e));}catch{}}};function Cy(r){return !!(r.UtmSource||r.UtmMedium||r.UtmCampaign||r.ClickID||r.Referrer||r.ReferralCode||r.ClaimToken)}function pn(r,e,t){t&&(r[e]=t);}var Eu="a1_",Lu={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},Sy=Object.keys(Lu);function by(r){let e=(r||"").trim();if(!e.startsWith(Eu))return null;let t=e.slice(Eu.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 qu(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function Uu(r){for(let e of yy){let t=r.get(e);if(t)return Ei(t)}return null}function Ei(r){let e=(r||"").trim();if(!e)return null;for(let t of Ry)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function xy(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 Bu="idos_usage_pending",Gu="idos_usage_session",Nu="idos_usage_closed_session",_u="idos_usage_new_session",Fu="idos_usage_last_activity",ni=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(Bu),this.currentSessionSeconds=this.readNumber(Gu),this.pendingClosedSessionSeconds=this.readNumber(Nu),this.isNewSessionPending=this.readNumber(_u)!==0;let e=this.readNumber(Fu);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(Bu,this.pendingSeconds),this.writeNumber(Gu,this.currentSessionSeconds),this.writeNumber(Nu,this.pendingClosedSessionSeconds),this.writeNumber(_u,this.isNewSessionPending?1:0),this.writeNumber(Fu,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 Dy(r){return r.ok}function Iy(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 At=zod.z.object({Type:Tn.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()}),Py=zod.z.object({Type:wi.nullish(),EntityID:zod.z.string()}),vy=zod.z.object({Address:Py.nullish(),Amount:Q.nullish(),Source:zod.z.string().nullish()}),fe=zod.z.object({Entries:zod.z.array(At).nullish(),EventTokens:zod.z.array(vy).nullish()}),Vu=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:fe.nullish()}),$=zod.z.object({Standard:fe.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Vu).nullish()}),Bt=zod.z.object({Standard:fe.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Vu).nullish()}),E=zod.z.object({Grant:$.nullish(),Consume:Bt.nullish()}),Gt=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:E.nullish(),ToResult:E.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:fe.nullish()});var Ay=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ty={Completed:"Completed",Started:"Started",StepReached:"StepReached"},wy=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:Ay.nullish(),Tutorial:wy.nullish(),Platforms:zod.z.array(Ai).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 ky=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),zy=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),My=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 Oy=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:zy.nullish(),Chain:My.nullish(),Cyclic:Oy.nullish(),ActivationTriggers:zod.z.array(mt).nullish(),Relative:ky.nullish()}).passthrough();var Ey={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},qy=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Uy={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Ly=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),By=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Je=zod.z.object({Base:zod.z.number().nullish(),Shape:qy.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(By).nullish(),Interpolation:Ly.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var Gy=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:$.nullish()}).passthrough(),Ny=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),ha=zod.z.object({Bundles:zod.z.array(Gy).nullish(),Multipliers:zod.z.array(Ny).nullish()}).passthrough();var _y=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),qi=zod.z.object({Source:_y.nullish(),SourceKey:zod.z.string().nullish(),Curve:Je.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:fe.nullish(),ExcludeRewards:fe.nullish()}).passthrough(),ju=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:ha.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),kn=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 Fy=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Tt=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:Fy.nullish()}).passthrough();var Vy=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),zn=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:Vy.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(),zn).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()}),wt=r=>zod.z.object({ServerTimeUtc:u,Items:zod.z.array(Oe(r)),Resources:E.nullish(),Inventory:K.nullish()});var jy={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Wu=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Wy=zod.z.object({}).passthrough().transform(r=>r),Hy=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()}),da=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:Wu}),Hu=zod.z.object({State:Wy.nullish(),PointsTracks:zod.z.record(zod.z.string(),Hy).nullish()}),ma=zod.z.object({ServerTimeUtc:u,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:Wu.nullish(),Resources:E.nullish(),Inventory:K.nullish()}),fa=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:Q.nullish(),Resources:E.nullish(),Inventory:K.nullish(),NextMilestone:Ve.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Ku=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:E.nullish(),Inventory:K.nullish()}),Qu=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(da).nullish()}),$u=zod.z.array(Oe(ma)),Ju=zod.z.array(Oe(fa)),Ky={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Qy=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),$y={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Jy=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),Zu=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:Qy.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(),ga=zod.z.object({Milestones:J.nullish(),Linking:J.nullish(),Availability:J.nullish(),Reward:J.nullish(),Objectives:J.nullish()}).passthrough(),Zy=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(),Yu=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:Jy.nullish()}).passthrough(),Xu=zod.z.object({Schedule:Ce.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),ec=zod.z.object({Grant:$.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Yy=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Zy.nullish(),Linking:Yu.nullish(),Availability:Xu.nullish(),Objectives:zod.z.record(zod.z.string(),Zu).nullish(),Reward:ec.nullish(),Presets:ga.nullish()}).passthrough(),Xy=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(),eR=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:ga.nullish(),PointsToken:Tt.nullish()}).passthrough(),tR=zod.z.object({Milestones:zod.z.record(zod.z.string(),kn).nullish(),Linking:zod.z.record(zod.z.string(),Yu).nullish(),Availability:zod.z.record(zod.z.string(),Xu).nullish(),Reward:zod.z.record(zod.z.string(),ec).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Zu)).nullish()}).passthrough(),nR=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:Tt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),Xy).nullish(),Phases:zod.z.record(zod.z.string(),eR).nullish(),Presets:ga.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Li=zod.z.object({Cycles:zod.z.record(zod.z.string(),nR).nullish(),Quests:zod.z.record(zod.z.string(),Yy).nullish(),Presets:tR.nullish()}).passthrough(),Dt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var iR={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},sR=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),rR={Never:"Never",OnRequest:"OnRequest",Always:"Always"},oR=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),aR={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},lR=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),uR={GameLoop:"GameLoop"},cR={Raid:"Raid",Attack:"Attack"},pR=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(),hR=zod.z.object({Mode:sR.nullish(),Triggers:zod.z.array(mt).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),dR=zod.z.object({Grant:$.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),mR=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(),fR=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:mR.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),gR=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),ya=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:pR.nullish(),Completion:hR.nullish(),Effects:dR.nullish(),Script:fR.nullish(),Policy:gR.nullish()}).passthrough(),yR=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(),tc=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(),nc=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:oR.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),ic=zod.z.object({Grant:$.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),RR=zod.z.object({Availability:J.nullish(),Policy:J.nullish(),Reward:J.nullish(),Steps:J.nullish()}).passthrough(),CR=zod.z.object({FlowID:zod.z.string().nullish(),Identity:yR.nullish(),Availability:tc.nullish(),Policy:nc.nullish(),Steps:zod.z.record(zod.z.string(),ya).nullish(),Reward:ic.nullish(),Presets:RR.nullish()}).passthrough(),SR=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(),bR=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:SR.nullish()}).passthrough(),xR=zod.z.object({Availability:zod.z.record(zod.z.string(),tc).nullish(),Policy:zod.z.record(zod.z.string(),nc).nullish(),Reward:zod.z.record(zod.z.string(),ic).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),ya)).nullish()}).passthrough(),sc=zod.z.object({Flows:zod.z.record(zod.z.string(),CR).nullish(),Settings:bR.nullish(),Presets:xR.nullish()}).passthrough(),DR=zod.z.object({}).passthrough().transform(r=>r),rc=zod.z.object({FlowID:zod.z.string(),Status:lR,CurrentStepID:zod.z.string().nullish(),CurrentStep:ya.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(),Bi=zod.z.object({State:DR.nullish(),Flows:zod.z.array(rc).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Qt=zod.z.object({Flow:rc.nullish()}).passthrough(),oc=zod.z.object({FlowID:zod.z.string().nullish(),Granted:E.nullish()}).passthrough(),ac=zod.z.array(Oe(Qt)),lc=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 Gi(r){return Array.isArray(r)?r.filter(e=>e!==null).map(Gi):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,Gi(t)])):r}var Ni=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 _i=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function uc(r){return r===429||r>=500&&r<=599}function Fi(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 $t(r){return new Promise(e=>setTimeout(e,r))}var cc=15e3;async function pc(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 hc(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function dc(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var Ra=15,mc=1e3,Vi=class{constructor(e=Ra,t=()=>Date.now(),n=$t){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]>=mc;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(mc-(e-this.starts[0])+5);}}};var IR=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function On(r){if(!r)return null;let e=IR.exec(r);if(!e)return null;let[,t,n,i]=e;if(!t||n===void 0||i===void 0)return null;let s=new dn__default.default(n),o=new dn__default.default(i),p=o.minus(dn__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 PR=12e3,vR=new Set(["RelatedEntityID"]);function AR(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[n,i]of Object.entries(e))vR.has(n)||(t[n]=i);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var TR=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(da).nullish(),TutorialProgress:zod.z.array(lc).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),ji=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new _i;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 Ni(e.throttleMs),this.pacer=new Vi(e.maxRequestsPerSecond??Ra),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??AR(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,V=i.timeoutMs??PR,ce=i.autoRetry??!0,ve=!1,de=!1,be=0;for(;;){let qt;i.keepalive||await this.pacer.take();try{qt=await this.doFetch(o,p,m,V,i.keepalive??!1);}catch{if(ce&&be<3){be++,await $t(Fi(be));continue}return this.connectionFailure("Internet Connection Error",g)}let ot=qt.status;if(ot>=200&&ot<300){let ue=!de&&this.cryptoTopUpHandler!==null,Me=await this.parseSuccess(qt,n,g,e,ue);if(!Me.ok&&ue){let ge=On(Me.error);if(ge){if(de=!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(uc(ot)){let ue=ot===429?await pc(qt):null;if(ue!==null&&ue>cc)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ue/1e3)} s`,g);if(ce&&be<3){be++,await $t(ue!==null?hc(ue):ot===429?dc(be):Fi(be));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${ot})`,g)}let Hn="";try{Hn=await qt.text();}catch{}if(ot===409&&/operation in progress/i.test(Hn)&&ce&&be<3){be++,await $t(Fi(be));continue}return this.handleWebError(Hn,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=TR.safeParse(p);if(!m.success)return this.globalError("Malformed response envelope",n);if(!m.data.Success){let de=m.data.Error??"Server returned Success=false",be=s&&On(de);return !n&&!be&&this.emitter.emit("error:global",de),h("server",de)}let g=m.data.StateVersions;g&&Object.keys(g).length>0&&this.emitter.emit("user:stateVersions",{epoch:m.data.StateEpoch??null,versions:g});let V=m.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);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 de=t.safeParse(Gi(m.data.Data));de.success&&(ve=de);}if(!ve.success){let de=`Validation error (${i}): ${ve.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",de),n||this.emitter.emit("error:global",de),h("validation",de)}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 En(r){return (typeof r=="string"?r:r.toISOString()).slice(0,10)}function ii(r){return `${En(r)}T00:00:00.000Z`}function fc(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function gc(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function ba(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,V=new Map,ce=new Map,ve=new Map,de=new Map,be=new Map,qt=e.Grant?.PremiumTiers??[],ot=qt.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=qt[ue-1]?.Resources?.Entries,ge=false;else if(ue===1+ot)Me=e.Consume?.Standard?.Entries,ge=true;else break;if(Me)for(let me of Me){if(me.Type==null)continue;let Re=Math.max(0,me.Amount??0);if(!(Re<=0))switch(me.Type){case "VirtualCurrency":{if(!me.CurrencyID)continue;let Se=ge?m:p;Se.set(me.CurrencyID,(Se.get(me.CurrencyID)??0)+Re);break}case "CryptoCurrency":{if(!me.CurrencyID)continue;let Se=ge?V:g;Se.set(me.CurrencyID,(Se.get(me.CurrencyID)??new dn__default.default(0)).plus(Re));break}case "Item":{if(!me.ItemID)continue;let Se=kR(t,me.CatalogID,me.ItemID),Te=(Se?Se.IsStackable??true:true)?ge?ve:ce:ge?be:de;Te.set(me.ItemID,(Te.get(me.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,me=Me-ge,Re=s.VirtualCurrencies[ue];Re?(Re.Amount+=me,Re.UpdatedAt=o,Re.Daily&&En(Re.Daily.PeriodStartUtc)===En(n)?(Re.Daily.Earned+=Me,Re.Daily.Spent+=ge):Re.Daily={PeriodStartUtc:ii(n),Earned:Me,Spent:ge}):s.VirtualCurrencies[ue]={Amount:me,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:ii(n),Earned:Me,Spent:ge}};}}if(i.ccChanged=g.size>0||V.size>0,i.ccChanged){s.CryptoCurrencies??={};for(let ue of new Set([...g.keys(),...V.keys()])){let Me=g.get(ue)??new dn__default.default(0),ge=V.get(ue)??new dn__default.default(0),me=Me.minus(ge),Re=s.CryptoCurrencies[ue];Re?(Re.Amount=new dn__default.default(Re.Amount).plus(me).toString(),Re.UpdatedAt=o):s.CryptoCurrencies[ue]={Amount:me.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(i.itemsChanged=ce.size>0||ve.size>0||de.size>0||be.size>0,i.itemsChanged){s.Items??={},s.UnstackableItems??={};let ue=s.UnstackableItems,Me=new Set([...ce.keys(),...ve.keys(),...de.keys(),...be.keys()]);for(let ge of Me){let me=(ce.get(ge)??0)-(ve.get(ge)??0),Re=(de.get(ge)??0)-(be.get(ge)??0),Se=me+Re,ht=s.Items[ge];ht?(me!==0&&(ht.StackableAmount+=me),Re!==0&&(ht.UnstackableAmount+=Re),Se!==0&&(ht.TotalAmount+=Se)):s.Items[ge]={StackableAmount:Math.max(0,me),UnstackableAmount:Math.max(0,Re),TotalAmount:Math.max(0,Se)};}for(let[ge,me]of be){if(me<=0)continue;let Re=Object.values(ue).filter(Se=>Se.ItemID===ge&&Se.EquippedSlot==null&&(Se.ExpiresAt==null||new Date(Se.ExpiresAt)>n)).sort(wR).slice(0,me).map(Se=>Se.ItemInstanceID);for(let Se of Re)delete ue[Se];}for(let[ge,me]of de){let Re=zR(t,ge);for(let Se=0;Se<me;Se++){let ht=_();ue[ht]={ItemInstanceID:ht,ItemID:ge,CatalogID:Re,RemainingUses:1,AcquiredAt:o};}}}r.EventToken??={};let Hn=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=qt[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 me of Me){let Re=me.Address;if(!Re||Re.Type==null)continue;let Se=me.Amount??0;if(Se<=0)continue;let ht=MR(Hn,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:ii(n),TotalEarned:0},Te.Meta??={};let Kn=me.Source&&me.Source.length>0?me.Source:"CustomAction";ge?(Te.Balance.Current-=Se,Te.Balance.TotalSpent+=Se):(Te.Balance.Current+=Se,Te.Balance.TotalEarned+=Se,En(Te.Daily.Date)!==En(n)&&(Te.Daily={Date:ii(n),TotalEarned:0}),Te.Daily.TotalEarned+=Se,Te.Daily.EarnedBySource??={},Te.Daily.EarnedBySource[Kn]=(Te.Daily.EarnedBySource[Kn]??0)+Se,Te.Daily.TriggersBySource??={},Te.Daily.TriggersBySource[Kn]=(Te.Daily.TriggersBySource[Kn]??0)+1,Te.Daily.LastTriggerBySource??={},Te.Daily.LastTriggerBySource[Kn]=o,Te.Meta.JoinedAtUtc||(Te.Meta.JoinedAtUtc=o),Te.Meta.LastEarnedAtUtc=o),i.tokensChanged=true;}}return i}function wR(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 kR(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 zR(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 MR(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 yc(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 xa(r,e){return r===e||r.startsWith(`${e}:`)}var Hi=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=ba(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=ba(s,e,n,i),m=yc(o,s.InventoryV2?.UnstackableItems,t),g=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],ce=m.drop.length>0||Object.keys(m.restore).length>0||g.length>0||V.length>0;if(ce){s.InventoryV2??={},s.InventoryV2.UnstackableItems??={};let ve=s.InventoryV2.UnstackableItems;for(let de of m.drop)delete ve[de];for(let[de,be]of Object.entries(m.restore))ve[de]=be;for(let[de,be]of g)ve[de]=be;for(let de of V)delete ve[de];}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 dn__default.default?t:new dn__default.default(t),p=i===void 0?new dn__default.default(0):i instanceof dn__default.default?i:new dn__default.default(i),m=n??new Date().toISOString(),g=s[e];g?(g.Amount=new dn__default.default(g.Amount).plus(o).toString(),p.isZero()||(g.Frozen=new dn__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=fc(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(xa(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:!xa(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 Ki=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 Qi=class{user;config;constructor(e){this.user=new Hi(e),this.config=new Ki;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function OR(r){return r}var ER=0,qR=1500,UR=3,Ji=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();},ER),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=$i(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 V=this.loginFailures.get(i);if(V)return this.loginFailures.delete(i),V;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 V=Date.now();if((this.generation.get(i)??0)===s)return this.entries.set(i,{data:g.data,storedAt:V,expiresAt:Da(e,g.data,V)}),g;let ce=this.entries.get(i);if(ce&&ce.storedAt>=o)return g;let ve=Da(e,g.data,V);return this.entries.set(i,{data:g.data,storedAt:V,expiresAt:Math.min(ve??1/0,V+qR)}),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=$i(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=Rc({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>UR||this.used.set(Rc(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($i(e,t))?.data}put(e,t,n){this.register(e);let i=$i(e,n);this.bump(i);let s=Date.now();this.entries.set(i,{data:t,storedAt:s,expiresAt:Da(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 $i(r,e){return e===void 0?r.key:`${r.key}|${e}`}function Rc(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function Da(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 Zi=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 LR(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 LR(r){return r!==null&&Object.values(qe).includes(r)}var BR=8,GR=100,NR=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,Yi=["GameLoop"];function _R(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var Xi=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(Yi,Yi);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"):(_R(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&&NR.test(e)}static isValidPasswordLength(e){return e.length>=BR&&e.length<=GR}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(Yi,Yi);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 FR="idos:cfg",qn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Cc(t)}`:e&&e.length>0?`f:${Cc(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 `${FR}:${this.titleId}:${e}`}};function Cc(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var Sc="idos:loc",Un=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 `${Sc}:${this.titleId}:${e}`}versionsKey(){return `${Sc}:${this.titleId}:versions`}};var VR="idos:sec",es=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 `${VR}:${this.titleId}`}};var jR="idos:state",ts=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 `${jR}:${this.titleId}:${e}`}};function WR(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 Ia(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 HR(r){return {...r??{}}}function Pa(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.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,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=WR(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=HR(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 bc=h("server","Title configuration is unavailable (CDN and API both failed)."),is=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:_()}:null}get configCache(){return this.cache??=new qn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new Un(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new es(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new ns(new ts(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=qn.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?bc:(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=Ia(e.User,t.cached,t.sent,e.StateVersions);e.User=n;let i=Pa(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:_()},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=qn.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?bc:(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=Ia(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,V])=>o[g]!==V||this.ctx.data.user.state?.[g]===void 0).map(([g])=>g);this.ctx.data.user.applyUserStateContainers(s,p);let m=Pa(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 V=this.ctx.data.config.titlePublicConfiguration;o&&V&&V.GameLoop==null&&(V.GameLoop=m),this.ctx.emitter.emit("user:clientStateReceived",e);}};var rs=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}_${_()}`},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===bt.Crypto||n===bt.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}_${_()}`},m=await this.ctx.api.currency.convert(p);if(m.ok){let g=m.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 m}async cryptoConvert(e,t,n,i,s,o){let p=s instanceof dn__default.default?s:new dn__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===bt.Virtual&&n===bt.Virtual)return h("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===bt.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}_${_()}`},g=await this.ctx.api.currency.cryptoConvert(m);if(g.ok){let V=g.data,ce=[],ve=[];if(V.SourceType===bt.Virtual&&ce.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===bt.Virtual&&ve.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),ce.length>0||ve.length>0){let de={Consume:ce.length>0?{Standard:{Entries:ce}}:null,Grant:ve.length>0?{Standard:{Entries:ve}}:null};this.ctx.data.user.applyResourceOperation(de,this.ctx.data.config.itemDefinitions);}V.SourceType===bt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new dn__default.default(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===bt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new dn__default.default(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return g}};var os=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}_${_()}`};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 as=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:Bt.nullish(),AllowedPlatforms:zod.z.array(Ai).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),pe=zod.z.record(zod.z.string(),as),KR=zod.z.object({Store:Ti,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var si={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(),xc=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),QR={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"},va=zod.z.object({ServerTimeUtc:u,OfferID:zod.z.string(),Count:zod.z.number(),Resources:E.nullish(),Inventory:K.nullish(),CreditsConfirmation:ye.nullish()}),Dc=zod.z.array(Oe(va)),$R=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:u,LastPurchasedAt:u}),JR=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:u}),Ic=zod.z.object({Purchases:zod.z.record(zod.z.string(),$R).nullish(),Rotations:zod.z.record(zod.z.string(),JR).nullish()}).passthrough().transform(r=>r),Nt=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(),ls=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),ZR={Fixed:"Fixed",Title:"Title",Player:"Player"},YR=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:ee.nullish()}).passthrough(),Pc=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(YR).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),XR=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Rotation:J.nullish()}).passthrough(),eC=zod.z.object({SlotID:zod.z.string().nullish(),Identity:Nt.nullish(),Availability:ls.nullish(),Rotation:Pc.nullish(),Presets:XR.nullish()}).passthrough(),tC=zod.z.object({Identity:J.nullish(),Availability:J.nullish()}).passthrough(),nC=zod.z.object({SectionID:zod.z.string().nullish(),Identity:Nt.nullish(),Availability:ls.nullish(),Slots:zod.z.record(zod.z.string(),eC).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:tC.nullish()}).passthrough(),vc=zod.z.object({Sections:zod.z.record(zod.z.string(),nC).nullish()}).passthrough(),iC=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Layout:J.nullish()}).passthrough(),sC=zod.z.object({StoreID:zod.z.string().nullish(),Identity:Nt.nullish(),Availability:ls.nullish(),Layout:vc.nullish(),Presets:iC.nullish()}).passthrough(),Ac=zod.z.object({Options:pe.nullish(),CompareAt:zod.z.record(zod.z.string(),Bt).nullish()}).passthrough(),Tc=zod.z.object({Grant:$.nullish()}).passthrough(),wc=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),rC=zod.z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish(),Availability:J.nullish()}).passthrough(),oC=zod.z.object({OfferID:zod.z.string().nullish(),Identity:Nt.nullish(),Pricing:Ac.nullish(),Reward:Tc.nullish(),Availability:wc.nullish(),Presets:rC.nullish()}).passthrough(),aC=zod.z.object({Identity:zod.z.record(zod.z.string(),Nt).nullish(),Availability:zod.z.record(zod.z.string(),ls).nullish(),Layout:zod.z.record(zod.z.string(),vc).nullish(),Rotation:zod.z.record(zod.z.string(),Pc).nullish(),Pricing:zod.z.record(zod.z.string(),Ac).nullish(),Reward:zod.z.record(zod.z.string(),Tc).nullish(),OfferAvailability:zod.z.record(zod.z.string(),wc).nullish()}).passthrough(),us=zod.z.object({Stores:zod.z.record(zod.z.string(),sC).nullish(),StoreOffers:zod.z.record(zod.z.string(),oC).nullish(),Presets:aC.nullish()}).passthrough(),lC=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(),uC=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:Bt.nullish(),CompareAtCost:Bt.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(),cC=zod.z.object({OfferID:zod.z.string(),Identity:Nt.nullish(),PriceOptions:zod.z.array(uC).nullish(),Rewards:$.nullish(),State:lC.nullish()}).passthrough(),pC=zod.z.object({SlotID:zod.z.string(),Identity:Nt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:u.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:cC.nullish()}).passthrough(),hC=zod.z.object({SectionID:zod.z.string(),Identity:Nt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(pC).nullish()}).passthrough(),dC=zod.z.object({StoreID:zod.z.string(),Identity:Nt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:u.nullish(),Sections:zod.z.array(hC).nullish()}).passthrough(),cs=zod.z.object({ServerTimeUtc:u,Stores:zod.z.array(dC).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),_t={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},mC="OFFER_NOT_IN_ROTATION";var kc="Store",zc={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}},ps=class{constructor(e){this.ctx=e;e.cache.bindLoginView(zc,{schema:cs,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}_${_()}`},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(kc,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(kc,i.data),this.ctx.emitter.emit("store:definitionsLoaded",i.data)),i}getStorefront(e){return this.ctx.cache.read(zc,()=>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 hs=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(V=>setTimeout(V,o));let m=await this.ctx.store.getCreditsConfirmation(i.ConfirmationID);if(!m.ok)continue;let g=m.data.Status;if(g!==si.Pending)return g===si.Declined?h("server","CREDITS_CONFIRMATION_DECLINED"):g===si.Expired?h("server","CREDITS_CONFIRMATION_EXPIRED"):await s()}}};var ds=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 Mc=3,fC=700,ms=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 On(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<=Mc;t++){let n=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(n.ok)return;if(n.reason!=="throttled"||t===Mc)break;await $t(fC);}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===vi.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!==vi.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 Oc="Lootbox",fs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Oc,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(Oc,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"}_${_()}`},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 Aa="Reward";function gs(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var ys=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(Aa)?.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(Aa,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(Aa,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"}_${_()}`},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(!gs(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}_${_()}`},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(!gs(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}_${_()}`},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(!gs(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}_${_()}`},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(!gs(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}_${_()}`},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 Rs="Tutorial",Ec={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"]},Cs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ec,{schema:Bi,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(Rs)?.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(Rs,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(Rs,i.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",i.data)),i}getUserTutorialState(e=true,t){return this.ctx.cache.read(Ec,()=>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}_${_()}`})}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}_${_()}`},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}_${_()}`},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(Rs)?.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 Ss=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 gC={Global:"Global",Announcement:"Announcement",Group:"Group"},Uc=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),yC={None:"None",Language:"Language",Region:"Region"},RC=zod.z.enum(["None","Language","Region"]).catch("None"),CC={Anyone:"Anyone",Friends:"Friends"},SC=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),bC={Reject:"Reject",Mask:"Mask"},xC=zod.z.enum(["Reject","Mask"]).catch("Reject"),DC={Player:"Player",Publisher:"Publisher",System:"System"},IC=zod.z.enum(["Player","Publisher","System"]).catch("Player"),PC={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var vC=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),Lc=zod.z.object({Gate:ee.nullish(),Schedule:Ce.nullish()}).passthrough(),Bc=zod.z.object({Gate:ee.nullish(),Limits:Pe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Gc=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),AC=zod.z.object({Availability:J.nullish(),Write:J.nullish(),Retention:J.nullish()}).passthrough(),TC=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:vC.nullish(),Type:Uc.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:RC.nullish(),Capacity:zod.z.number().nullish(),Availability:Lc.nullish(),Write:Bc.nullish(),Retention:Gc.nullish(),Presets:AC.nullish()}).passthrough(),wC=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:ee.nullish(),WhoCanMessage:SC.nullish(),Limits:Pe.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),kC=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:xC.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Pe.nullish()}).passthrough(),zC=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),MC=zod.z.object({Availability:zod.z.record(zod.z.string(),Lc).nullish(),Write:zod.z.record(zod.z.string(),Bc).nullish(),Retention:zod.z.record(zod.z.string(),Gc).nullish()}).passthrough(),Nc=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),TC).nullish(),Direct:wC.nullish(),Moderation:kC.nullish(),Polling:zC.nullish(),Presets:MC.nullish()}).passthrough(),OC=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),qc=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(),OC).nullish(),Limits:zod.z.record(zod.z.string(),qc).nullish(),ReportLimits:qc.nullish()}).passthrough();var Ta=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),bs=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:IC.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(),EC=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:Uc.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(),xs=zod.z.object({Channels:zod.z.array(EC).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),qC=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(bs).nullish(),NextCursor:Ta.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),_c=zod.z.object({Rooms:zod.z.array(qC).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Fc=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(bs).nullish(),NextBefore:Ta.nullish()}).passthrough(),Vc=zod.z.object({Message:bs.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),jc=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ne.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),UC=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ne.nullish(),LastMessage:bs.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Wc=zod.z.object({Conversations:zod.z.array(UC).nullish()}).passthrough(),Ln=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:Ta.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),Hc=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 Kc="Chat",Qc={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Ds=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Qc,{schema:xs,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(Kc,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(Kc,i.data),this.ctx.emitter.emit("chat:definitionsLoaded",i.data)),i}getChannels(e,t){return this.ctx.cache.read(Qc,()=>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 LC={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},BC=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),GC={Player:"player",Title:"title",Creator:"creator"},Bn={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},$c=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),NC=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),wa=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:BC.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(NC).nullish()}).passthrough(),Jc=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(wa).nullish()}).passthrough(),nt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var _C="IDOS_PLATFORM_PUSH_REQUEST",FC="IDOS_PLATFORM_PUSH_RESPONSE",VC=12e4;function Zc(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!==FC||g.requestId!==t||Ut.includes(m.origin)&&s(g.ok===true);},p=setTimeout(()=>s(false),VC);window.addEventListener("message",o);for(let m of Ut)try{e.postMessage({type:_C,requestId:t,titleID:r},m);}catch{}})}var jC="idos:push:deviceToken:",Is=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 Zc(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:WC(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 jC+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 WC(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 Ps=Object.freeze({}),vs=class{constructor(e){this.ctx=e;}ctx;table={...Ps};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new Un(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?HC(i,t):i}applyState(e,t){if(!e){this.reset();return}let n=e.Locale??null;this.table=t.table??{...Ps},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={...Ps},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:_()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return l;t.Locale=e;let n=await this.cache.read(Yc(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??Yc(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??{...Ps},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 HC(r,e){return r.replace(/\{(\w+)\}/g,(t,n)=>{let i=e[n];return i===void 0?t:String(i)})}function Yc(r){return r.trim().replace(/_/g,"-").toLowerCase()}var ka="Quest",KC={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}},As=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(ka)?.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(ka,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(ka,i.data),this.ctx.emitter.emit("quest:definitionsLoaded",i.data)),i}getUserQuestState(e=true,t){return this.ctx.cache.read(KC,()=>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}_${_()}`},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}_${_()}`},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}_${_()}`},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 Xc=zod.z.object({}).passthrough().transform(r=>r);var QC=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),$C=zod.z.object({Schedule:zod.z.array(QC).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),JC=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(),ZC=zod.z.object({Milestones:J.nullish()}).passthrough(),za=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:Tt.nullish(),TokenSources:zod.z.array(mt).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),Presets:ZC.nullish(),BonusWindow:$C.nullish()}).passthrough(),YC=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:za.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),XC=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:za.nullish(),Events:zod.z.array(YC).nullish(),Gate:ee.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),eS=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),tS=zod.z.object({Milestones:zod.z.record(zod.z.string(),kn).nullish()}).passthrough(),Ts=zod.z.object({Definitions:zod.z.record(zod.z.string(),XC).nullish(),Settings:eS.nullish(),Presets:tS.nullish()}).passthrough(),nS=zod.z.object({Type:Zn,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:za.nullish(),Progress:Xc.nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:Ve.nullish(),BonusWindow:JC.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),ws=zod.z.object({ActiveEvents:zod.z.array(nS).nullish()}).passthrough(),ep=zod.z.object({Tokens:zod.z.record(zod.z.string(),Xc).nullish()}),Ma=zod.z.object({Type:Zn.nullish(),LteID:zod.z.string().nullish(),Resources:E.nullish()}),Oa=zod.z.object({Type:Zn.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:E.nullish(),Inventory:K.nullish()}),iS=zod.z.object({Type:Zn.nullish(),LteID:zod.z.string().nullish(),Resources:E.nullish()}),Ea=zod.z.array(Oe(Oa)),tp=zod.z.array(Oe(Ma)),np=zod.z.array(Oe(iS)),yt={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var ip="TimedEvent",sp={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}},ks=class{constructor(e){this.ctx=e;e.cache.bindLoginView(sp,{schema:ws,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(sp,()=>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(ip,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(ip,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 sS=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(),ri=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:Q.nullish(),CycleEndUtc:u.nullish(),TopUsers:zod.z.array(sS).nullish(),BracketID:zod.z.string().nullish()}),rS=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(),zs=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(rS).nullish()}),Ms=zod.z.object({LeaderboardID:zod.z.string(),NewScore:Q,CycleVersion:zod.z.number()}),Os=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:E.nullish(),Inventory:K.nullish()}),Es=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:E.nullish(),Inventory:K.nullish()}),rp=zod.z.array(Oe(ri)),qs=zod.z.array(Oe(zs)),op=zod.z.array(Oe(Os)),ap=zod.z.array(Oe(Es)),lp=zod.z.array(Oe(Ms)),oS=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:Oe(Os).nullish(),Milestones:zod.z.array(Oe(Es)).nullish()}),up=zod.z.array(oS),aS=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:Oe(ri).nullish(),Progress:Oe(zs).nullish()}),cp=zod.z.array(aS),lS=zod.z.string(),pp=zod.z.object({Rank:zod.z.string().nullish(),Rewards:$.nullish(),SeasonTierRewards:ha.nullish()}).passthrough(),uS=zod.z.object({RankRewards:zod.z.array(pp).nullish()}).passthrough(),cS=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),pS=zod.z.object({Milestones:J.nullish(),RankRewards:J.nullish()}).passthrough(),hS=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:lS.nullish(),Schedule:Ce.nullish(),ChainEvents:zod.z.array(cS).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(pp).nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),Presets:pS.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(mt).nullish()}).passthrough(),dS=zod.z.object({Milestones:zod.z.record(zod.z.string(),kn).nullish(),RankRewards:zod.z.record(zod.z.string(),uS).nullish()}).passthrough(),Us=zod.z.object({Definitions:zod.z.record(zod.z.string(),hS).nullish(),Presets:dS.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 hp="Leaderboard",dp={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"]},Ls=class{constructor(e){this.ctx=e;e.cache.bindLoginView(dp,{schema:qs,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(hp,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(hp,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(dp,()=>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 qa=zod.z.object({}).passthrough().transform(r=>r),Bs=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>yp).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:Q.nullish(),UserState:qa.nullish(),NextTier:zod.z.lazy(()=>gp).nullish()}).passthrough(),mp=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()}),Ua=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:E.nullish(),Inventory:K.nullish()}),fp=wt(Ua);var gp=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(),yp=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(gp).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var mS=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Ce.nullish(),Seasons:zod.z.array(yp).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:ee.nullish()}).passthrough(),Gs=zod.z.object({Chains:zod.z.record(zod.z.string(),mS).nullish()}).passthrough(),Zt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Rp="Season",Cp={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}},Ns=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Cp,{schema:Bs,apply:(t,n)=>this.applyActiveSeason(n??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Rp,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(Rp,i.data),this.ctx.emitter.emit("season:definitionsLoaded",i.data)),i}getActiveSeason(e,t){return e?this.ctx.cache.read(Cp,()=>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}_${_()}`},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}_${_()}`},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}_${_()}`},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 Sp="Premium",_s=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Sp,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(Sp,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}`},V=await this.ctx.api.premium.purchaseRealMoney(g);if(V.ok){let ce=V.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 V}};var Fs=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()}),oi=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(),Fs).nullish(),UpdatedAt:u.nullish()}).passthrough(),bp=zod.z.object({Characters:zod.z.record(zod.z.string(),oi).nullish(),SelectedCharacterID:zod.z.string().nullish()}),La=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:E.nullish()}),Ba=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:E.nullish()}),xp=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Fs).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Dp=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()}),fS=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Ip=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),fS).nullish(),Inventory:K.nullish()}),Ga=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:E.nullish()}),Pp=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:E.nullish(),Inventory:K.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:Fs.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),vp=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Fs.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Ap=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),gS=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:pe.nullish()}),yS=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(gS).nullish()}),Tp=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),yS).nullish()}),wp=zod.z.object({ServerTimeUtc:u,SelectedCharacterID:zod.z.string().nullish()}),kp=wt(Ga),zp=wt(Ba),Mp=wt(La),Na=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),Op=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:pe.nullish(),CostCurve:Je.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Je.nullish(),RankCurve:Je.nullish(),Requirements:zod.z.array(Na).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),RS=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Na).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(),Ep=zod.z.object({Slots:zod.z.record(zod.z.string(),RS).nullish()}).passthrough(),qp=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(),CS=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),SS=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:pe.nullish()}).passthrough(),bS=zod.z.object({Stats:J.nullish(),Levels:J.nullish(),Equipment:J.nullish()}).passthrough(),Up=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:pe.nullish(),CostCurve:Je.nullish()}).passthrough(),_a="@skin";function xS(r){return !!r&&r.startsWith("@")}var DS=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),IS=zod.z.object({PriceOptions:pe.nullish(),Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),PS=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Na).nullish()}).passthrough(),vS=zod.z.object({SkinID:zod.z.string().nullish(),Identity:qp.nullish(),Item:DS.nullish(),Sale:IS.nullish(),Requirements:PS.nullish()}).passthrough(),AS=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),vS).nullish()}).passthrough(),TS=zod.z.object({CharacterID:zod.z.string(),Identity:qp.nullish(),Classification:CS.nullish(),Unlock:SS.nullish(),Presets:bS.nullish(),Equipment:Ep.nullish(),Stats:zod.z.record(zod.z.string(),Op).nullish(),RankLadder:Up.nullish(),RankStatCurve:Je.nullish(),StatMaxLevelCurve:Je.nullish(),Skins:AS.nullish()}).passthrough(),wS=zod.z.object({Stats:zod.z.record(zod.z.string(),Op).nullish()}).passthrough(),kS=zod.z.object({RankLadder:Up.nullish()}).passthrough(),zS=zod.z.object({Equipment:Ep.nullish()}).passthrough(),MS=zod.z.object({Stats:zod.z.record(zod.z.string(),wS).nullish(),Levels:zod.z.record(zod.z.string(),kS).nullish(),Equipment:zod.z.record(zod.z.string(),zS).nullish()}).passthrough(),Vs=zod.z.object({Definitions:zod.z.record(zod.z.string(),TS).nullish(),Presets:MS.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"},OS="SKIN_ALREADY_OWNED";var Fa="Character",js=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Fa)?.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(Fa,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(Fa,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}_${_()}`},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}_${_()}`,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}_${_()}`,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}_${_()}`},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,_a,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 Lp="Match",Ws=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}_${_()}`},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}_${_()}`},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 V=m.ResourcesDual;V.FromUserID===s.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,g):V.ToUserID===s.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.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(Lp,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(Lp,i.data),this.ctx.emitter.emit("match:definitionsLoaded",i.data)),i}};var ES="Challenge",Hs=class{constructor(e){this.ctx=e;}ctx;lastState=null;get definitions(){return this.ctx.cache.configSection(ES)??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 _().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 Bp="Craft",Ks=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Bp,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(Bp,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}_${_()}`},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 Yt=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(Yt),zod.z.record(zod.z.string(),Yt)]));var Xt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Gp=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),mn={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function ai(r){return r!==mn.Pending&&r!==mn.Running}var qS={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 US(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var LS=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),BS=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),Qs=zod.z.object({CreditsConfirmation:ye.nullish(),GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Gp.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),Yt).nullish(),Assets:zod.z.array(LS).nullish(),Error:BS.nullish(),Charge:E.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:E.nullish(),Context:zod.z.record(zod.z.string(),Yt).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish()}),Np=zod.z.object({Data:zod.z.array(Qs).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),GS=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(),It=zod.z.record(zod.z.string(),zod.z.string()),NS=zod.z.object({Key:zod.z.string().nullish(),Role:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),Label:It.nullish()}).passthrough(),_S=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:It.nullish(),Placeholder:It.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string().nullish(),Label:It.nullish()}).passthrough()).nullish()}).passthrough(),_p=zod.z.object({Key:zod.z.string(),Kind:zod.z.string().nullish(),Name:It.nullish(),Hint:It.nullish(),Unit:It.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string(),Name:It.nullish(),Group:zod.z.string().nullish()}).passthrough()).nullish(),Groups:zod.z.array(zod.z.object({Key:zod.z.string(),Name:It.nullish()}).passthrough()).nullish(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),Step:zod.z.number().nullish()}).passthrough(),Fp=zod.z.object({PriceOptions:pe.nullish()}).passthrough(),FS=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:It.nullish(),Description:It.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(NS).nullish(),Variables:zod.z.array(_S).nullish(),Settings:zod.z.array(_p).nullish()}).passthrough(),VS=zod.z.object({Modality:Gp.nullish(),Async:zod.z.boolean().nullish(),Limits:Pe.nullish(),PriceOptions:pe.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(GS).nullish(),AllowFreePrompt:zod.z.boolean().nullish(),PlatformTemplateId:zod.z.string().nullish(),PlatformTemplate:FS.nullish(),Settings:zod.z.array(_p).nullish(),FreePerDay:zod.z.number().nullish(),FreeLeftToday:zod.z.number().nullish()}).passthrough(),Vp=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),VS).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 jp="AI",jS=/^[A-Za-z0-9_-]{1,128}$/,WS=2e3,HS=5e3,KS=30*6e4;function QS(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 $s=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(jp,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(jp,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 ai(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??KS),s=Math.max(1,t.intervalMs??WS),o=Math.max(s,t.maxIntervalMs??HS);for(;!ai(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 QS(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,ai(n.Status)||t.onUpdate?.(n);}return B(n)}pollFor(e){switch(e.Modality){case Xt.Text:return this.getText(e.GenerationID);case Xt.Image:return this.getImage(e.GenerationID);case Xt.Audio:return this.getAudio(e.GenerationID);case Xt.Music:return this.getMusic(e.GenerationID);case Xt.Video:return this.getVideo(e.GenerationID);case Xt.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&&!jS.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??_()},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===mn.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===mn.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===mn.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Va="Collection",Js=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(Va),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(Va,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(Va,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}_${_()}`},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}_${_()}`},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}_${_()}`},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}_${_()}`},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}_${_()}`},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}_${_()}`},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}_${_()}`},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}_${_()}`},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}_${_()}`},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 $S=zod.z.object({}).passthrough().transform(r=>r),JS={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},ZS={Active:"Active",Left:"Left",Replaced:"Replaced"},YS=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),XS=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ne.nullish(),BuildObjectsProgress:YS.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(),eb=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(),tb=zod.z.object({Objects:zod.z.array(eb).nullish()}).passthrough(),Wp=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(XS).nullish(),BuildObjectsState:tb.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),Hp=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>Kp).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),nb=zod.z.string(),ja=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(),ib=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(),sb=zod.z.object({Objects:zod.z.array(ib).nullish(),PriceOptions:pe.nullish(),SpinnerTable:zod.z.array(ja).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),Kp=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:nb.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:sb.nullish(),GrandPrize:$.nullish()}).passthrough(),rb=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Ce.nullish(),Events:zod.z.array(Kp).nullish(),Gate:ee.nullish()}).passthrough(),Zs=zod.z.object({ServerTimeUtc:u.nullish(),UserState:$S.nullish(),ActiveGroup:Wp.nullish()}),Wa=zod.z.object({ServerTimeUtc:u.nullish(),Group:Wp.nullish(),SecondsRemaining:Q.nullish()}),Qp=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Resources:E.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:ja.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(ja).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:Q.nullish(),MaxProgress:Q.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),Ha=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:E.nullish(),Inventory:K.nullish()}),$p=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Ys=zod.z.object({Chains:zod.z.record(zod.z.string(),rb).nullish()}).passthrough(),Pt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Jp="CoopEvent",Zp={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},Xs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Zp,{schema:Zs,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Jp,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(Jp,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(Zp,()=>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:_()},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 ob={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},ab={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},lb=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(),ub=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),Yp=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(),lb).nullish(),Tracks:zod.z.record(zod.z.string(),ub).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),cb=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:Yp.nullish(),NextCycleStartsAtUtc:u.nullish(),LastUpdatedUtc:u.nullish(),DismissSkipAvailableAtUtc:u.nullish(),LastDismissedAtUtc:u.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),pb=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),hb=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(),pb).nullish()}).passthrough(),db=zod.z.object({Slots:zod.z.record(zod.z.string(),cb).nullish(),OfferHistory:zod.z.record(zod.z.string(),hb).nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),mb={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},fb={Eq:"Eq",Gte:"Gte",Lte:"Lte"},gb=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),er=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(),Xp=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),eh=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),yb=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Behaviour:J.nullish()}).passthrough(),Rb=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:er.nullish(),Availability:Xp.nullish(),Behaviour:eh.nullish(),Queue:zod.z.array(gb).nullish(),Presets:yb.nullish()}).passthrough(),Cb=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),Sb=zod.z.object({RewardedVideo:Cb.nullish()}).passthrough(),bb=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),xb=zod.z.object({Identity:J.nullish(),Graph:J.nullish(),Milestones:J.nullish()}).passthrough(),Db=zod.z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish()}).passthrough(),Ib=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),Pb=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(),vb=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(bb).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),th=zod.z.object({Options:pe.nullish()}).passthrough(),nh=zod.z.object({Grants:$.nullish(),TrackChanges:zod.z.array(Ib).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),Ab=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:er.nullish(),Pricing:th.nullish(),Reward:nh.nullish(),Action:Sb.nullish(),UnlockRules:vb.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:Db.nullish()}).passthrough(),ih=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(Ab).nullish(),Tracks:zod.z.array(Pb).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),sh=zod.z.object({Milestones:zod.z.record(zod.z.string(),Ve).nullish(),ClaimMode:zod.z.string().nullish(),Token:Tt.nullish()}).passthrough(),rh=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:er.nullish(),Graph:ih.nullish(),Milestones:sh.nullish(),Presets:xb.nullish()}).passthrough(),Tb=zod.z.object({Identity:zod.z.record(zod.z.string(),er).nullish(),Availability:zod.z.record(zod.z.string(),Xp).nullish(),Behaviour:zod.z.record(zod.z.string(),eh).nullish(),Graph:zod.z.record(zod.z.string(),ih).nullish(),Milestones:zod.z.record(zod.z.string(),sh).nullish(),Pricing:zod.z.record(zod.z.string(),th).nullish(),Reward:zod.z.record(zod.z.string(),nh).nullish()}).passthrough(),Ka=zod.z.object({Slots:zod.z.record(zod.z.string(),Rb).nullish(),Offers:zod.z.record(zod.z.string(),rh).nullish(),Presets:Tb.nullish()}).passthrough(),oh=zod.z.object({DealOfferDefinitions:Ka.nullish()}),ah=zod.z.object({DealOffers:db.nullish()}),wb=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(),kb=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:rh.nullish(),ActivationState:Yp.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:u.nullish(),Cost:Bt.nullish(),Milestone:wb.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),tr=zod.z.object({Slots:zod.z.array(kb).nullish()}),lh=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:E.nullish(),Inventory:K.nullish()}),uh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:E.nullish()}),ch=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:E.nullish()}),ph=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:E.nullish(),Inventory:K.nullish()}),hh=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:E.nullish(),Inventory:K.nullish()}),zt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var zb="DealOffer",dh={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},nr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(dh,{schema:tr,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(zb,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(dh,()=>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}_${_()}`},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}_${_()}`},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}_${_()}`},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}_${_()}`},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}_${_()}`},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 mh="Referral",ir=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(mh,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(mh,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=hn.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 Mb={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},fh=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),Ob={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},Eb=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),qb={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},Ub=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"},Lb={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"},Bb=100,Gb=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),gh=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(),Nb=zod.z.object({Texts:zod.z.record(zod.z.string(),Gb).nullish(),Category:fh.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:gh.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),_b=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:fe.nullish(),Cost:fe.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),SenderGate:ee.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),Fb=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(),Vb=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(Fb).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:fe.nullish(),SenderGate:ee.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),yh=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(),Nb).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),_b).nullish(),Transfer:Vb.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(),jb=zod.z.object({MessageID:zod.z.string(),Source:Eb,Category:fh,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:gh.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(zn).nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:u,ExpiresAt:u.nullish(),ReadAt:u.nullish(),ClaimedAt:u.nullish()}).passthrough(),Wb=zod.z.object({MessageID:zod.z.string(),Module:Ub,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(),Qa=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),Rh=zod.z.object({ServerTimeUtc:u.nullish(),Messages:zod.z.array(jb).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(Wb).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),sr=zod.z.object({ServerTimeUtc:u.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),$a=zod.z.object({ServerTimeUtc:u.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(Qa).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Hb=zod.z.object({MessageID:zod.z.string(),Rewards:fe.nullish(),Instances:zod.z.array(zn).nullish()}).passthrough(),rr=zod.z.object({ServerTimeUtc:u.nullish(),Claimed:zod.z.array(Hb).default([]),Failed:zod.z.array(Qa).default([]),Resources:E.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Ch=zod.z.object({ServerTimeUtc:u.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(Qa).default([]),Resources:E.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough(),Sh=zod.z.object({ServerTimeUtc:u.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:u.nullish(),Resources:E.nullish(),RecipientReceives:fe.nullish(),RecipientInstances:zod.z.array(zn).nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),bh=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 Ja="Mailbox",Za={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},or=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Za,{schema:sr,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(Za,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Ja)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Ja,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(Ja,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(Za,()=>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 Kb={Head:"Head",Torso:"Torso",Legs:"Legs"},ar=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),Qb={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},Ya=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Dh=zod.z.object({AttackTarget:ar,DefenseTarget:ar});var $b=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),Jb=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:ar.nullish(),DefenseZone:ar.nullish(),HitType:$b.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),Zb=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(),Yb=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),xh=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:oi.nullish(),BattleStrategy:zod.z.array(Dh).nullish(),UnstackableItems:zod.z.record(zod.z.string(),Yb).nullish(),Stats:Zb.nullish()}).passthrough(),li=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:fe.nullish(),NetReward:fe.nullish(),BattleLog:zod.z.array(Jb).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:xh.nullish(),P2BattleProfile:xh.nullish()}).passthrough(),Ih=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(Dh).nullish(),TargetUserID:zod.z.string().nullish(),Entry:fe.nullish(),CreationCostPaid:fe.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:u.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:u.nullish(),Status:Ya.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:u.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:u.nullish()}).passthrough(),Ph=zod.z.object({Status:Ya,MatchID:zod.z.string(),Entry:fe.nullish(),Resources:E.nullish()}),vh=zod.z.object({Match:Ih.nullish()}),Ah=zod.z.object({MatchID:zod.z.string(),Status:Ya,Resources:E.nullish()}),Th=zod.z.object({Battle:li.nullish(),Resources:E.nullish(),ResourcesDual:Gt.nullish()}),Xa=zod.z.object({Matches:zod.z.array(Ih).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),Mt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var Xb=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var ex=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),tx=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(),nx=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),ix=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:nx.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),sx=zod.z.object({Kind:ex.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(),rx=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(sx).nullish()}).passthrough(),fn=zod.z.object({Terms:zod.z.array(rx).nullish()}).passthrough(),ox=zod.z.object({Health:fn.nullish(),Damage:fn.nullish(),Armor:fn.nullish(),AttackSpeed:fn.nullish(),CritChance:fn.nullish(),CritDamage:fn.nullish(),Dodge:fn.nullish()}).passthrough(),wh=zod.z.object({StatMapping:tx.nullish(),Combat:ix.nullish(),Formula:ox.nullish()}).passthrough(),ax=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),ui=zod.z.object({Kind:Xb.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:wi.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),kh=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(ui).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),zh=zod.z.object({PriceOptions:pe.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(),lx=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:ax.nullish(),Entry:kh.nullish(),Creation:zh.nullish(),Settings:wh.nullish()}).passthrough(),ux=zod.z.object({Rules:zod.z.record(zod.z.string(),lx).nullish(),Defaults:wh.nullish(),EntryDefaults:kh.nullish(),CreationDefaults:zh.nullish()}).passthrough(),el=zod.z.object({InstantBattle:ux.nullish()}).passthrough(),Mh=el;var cx={Open:"Open",Request:"Request",InviteOnly:"InviteOnly"},px=zod.z.enum(["Open","Request","InviteOnly"]).catch("Open"),hx={Application:"Application",Invite:"Invite"},dx={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"},mx={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"},fx={Duel:"Duel",Battle:"Battle",League:"League",War:"War"},gx={Ally:"Ally",Pact:"Pact",Enemy:"Enemy",None:"None"},lr="clan",gn=zod.z.array(zod.z.string()).nullish(),Z=zod.z.number().nullish(),yx=zod.z.record(zod.z.string(),zod.z.number()).nullish(),Rx=zod.z.object({NounKey:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SortOrder:Z}).passthrough(),Cx=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:gn,Symbols:gn,Colors:gn}).passthrough().nullish(),Languages:gn,Attributes:zod.z.record(zod.z.string(),zod.z.object({NameKey:zod.z.string().nullish(),Values:gn,Required:zod.z.boolean().nullish()}).passthrough()).nullish(),RenameCooldownHours:Z}).passthrough(),Sx=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:gn}).passthrough(),xx=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(At.passthrough()).nullish(),Funding:zod.z.string().nullish(),MaxPerDonor:Z,MaxHelps:Z,MaxItemLevel:Z,MinMembershipHoursToDonate:Z}).passthrough(),Dx=zod.z.object({Enabled:zod.z.boolean().nullish(),Identity:Rx.nullish(),Create:Cx.nullish(),Membership:Sx.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:gn,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(),xx).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:At.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:yx,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:At.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(),Ix=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Kinds:zod.z.record(zod.z.string(),Dx).nullish(),RefreshSeconds:Z}).passthrough(),nl=zod.z.record(zod.z.string(),zod.z.string()).nullish(),tl=zod.z.record(zod.z.string(),zod.z.number()).nullish(),en=zod.z.object({ClanID:zod.z.string(),KindID:zod.z.string().catch(lr),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:nl,JoinMode:px,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:tl,Perks:tl,Modifiers:zod.z.array(zod.z.object({}).passthrough()).nullish(),Treasury:tl,RecommendedProjectID:zod.z.string().nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),CreatedAt:u.nullish(),ActiveAt:u.nullish()}).passthrough(),il=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(),Px=zod.z.object({KindID:zod.z.string(),Clan:en.nullish(),Membership:il.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(),Eh=zod.z.object({ServerTimeUtc:u.nullish(),RefreshSeconds:zod.z.number().catch(30),Kinds:zod.z.array(Px).catch([])}).passthrough(),sl=zod.z.object({ServerTimeUtc:u.nullish(),Clans:zod.z.array(en).catch([]),NextCursor:zod.z.string().nullish()}).passthrough(),qh=zod.z.object({ServerTimeUtc:u.nullish(),Clan:en,Membership:il.nullish(),Applied:zod.z.boolean().catch(false)}).passthrough(),Uh=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(),Lh=zod.z.object({ServerTimeUtc:u.nullish(),ClanID:zod.z.string().nullish(),Members:zod.z.array(Uh).catch([])}).passthrough(),Oh=zod.z.object({Rank:zod.z.number().catch(0),Value:zod.z.number().catch(0),Clan:en}).passthrough(),Bh=zod.z.object({ServerTimeUtc:u.nullish(),Metric:zod.z.string().nullish(),Slice:zod.z.string().nullish(),Rows:zod.z.array(Oh).catch([]),Mine:Oh.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:en.nullish(),UserID:zod.z.string().nullish(),Player:Uh.nullish(),InviterUserID:zod.z.string().nullish(),Message:zod.z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),rl=zod.z.object({ServerTimeUtc:u.nullish(),Items:zod.z.array(vx).catch([])}).passthrough(),Ax=zod.z.object({Type:zod.z.string().catch(""),ActorUserID:zod.z.string().nullish(),TargetUserID:zod.z.string().nullish(),Params:nl,At:u.nullish()}).passthrough(),Gh=zod.z.object({ServerTimeUtc:u.nullish(),Entries:zod.z.array(Ax).catch([]),NextCursor:zod.z.string().nullish()}).passthrough(),Nh=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:At.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(Nh).catch([])}).passthrough(),Tx=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(),Fh=zod.z.object({ServerTimeUtc:u.nullish(),GiftLevel:zod.z.number().catch(0),GiftPoints:zod.z.number().catch(0),NextGiftLevelPoints:Z,Gifts:zod.z.array(Tx).catch([])}).passthrough(),ur=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(),Vh=zod.z.object({ServerTimeUtc:u.nullish(),Rewards:zod.z.array(ur).catch([])}).passthrough(),jh=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(),Wh=zod.z.object({ClanID:zod.z.string(),Clan:en.nullish(),Relation:zod.z.string().catch("None"),Status:zod.z.string().catch("Active"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),Hh=zod.z.object({ServerTimeUtc:u.nullish(),Clan:en.nullish(),Membership:il.nullish(),Request:Nh.nullish(),Resources:E.nullish(),Inventory:K.nullish(),Done:zod.z.array(zod.z.string()).nullish(),Failed:nl,WarAttack:jh.nullish(),WarBattle:li.nullish(),Relation:Wh.nullish()}).passthrough(),Kh=zod.z.object({ServerTimeUtc:u.nullish(),Definitions:Ix.nullish(),DefaultKindID:zod.z.string().nullish()}).passthrough(),wx=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(wx).nullish()}).passthrough(),zx=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(),Qh=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(zx).catch([]),NextCursor:zod.z.string().nullish(),MyDepositsToday:zod.z.record(zod.z.string(),zod.z.number()).catch({})}).passthrough(),Mx=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(),$h=zod.z.object({ServerTimeUtc:u.nullish(),RecommendedProjectID:zod.z.string().nullish(),Projects:zod.z.array(Mx).catch([])}).passthrough(),Ox=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(ur).catch([])}).passthrough(),Jh=zod.z.object({ServerTimeUtc:u.nullish(),Activities:zod.z.array(Ox).catch([])}).passthrough(),Ex=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(),qx=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(Ex).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(),Ux=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(qx).catch([]),Rewards:zod.z.array(ur).catch([])}).passthrough(),Zh=zod.z.object({ServerTimeUtc:u.nullish(),Boards:zod.z.array(Ux).catch([])}).passthrough(),Lx=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(ur).catch([])}).passthrough(),Yh=zod.z.object({ServerTimeUtc:u.nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),Competitions:zod.z.array(Lx).catch([])}).passthrough(),Bx=zod.z.object({Place:zod.z.number().catch(0),Clan:en.nullish(),Score:zod.z.number().catch(0),RatingDelta:Z,IsMine:zod.z.boolean().catch(false)}).passthrough(),Gx=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(),Xh=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(Bx).catch([]),War:zod.z.array(Gx).nullish(),MyAttacks:zod.z.array(jh).nullish()}).passthrough(),ed=zod.z.object({ServerTimeUtc:u.nullish(),CanManage:zod.z.boolean().catch(false),Relations:zod.z.array(Wh).catch([]),Limits:zod.z.record(zod.z.string(),zod.z.number()).catch({}),Counts:zod.z.record(zod.z.string(),zod.z.number()).catch({})}).passthrough(),Nx=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(),td=zod.z.object({ServerTimeUtc:u.nullish(),Revenges:zod.z.array(Nx).catch([]),TakenToday:zod.z.number().catch(0),DailyLimit:zod.z.number().catch(0)}).passthrough(),_x=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(),nd=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:_x.nullish()}).passthrough();var ol="Clan",cr=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(ol)}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]??lr]}async getDefinitions(e){let t=this.ctx.cache.configSection(ol,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(ol,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_${_()}`})}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_${_()}`})}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 Gn={GetDefinitions:"GetDefinitions",GetAvatars:"GetAvatars",GetShop:"GetShop",BuyItem:"BuyItem"},Fx={TooManyUsers:"AVATAR_TOO_MANY_USERS",Disabled:"AVATAR_DISABLED",NotForSale:"AVATAR_ITEM_NOT_FOR_SALE"},pr=50,hr=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(),Vx=48,jx=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(),id=zod.z.object({id:zod.z.string(),slot:zod.z.string()}).passthrough(),sd=zod.z.object({Enabled:zod.z.boolean(),Avatars:zod.z.array(jx).nullish().transform(r=>r??[]),Items:zod.z.record(zod.z.string(),id).nullish().transform(r=>r??{})}).passthrough(),Wx=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(),rd=zod.z.object({Enabled:zod.z.boolean(),Offers:zod.z.array(Wx).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(),id).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(),od=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 Hx="Avatar",dr=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(Hx)??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+=pr){let p=s.slice(o,o+pr),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?Kx(i,e.Items):[]}),t.push(n.UserID);}t.length>0&&this.ctx.emitter.emit("avatar:changed",{userIDs:t});}};function Kx(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 mr={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},al="idos-app",ad=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()}),ld=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:E.nullish()});var Qx=new Set(["CANCELLED","DECLINED","CLOSED"]),$x=45e3,Jx=r=>new Promise(e=>setTimeout(e,r)),fr=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!==al&&(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:Qx.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()+$x;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 Jx(o);}}};var Vt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},Zx={Client:"Client",Server:"Server",System:"System"},Yx=zod.z.enum(["Client","Server","System"]).catch("Client"),ll=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:Yx.nullish(),ExpiresAt:u.nullish()}).passthrough(),gr=zod.z.record(zod.z.string(),ll),ud=zod.z.object({Version:zod.z.number().nullish(),Private:gr.nullish(),Public:gr.nullish(),ReadOnly:gr.nullish()}),ul=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:gr.nullish()}),cl=zod.z.object({ServerTimeUtc:u.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),Xx=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),cd=zod.z.object({ServerTimeUtc:u.nullish(),Results:zod.z.array(Xx).nullish()}),pd=zod.z.object({ServerTimeUtc:u.nullish(),DeletedCount:zod.z.number().nullish()}),hd=zod.z.object({Results:zod.z.array(ul).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),eD={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},tD=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),nD=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:tD.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(),nD).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(),vt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var iD={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},sD={Title:"Title",Platform:"Platform"},dd=zod.z.object({UserID:zod.z.string(),PublicData:Ne.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()});var rD=zod.z.object({StageLevel:zod.z.number().nullish(),SpecialPlayedCount:zod.z.number().nullish()}),md=zod.z.object({UserID:zod.z.string(),IsSelf:zod.z.boolean().nullish(),PublicData:Ne.nullish(),Characters:zod.z.record(zod.z.string(),oi).nullish(),StrongestCharacterID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),Board:rD.nullish(),PublicCustomData:zod.z.record(zod.z.string(),ll).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 ci=zod.z.object({Friends:zod.z.array(dd).nullish()}),oD=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),pi=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:dd.nullish(),Counters:oD.nullish()}),aD={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},lD={Like:"Like",Favorite:"Favorite"},uD={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},cD={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},pD={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived",ArenaDefeat:"ArenaDefeat"},hD=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),dD=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(hD).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:E.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),fd=zod.z.object({Items:zod.z.array(dD).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(),hi=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),mD=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(),tn=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:mD.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),gd=zod.z.object({Items:zod.z.array(tn).nullish()}).passthrough(),pl={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},fD=zod.z.object({UserID:zod.z.string(),PublicData:Ne.nullish(),Mutual:zod.z.boolean().nullish(),Since:u.nullish()}).passthrough(),Rr=zod.z.object({Items:zod.z.array(fD).nullish(),...pl}).passthrough(),gD=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:u.nullish()}).passthrough(),yd=zod.z.object({Items:zod.z.array(gD).nullish(),...pl}).passthrough(),Cr=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(),Rd=zod.z.object({Items:zod.z.array(Cr).nullish(),...pl,TotalCount:zod.z.number().nullish()}).passthrough(),Cd=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),Sd=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),bd=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(),yD="FRIENDS_FROM_PLATFORM",RD={Off:"Off",Default:"Default",Always:"Always"},CD={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},xd=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 hl={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Sr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(hl,{schema:hi,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(hl,()=>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(hl,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 Dd="TimedBoost";function SD(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var br=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Dd,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(Dd,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(!SD(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}_${_()}`},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 Id(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var xr=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,Vt.Private)}async setPublicData(e,t){return this.setData(e,t,Vt.Public)}async setData(e,t,n){let i=e.trim();if(!Id(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===Vt.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===Vt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",m);}return p}async deleteKey(e,t){let n=e.trim();if(!Id(n))return h("client",'KeyID is required and must not contain "." or "$".');if(t!==Vt.Private&&t!==Vt.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??Vt.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 xD="TitleCustomDataDefinitions",Pd=50;function DD(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function dl(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function ID(r){let e={};for(let[t,n]of Object.entries(r))dl(n)||(e[t]=n);return e}var Dr=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(xD,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=>!DD(s)))return h("client",'KeyID must not contain "." or "$".');if(t.length>Pd)return h("client",`At most ${Pd} 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&&!dl(t))return t.Value;let n=this.staticCache[e];if(n?.Value!=null&&!dl(n))return n.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=ID(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 Ir=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 PD={Fast:"Fast",Sequential:"Sequential"},vD={Instant:"Instant",Timed:"Timed"};var AD={Hit:"Hit",Blocked:"Blocked"},TD=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),wD=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(),zD=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:zD.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 vd=zod.z.object({}).passthrough().transform(r=>r),Ad=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Ye=zod.z.object({Operation:E.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),MD=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),OD=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(),ED=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:fe.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(),qD=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:fe.nullish()}).passthrough(),Td=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(),UD=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(),LD=zod.z.object({Tiles:zod.z.record(zod.z.string(),UD).nullish()}).passthrough(),BD=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Ye.nullish(),Tag:zod.z.string().nullish()}).passthrough(),GD=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(BD).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(),ND=zod.z.object({Variants:zod.z.array(GD).nullish()}).passthrough(),_D=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(),FD=zod.z.object({Outcomes:zod.z.array(_D).nullish()}).passthrough(),wd=zod.z.object({PerAdMultiplierRange:Ad.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(),VD=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Ye.nullish()}).passthrough(),jD=zod.z.object({Tiers:zod.z.array(VD).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Ye.nullish()}).passthrough(),WD=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Ye.nullish()}).passthrough(),HD=zod.z.object({Reward:Ye.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),KD=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(WD).nullish(),Rate:HD.nullish()}).passthrough(),kd=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),KD).nullish()}).passthrough(),QD=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Ye.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:pe.nullish(),Multipliers:wd.nullish(),Gradation:jD.nullish(),RunStats:kd.nullish()}).passthrough(),$D=zod.z.object({Choices:zod.z.array(QD).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),JD=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Ye.nullish(),Tag:zod.z.string().nullish()}).passthrough(),ZD=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(JD).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),FD).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),$D).nullish()}).passthrough(),zd=zod.z.object({BaseAttackReward:$.nullish(),BaseRaidReward:$.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Td).nullish(),HeistGridBonusConfig:ND.nullish(),StageOperations:ZD.nullish(),TileLandingMultiplier:Ad.nullish(),EconomyOverride:qD.nullish()}).passthrough(),YD=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(Td).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:zd.nullish()}).passthrough(),XD=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(),eI=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(),tI=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(),Pr=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(),LD).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),zd).nullish(),StagesByLevel:zod.z.record(zod.z.string(),YD).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:ED.nullish(),Dice:MD.nullish(),Bots:OD.nullish(),Targeting:XD.nullish(),BotRaids:eI.nullish(),RewardBoost:tI.nullish()}).passthrough(),nI=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(),vr=zod.z.object({Board:Pr.nullish(),CommunityChest:nI.nullish()}).passthrough(),Md=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),fe).nullish()}).passthrough(),iI=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:Ne.nullish(),TargetBuildingStates:zod.z.array(TD).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:Md.nullish()}).passthrough(),sI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Ye.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:pe.nullish(),Multipliers:wd.nullish(),RunStats:kd.nullish()}).passthrough(),rI=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(sI).nullish()}).passthrough(),oI=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(),Od=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:E.nullish(),Inventory:K.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:iI.nullish(),SpecialModeOffer:rI.nullish(),CommunityChestContribution:oI.nullish()}).passthrough(),Ar={Ad:"Ad",Premium:"Premium"},Ed=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(At).nullish()}).passthrough(),qd=zod.z.object({BoostID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Multiplier:zod.z.number().nullish(),AlreadyApplied:zod.z.boolean().nullish(),Operation:E.nullish(),Inventory:K.nullish(),AdRemainingToday:zod.z.number().nullish(),PremiumRemainingToday:zod.z.number().nullish()}).passthrough(),Ud=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:E.nullish(),Inventory:K.nullish(),DualResult:Gt.nullish(),RewardBoost:Ed.nullish()}).passthrough(),ml=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(wD).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:E.nullish(),Inventory:K.nullish(),DualResult:Gt.nullish(),RaidRewardPreview:Md.nullish(),RewardBoost:Ed.nullish()}).passthrough(),Ld=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:E.nullish(),Inventory:K.nullish()}).passthrough(),Bd=zod.z.object({CreditsConfirmation:ye.nullish(),Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:E.nullish(),Inventory:K.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish()}).passthrough(),Gd=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(),aI=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),Nd=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:E.nullish(),Inventory:K.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(aI).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:$.nullish()}).passthrough(),lI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},_d=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),uI={Active:"Active",Left:"Left",Replaced:"Replaced"},cI=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),pI=zod.z.object({CurrentProgress:Q.nullish(),MaxProgress:Q.nullish()}).passthrough(),hI=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(),ju).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:cI.nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),Fd=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(hI).nullish(),SharedProgress:pI.nullish(),Status:_d.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),dI=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(),mI=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(dI).nullish()}).passthrough(),Vd=zod.z.object({ServerTimeUtc:u.nullish(),UserState:mI.nullish(),ActiveGroup:Fd.nullish(),SecondsRemaining:Q.nullish()}),jd=zod.z.object({ServerTimeUtc:u.nullish(),Group:Fd.nullish(),SecondsRemaining:Q.nullish()}),fl=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:E.nullish(),Inventory:K.nullish()}),Wd=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 fI=15,gI="GameLoop",Hd="BoardDefinition",di="InventoryV2",yI="GameLoop",Tr=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(gI,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let n=this.ctx.cache.configSection(Hd,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(Hd,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[di]!==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([di]),this.ctx.cache.ensureState([di]),this.ctx.emitter.emit("user:changedElsewhere",{containers:[di]}))),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}_${_()}`},i=await this.ctx.api.gameLoop.boardLoopRoll(n);if(i.ok){let s=i.data,o=gc(new Date,fI);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}_${_()}`},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}_${_()}`},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}_${_()}`},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}_${_()}`},i=await this.ctx.api.gameLoop.boardLoopBuild(n);if(!i.ok&&i.reason==="server"&&await this.ctx.cache.ensureState([di,yI],{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}_${_()}`},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=Ar.Ad){let n=this.ctx.auth.context;if(!n)return l;let i=t===Ar.Premium,s={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_${i?"vip":"ad"}_${n.userID}_${_()}`,...i?{BoostMode:Ar.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}_${_()}`,...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 wr=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 Kd=zod.z.object({ServerTimeUtc:u,SourceType:An,SourceID:zod.z.string(),TargetType:An,TargetID:zod.z.string(),SourceSpent:Q,FeeAmount:Q,RateApplied:ne,TargetCredited:Q}),Qd=zod.z.object({ServerTimeUtc:u,SourceType:An,SourceID:zod.z.string(),TargetType:An,TargetID:zod.z.string(),SourceSpent:ne,FeeAmount:ne,RateApplied:ne,TargetCredited:ne}),$d=zod.z.object({ServerTimeUtc:u,SpendID:zod.z.string(),Resources:E.nullish()}),mi={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},RI={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},Jd=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),CI={Automatic:"Automatic",Manual:"Manual"},SI=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),bI=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(),xI=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),DI=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),II=zod.z.object({TargetCurrencyType:An.nullish(),TargetCurrencyID:zod.z.string(),Rate:ne.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),Zd=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:SI.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(II).nullish()}).passthrough(),Yd=zod.z.object({CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough(),PI=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:bI.nullish(),Recharge:xI.nullish(),Conversion:Zd.nullish(),Permissions:DI.nullish(),Audit:Yd.nullish(),Status:Jd.nullish()}).passthrough(),vI=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(),AI=zod.z.object({DailyWithdrawUsd:ne.nullish(),MonthlyWithdrawUsd:ne.nullish(),KycRequiredAboveUsd:ne.nullish()}).passthrough(),TI=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),wI=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(),gl=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(vI).nullish(),Limits:AI.nullish(),Permissions:TI.nullish(),Conversion:Zd.nullish(),Audit:Yd.nullish(),Status:Jd.nullish(),ServerGrantPolicy:wI.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),kI=zod.z.object({SpendID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),PriceOptions:zod.z.record(zod.z.string(),as).nullish()}).passthrough(),kr=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),PI).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),gl).nullish(),Spends:zod.z.record(zod.z.string(),kI).nullish()}).passthrough();var zI={EVM:"EVM",Solana:"Solana"},MI=zod.z.enum(["EVM","Solana"]).catch("EVM"),OI={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},EI=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),qI={Token:"Token",Nft:"Nft"},Xd=zod.z.enum(["Token","Nft"]).catch("Token"),UI={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},LI=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),BI={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},GI=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),NI={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},yl=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),em={GameTopUp:"game_topup",CommunityReward:"community_reward"};function zr(r){let e=r?.trim();return e||em.GameTopUp}var _I={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},tm=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),FI=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(),nm=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),VI=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:MI.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:nm.nullish(),NftCollections:zod.z.array(FI).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(),jI=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:nm.nullish()}).passthrough(),WI=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),HI={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},KI=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),im=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:ne.nullish(),BalanceSource:KI.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),QI=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),$I={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},fi=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),JI=zod.z.object({Mode:fi.nullish(),TokenGates:zod.z.array(im).nullish()}).passthrough(),Rl=zod.z.object({SystemState:jI.nullish(),Networks:zod.z.record(zod.z.string(),VI).nullish(),AccountSafety:WI.nullish(),WalletLogin:QI.nullish(),PlayAccess:JI.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),ZI=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:u.nullish(),LastUsedAt:u.nullish(),LinkType:EI.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),sm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:Xd.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:ne.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),YI=zod.z.object({Status:LI.nullish(),Tier:GI.nullish(),VerifiedAt:u.nullish(),ExpiresAt:u.nullish(),RejectedAt:u.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),XI=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(),eP=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(),XI).nullish()}).passthrough(),tP=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(),nP=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(),tP).nullish()}).passthrough(),iP=zod.z.object({Tokens:eP.nullish(),Nfts:nP.nullish()}).passthrough(),Cl=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:ne.nullish(),MinBalance:ne.nullish()}).passthrough(),nn=zod.z.object({Granted:zod.z.boolean(),Mode:fi.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(Cl).nullish()}).passthrough(),sP=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(Cl).nullish()}).passthrough(),rP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),rm=zod.z.object({Mode:fi.nullish(),TokenGates:zod.z.array(im).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(rP).nullish(),Status:nn.nullish()}).passthrough(),oP=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(Cl).nullish()}).passthrough(),aP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:u.nullish()}).passthrough(),lP=zod.z.object({Version:zod.z.number().nullish(),Stats:iP.nullish(),LinkedWallets:zod.z.record(zod.z.string(),ZI).nullish(),LastWalletLogin:oP.nullish(),PlayAccess:sP.nullish(),PendingWithdrawals:zod.z.array(sm).nullish(),Kyc:YI.nullish(),FirstActivityAt:u.nullish(),LastActivityAt:u.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(aP).nullish()}).passthrough(),uP=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:ne,FrozenDelta:ne,UpdatedAt:u}).passthrough(),Nn=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),uP).nullish(),PendingAdded:sm.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),cP=zod.z.object({Amount:ne,Frozen:ne,CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough().transform(r=>r),pP=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:tm.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:ne.nullish(),Status:yl.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(),hP=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:tm.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:ne.nullish(),Status:yl.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(),om=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Sl=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(om).nullish(),Signature:zod.z.string().nullish()}).passthrough(),bl=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(om).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(),am=zod.z.object({Blockchain:Rl.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),gl).nullish()}).passthrough(),lm=zod.z.object({State:lP.nullish(),CryptoBalances:zod.z.record(zod.z.string(),cP).nullish()}).passthrough(),um=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:Nn.nullish()}).passthrough(),cm=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:E.nullish(),Inventory:K.nullish()}).passthrough(),pm=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:Sl.nullish(),SolanaSignature:bl.nullish(),StateDelta:Nn.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),hm=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:E.nullish(),EvmSignature:Sl.nullish(),SolanaSignature:bl.nullish(),StateDelta:Nn.nullish(),Inventory:K.nullish()}).passthrough(),dm=zod.z.object({TokenTransactions:zod.z.array(pP).nullish(),NFTTransactions:zod.z.array(hP).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),xl=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(),mm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:Xd.nullish(),EvmSignature:Sl.nullish(),SolanaSignature:bl.nullish()}).passthrough(),fm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:yl.nullish(),StateDelta:Nn.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 dP="Blockchain",gm="Blockchain:Definitions",Mr=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(gm,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(dP,s.data.Blockchain),this.ctx.data.config.patchSection(gm,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=zr(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=zr(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 mP={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Dl=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),fP={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Il=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),gP={Burn:"Burn",Ledger:"Ledger"},yP=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Er={Item:"Item",VirtualCurrency:"VirtualCurrency"},Pl=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),RP=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:Q.nullish()}).passthrough(),qr=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(ui).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),vl=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:Q.nullish(),Sink:yP.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),RP).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),CP=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(),SP=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:pe.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),bP=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(),xP=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(),DP=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(),IP=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Al=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:ee.nullish(),Schedule:Ce.nullish(),PricePolicy:qr.nullish(),Commission:vl.nullish(),Tradability:CP.nullish(),Listings:SP.nullish(),Auctions:bP.nullish(),BuyOrders:xP.nullish(),DirectTrades:DP.nullish(),Matching:IP.nullish()}).passthrough(),ym=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(),PP=zod.z.object({BidAxisType:Tn.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(ym).nullish()}).passthrough(),Or=zod.z.object({LastAt:u.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),vP=zod.z.object({Create:Or.nullish(),Buy:Or.nullish(),Sell:Or.nullish(),Bid:Or.nullish()}).passthrough(),AP=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),TP=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:AP.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),jt=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Dl.nullish(),Status:Il.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:Ne.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:Pl.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:Q.nullish(),GoodsInstances:zod.z.array(TP).nullish(),Price:fe.nullish(),Auction:PP.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),wP=zod.z.object({GoodsType:Pl.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(Dl,Q).nullish()}).passthrough(),Rm=zod.z.object({Definitions:Al.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),Tl=zod.z.object({Offers:zod.z.array(jt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Cm=zod.z.object({Groups:zod.z.array(wP).nullish()}).passthrough(),Sm=zod.z.object({Offer:jt.nullish()}).passthrough(),Rt=zod.z.object({OfferID:zod.z.string().nullish(),Status:Il.nullish(),Settlement:Gt.nullish(),Resources:E.nullish(),CommissionTaken:fe.nullish()}).passthrough(),gi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:jt.nullish(),Resources:E.nullish(),Matched:zod.z.boolean().nullish(),Settlement:Rt.nullish()}).passthrough(),bm=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:Q.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:E.nullish()}).passthrough(),Ur=zod.z.object({MyOffers:zod.z.array(jt).nullish(),MyBids:zod.z.array(jt).nullish(),MyBuyOrders:zod.z.array(jt).nullish(),IncomingTrades:zod.z.array(jt).nullish(),OutgoingTrades:zod.z.array(jt).nullish(),Claimables:zod.z.array(jt).nullish(),DrainedRefunds:zod.z.array(ym).nullish(),Limits:vP.nullish()}).passthrough(),kP=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Dl.nullish(),FinalStatus:Il.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:Pl.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:Q.nullish(),PricePaid:fe.nullish(),CommissionTaken:fe.nullish(),CompletedAt:u.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),xm=zod.z.object({Entries:zod.z.array(kP).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 zP="Marketplace",Dm={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"]},Lr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Dm,{schema:Ur,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(zP,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(Dm,()=>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);return n.ok&&this.applyMyState(n.data),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=Er.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Er.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 Br=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 Im=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Gr=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 V=Pm(m.data,m.contentType);return t.set(g,V),{Role:m.role,ContentType:m.contentType,Size:V.size}}),i=e.thumbnail?Pm(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 V=t.get(m);if(!V)return h("client",`No bytes for file #${m+1}.`);let ce=await this.putBytes(g.Url,V,g.ContentType??V.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)}${Im}`)}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)}${Im}`)}}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 Pm(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 MP={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},OP=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),EP={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},vm=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),qP={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Am=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),UP={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},LP=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),BP={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},GP=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),NP={Count:"Count",Sum:"Sum"},_P=zod.z.enum(["Count","Sum"]).catch("Count"),FP={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},VP=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),jP={Strict:"Strict",Loose:"Loose"},WP=zod.z.enum(["Strict","Loose"]).catch("Strict"),HP=zod.z.object({Kind:GP,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),KP=zod.z.object({Type:vm,ItemType:vm.nullish(),Ref:HP.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:Am.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()}),QP=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Nr=zod.z.object({Mode:LP,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),$P=zod.z.object({Read:zod.z.array(Nr).nullish(),Create:zod.z.array(Nr).nullish(),Update:zod.z.array(Nr).nullish(),Delete:zod.z.array(Nr).nullish()}),wl=zod.z.object({Cost:fe.nullish(),Grant:fe.nullish()}),JP=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()}),ZP=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:OP,Mode:WP.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),KP).nullish(),SortKeys:zod.z.array(QP).nullish(),Access:$P.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:VP.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:_P,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:Am.optional()})).nullish(),Economy:zod.z.object({OnCreate:wl.nullish(),OnUpdate:wl.nullish(),OnDelete:wl.nullish()}).nullish(),WriteGate:ee.nullish(),PublicViews:zod.z.array(JP).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()}),Tm=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),ZP).default({})}),YP=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),wm=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),_n=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(),YP).nullish()}),kl=zod.z.object({Item:_n}),km=zod.z.object({Items:zod.z.array(_n).default([]),Missing:zod.z.array(zod.z.string()).default([])}),zl=zod.z.object({Items:zod.z.array(_n).default([]),NextCursor:zod.z.string().nullish()}),zm=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),Ml=zod.z.object({Item:_n,AlreadyExists:zod.z.boolean().optional(),Economy:E.nullish()}),Mm=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:E.nullish()}),Om=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),Em=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:_n.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),qm=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),Um=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),Lm=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({})}),Bm=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(_n).default([])}),XP={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 ev=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,_m=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,El=100,Gm=25,Nm=100;function tv(r,e,t){return {Field:r,Op:e,Value:t}}var _r=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)??yi(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=>_m.test(o)))];return s.length?s.length>Nm?Promise.resolve(h("client",`At most ${Nm} 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)??Ol(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??El},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)??Ol(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?yi(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)??yi(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)??yi(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>Gm)return Promise.resolve(h("client",`At most ${Gm} 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,Lm);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`,Bm);return g.ok?B({pointer:o.data,page:g.data}):g}getPublic(e,t){let n=pt(e)??yi(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let n=pt(e)??Ol(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 ev.test(r??"")?null:h("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function yi(r){return _m.test(r??"")?null:h("client",`Item id '${r}' is invalid.`)}function Ol(r){return r.Limit!=null&&(r.Limit<1||r.Limit>El)?h("client",`Limit must be 1..${El}.`):(r.Where?.length??0)>8?h("client","At most 8 filters per query."):null}var ql={Open:"Open",Declared:"Declared"},nv=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),iv=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),Fm=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),nv).nullish(),Dimensions:zod.z.array(iv).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),sn={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Ot={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Fr=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,sv={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},rv=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),Vm=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(rv).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Ul={LogEvents:"LogEvents"};function jm(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 Wm(r){let e=typeof navigator>"u"?void 0:navigator,t=jm(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 ov=25,av=3e4,Hm=1800*1e3,Km=500,lv=5,uv=1e3,cv=3600*1e3,Qm="idos_analytics_queue",Ll="idos_analytics_pending",Bl="idos_analytics_opt_out",$m="idos_analytics_first_open",Jm="idos_analytics_last_activity",Zm="idos_analytics_last_context",Ym="idos_analytics_owner",Vr=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"||!Fr.test(e)?h("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):pv(e)?h("client",`Event name "${e}" uses a reserved prefix (${Ot.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(sn.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:_(),Events:this.queue.splice(0,Ot.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>=lv)&&(this.pending=null),this.persist(),n)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Bl);return}this.write(Bl,"1"),this.clear();}get isEnabled(){return this.read(Bl)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(Ym);e&&t&&t!==e&&this.clear(),e&&this.write(Ym,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},av),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(Jm)??"0");this.read($m)||(this.write($m,new Date().toISOString()),this.enqueue(sn.FirstOpen,void 0,void 0,true));let t=this.clientContext(),n=this.readJson(Zm);n?.AppVersion&&t.AppVersion&&n.AppVersion!==t.AppVersion&&this.enqueue(sn.AppUpdate,{previous_app_version:n.AppVersion},void 0,true),n?.OsVersion&&t.OsVersion&&n.OsVersion!==t.OsVersion&&this.enqueue(sn.OsUpdate,{previous_os_version:n.OsVersion},void 0,true),this.writeJson(Zm,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Hm)&&this.enqueue(sn.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>=Hm&&this.enqueue(sn.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()===ql.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=hv(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>Km&&this.queue.splice(0,this.queue.length-Km),this.touch(),this.persist(),this.started&&this.queue.length>=ov&&this.flush(),B(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},uv));}dropStale(){let e=Date.now()-(Ot.maxEventAgeMs-cv);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??=Wm({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(Qm);Array.isArray(e)&&(this.queue=e.filter(n=>typeof n?.Name=="string").concat(this.queue));let t=this.readJson(Ll);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(Qm,this.queue),this.pending?this.writeJson(Ll,this.pending):this.remove(Ll);}touch(){this.write(Jm,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 pv(r){let e=r.toLowerCase();return Ot.reservedPrefixes.some(t=>e.startsWith(t))}function hv(r){if(!r)return {};let e=Object.keys(r);if(e.length===0)return {};if(e.length>Ot.maxParams)return {error:`Too many parameters: ${e.length}, max ${Ot.maxParams}.`};let t={};for(let n of e){if(!Fr.test(n))return {error:`Invalid parameter name "${n}".`};let i=r[n];typeof i=="string"?t[n]=i.length>Ot.maxStringValueLength?i.slice(0,Ot.maxStringValueLength):i:typeof i=="number"?Number.isFinite(i)&&(t[n]=i):typeof i=="boolean"&&(t[n]=i);}return {params:t}}var dv="idos_experiments",jr=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 `${dv}:${this.ctx.settings.titleID}`}};function rn(r,e,t,n){let s=`api/v2/${r&&r.length>0?r:"0"}/Client/${e}/${t}`;return n==null?s:`${s}/${n}`}var N=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return rn(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 Wr=class extends N{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Ul.LogEvents,e,Vm,{silent:true})}};var mv=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(),fv={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},gv=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),yv=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(mv).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(gv).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),Xm=zod.z.object({Experiments:zod.z.record(zod.z.string(),yv).nullish()}).passthrough(),Rv={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Cv=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(),ef=zod.z.object({Experiments:zod.z.array(Cv).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),Gl={GetExperiments:"GetExperiments"};var Hr=class extends N{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Gl.GetExperiments,e,ef)}};var Sv={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},tf=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),bv=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),nf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),bv).nullish(),MissingKeyMode:tf.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),xv=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),sf=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:xv.nullish()}).passthrough(),Kr={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Dv=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),rf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:tf.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(Dv).nullish()}).passthrough(),of=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 Ri=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:sf.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(r=>r),af=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(r=>r),lf=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),uf=zod.z.object({}).passthrough().transform(r=>r),cf=zod.z.object({}).passthrough().transform(r=>r),pf=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(),hf=zod.z.object({Username:zod.z.string()}),Ct={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var df=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:nn.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:u.nullish(),ClientState:Ri.nullish()}),mf=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,RefreshToken:zod.z.string(),RefreshTokenExpiration:u.nullish(),PlayAccess:nn.nullish()}),Iv=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),ff=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:fi.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:Iv.nullish()}).passthrough(),gf=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:nn.nullish()}).passthrough(),yf=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:u.nullish(),PlayAccess:nn.nullish()}).passthrough(),Rf=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()}),Cf=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 Qr=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return rn(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,df,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(He.RefreshSession),e,mf,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(He.GetAuthOptions),e,ff,{ticket:null})}linkWallet(e){return this.ctx.transport.post(rn(this.ctx.settings.titleID,"Authentication",He.LinkWallet,e.UserID??""),e,gf,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(rn(this.ctx.settings.titleID,"Authentication",He.UnlinkWallet,e.UserID??""),e,yf,{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,Rf,{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,Cf,{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 $r=class extends N{constructor(e){super(e,"User");}getClientState(e){return this.send(Ct.GetClientState,e,Ri)}getClientStateExcept(e){return this.send(Ct.GetClientStateExcept,e,Ri)}getStateVersions(e){return this.send(Ct.GetStateVersions,e,af)}getUserState(e){return this.send(Ct.GetUserState,e,lf)}getInventory(e){return this.send(Ct.GetInventory,e,uf)}getEventTokens(e){return this.send(Ct.GetEventTokens,e,cf)}getUsageTime(e){return this.send(Ct.GetUsageTime,e,pf)}addUsageTime(e){return this.send(Ct.AddUsageTime,e,Ke,{silent:true})}deleteUserAccount(e){return this.send(Ct.DeleteUserAccount,e,Ke)}changeUsername(e){return this.send(Ct.ChangeUsername,e,hf)}};var Jr=class extends N{constructor(e){super(e,"Currency");}convert(e){return this.send(mi.Convert,e,Kd)}spend(e){return this.send(mi.Spend,e,$d)}cryptoConvert(e){return this.send(mi.CryptoConvert,e,Qd)}};var Pv=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),Nl=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:E.nullish(),FodderConsumed:zod.z.array(Pv).nullish()}),Sf=zod.z.array(Oe(Nl)),Zr={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},vv={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},Av=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Tv={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},wv=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),kv=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),zv=zod.z.object({Networks:zod.z.record(zod.z.string(),kv).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),Mv=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(),Ov=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(),Ev=zod.z.object({ValuationMode:Av.nullish(),WeightCurve:Je.nullish(),Selection:wv.nullish()}).passthrough(),qv=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:pe.nullish(),CostCurve:Je.nullish(),FlatBonusCurve:Je.nullish(),PercentBonusCurve:Je.nullish(),PowerCurve:Je.nullish(),Fodder:Ev.nullish()}).passthrough(),Uv=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),Lv=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:zv.nullish(),Stats:Mv.nullish(),Equipment:Ov.nullish(),Upgrade:qv.nullish(),Metadata:Uv.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),Bv=zod.z.object({Items:zod.z.record(zod.z.string(),Lv).nullish()}).passthrough(),Gv={Cumulative:"Cumulative",HighestOnly:"HighestOnly"},Nv=zod.z.enum(["Cumulative","HighestOnly"]).catch("Cumulative"),_v=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(),Fv=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(_v).nullish()}).passthrough(),Vv=zod.z.object({BonusMode:Nv.nullish()}).passthrough(),Yr=zod.z.object({Catalogs:zod.z.record(zod.z.string(),Bv).nullish(),Sets:zod.z.record(zod.z.string(),Fv).nullish(),SetSettings:Vv.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 Xr=class extends N{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(Zr.UpgradeLevel,e,we(Nl))}upgradeLevelsBatch(e){return this.send(Zr.UpgradeLevelsBatch,e,Sf)}};var eo=class extends N{constructor(e){super(e,"Store");}purchase(e){return this.send(_t.Purchase,e,va)}purchaseBatch(e){return this.send(_t.PurchaseBatch,e,Dc)}getDefinitions(e){return this.send(_t.GetDefinitions,e,us)}getUserState(e){return this.send(_t.GetUserState,e,Ic)}getStorefront(e){return this.send(_t.GetStorefront,e,cs)}getCreditsConfirmation(e){return this.send(_t.GetCreditsConfirmation,e,ye)}getCreditsBalance(e){return this.send(_t.GetCreditsBalance,e,xc)}};var jv={Apple:"Apple",Google:"Google"},to=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(),no=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),to).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(r=>r),Wv=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:pe.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Fl=zod.z.object({Definitions:zod.z.record(zod.z.string(),Wv).nullish()}).passthrough(),bf=zod.z.object({Premium:Fl.nullish()}),xf=zod.z.object({ServerTimeUtc:u.nullish(),Premium:no.nullish()}),io=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),Premium:no.nullish(),Subscription:to.nullish(),Resources:E.nullish()}),yn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var Hv={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},Kv=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Df=zod.z.object({StartUtc:u.nullish(),EndUtc:u.nullish(),Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),Vl=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),Qv=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:$.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),$v=zod.z.object({Rewards:J.nullish(),Rules:J.nullish(),Refund:J.nullish()}).passthrough(),Jv=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:Kv.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:Df.nullish(),Refund:Vl.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:Qv.nullish(),Presets:$v.nullish()}).passthrough(),Zv=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(),Yv=zod.z.object({Rewards:$.nullish()}).passthrough(),Xv=zod.z.object({Rules:Df.nullish()}).passthrough(),eA=zod.z.object({Refund:Vl.nullish()}).passthrough(),tA=zod.z.object({Rewards:zod.z.record(zod.z.string(),Yv).nullish(),Rules:zod.z.record(zod.z.string(),Xv).nullish(),Refund:zod.z.record(zod.z.string(),eA).nullish()}).passthrough(),nA=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(),iA=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),Jv).nullish(),Stores:zod.z.record(zod.z.string(),Zv).nullish(),Presets:tA.nullish(),Validation:nA.nullish(),Refund:Vl.nullish()}).passthrough(),If=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(),Pf=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(),sA=zod.z.object({Products:zod.z.record(zod.z.string(),If).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Pf).nullish(),LastRefundCheckAt:u.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:u.nullish(),LastPurchaseAt:u.nullish()}).passthrough(),rA=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(),vf=zod.z.object({ServerTimeUtc:u,Purchase:iA.nullish(),Availability:zod.z.array(rA).nullish()}),Af=zod.z.object({ServerTimeUtc:u,Purchase:sA.nullish()}),oA={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},aA=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),jl=zod.z.object({ServerTimeUtc:u,Store:Ti.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:aA.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:E.nullish(),Inventory:K.nullish(),ProductState:If.nullish(),Premium:no.nullish(),Subscription:to.nullish(),SubscriptionMirror:Pf.nullish()}).passthrough(),Tf=zod.z.object({ServerTimeUtc:u,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:u.nullish()}).passthrough(),wf=wt(jl),Rn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var so=class extends N{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(Rn.GetDefinitions,e,vf)}getUserState(e){return this.send(Rn.GetUserState,e,Af)}validatePurchase(e){return this.send(Rn.ValidatePurchase,e,jl)}validatePurchasesBatch(e){return this.send(Rn.ValidatePurchasesBatch,e,wf)}createTelegramInvoice(e){return this.send(Rn.CreateTelegramInvoice,e,Tf)}};var lA=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),kf=zod.z.object({Reward:$.nullish(),Weight:zod.z.number().nullish(),AmountRange:lA.nullish()}).passthrough(),Fn=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(kf).nullish()}).passthrough(),Vn=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(kf).nullish()}).passthrough(),uA=zod.z.object({RewardSlots:zod.z.array(Fn).nullish()}).passthrough(),cA=zod.z.object({PityRules:zod.z.array(Vn).nullish()}).passthrough(),ro=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),uA).nullish(),PityPresets:zod.z.record(zod.z.string(),cA).nullish()}).passthrough();var pA=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),zf=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:E.nullish(),Inventory:K.nullish(),Results:zod.z.array(E).nullish(),TriggeredPity:zod.z.array(pA).nullish()}),hA=zod.z.object({RewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),dA=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:Q.nullish()}).passthrough(),mA=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:pe.nullish(),RewardSlots:zod.z.array(Fn).nullish(),PityRules:zod.z.array(Vn).nullish(),Presets:hA.nullish(),RewardMultiplier:qi.nullish(),SupplyLimits:zod.z.array(dA).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),fA=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Wl=zod.z.object({Definitions:zod.z.record(zod.z.string(),mA).nullish(),RewardPools:ro.nullish(),Settings:fA.nullish()}).passthrough(),Mf=zod.z.object({LootboxDefinitions:Wl.nullish()}),oo={GetDefinitions:"GetDefinitions",Open:"Open"};var ao=class extends N{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(oo.GetDefinitions,e,Mf)}open(e){return this.send(oo.Open,e,we(zf))}};var gA=zod.z.object({}).passthrough().transform(r=>r),yA=zod.z.object({}).passthrough().transform(r=>r),RA=zod.z.object({}).passthrough().transform(r=>r),CA=zod.z.object({}).passthrough().transform(r=>r),SA=zod.z.object({}).passthrough().transform(r=>r),bA=zod.z.object({}).passthrough().transform(r=>r),Of=zod.z.object({ServerTimeUtc:u,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:gA,Resources:E.nullish(),Inventory:K.nullish()}),Ef=zod.z.object({ServerTimeUtc:u,AccrualID:zod.z.string(),AccruedSeconds:Q.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:yA,Resources:E.nullish(),Inventory:K.nullish()}),qf=zod.z.object({ServerTimeUtc:u,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:RA,Resources:E.nullish(),Inventory:K.nullish()}),Uf=zod.z.object({ServerTimeUtc:u,ClaimID:zod.z.string(),ClaimState:CA,Resources:E.nullish(),Inventory:K.nullish()}),xA={None:"None",Ad:"Ad",Vip:"Vip"},Lf=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:SA,Resources:E.nullish(),Inventory:K.nullish()}),Bf=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()}),DA=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),IA=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(),Ci=zod.z.object({Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),Hl=zod.z.object({Availability:J.nullish()}).passthrough(),PA=zod.z.object({Availability:zod.z.record(zod.z.string(),Ci).nullish()}).passthrough(),vA=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(IA).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:Ci.nullish(),Presets:Hl.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),AA=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),TA=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(AA).nullish()}).passthrough(),wA=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Ci.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),kA=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:TA.nullish(),Rewards:$.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:wA.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),zA=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:$.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),MA=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(zA).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Ci.nullish(),Presets:Hl.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),OA=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(),EA=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(OA).nullish(),Availability:Ci.nullish(),Presets:Hl.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),qA=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(),Kl=zod.z.object({TierRewards:DA.nullish(),MilestoneRewardMultiplier:qi.nullish(),DailyCalendars:zod.z.record(zod.z.string(),vA).nullish(),IdleAccruals:zod.z.record(zod.z.string(),kA).nullish(),Comebacks:zod.z.record(zod.z.string(),MA).nullish(),Claims:zod.z.record(zod.z.string(),EA).nullish(),Windows:zod.z.record(zod.z.string(),qA).nullish(),Presets:PA.nullish()}).passthrough(),Gf=zod.z.object({RewardDefinitions:Kl.nullish()}),Nf=zod.z.object({Rewards:bA.nullish()}),Et={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var lo=class extends N{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Et.GetRewardDefinitions,e,Gf)}getUserRewardsState(e){return this.send(Et.GetUserRewardsState,e,Nf)}getMilestoneRewardMultiplier(e){return this.send(Et.GetMilestoneRewardMultiplier,e,Bf)}claimDailyReward(e){return this.send(Et.ClaimDailyReward,e,Of)}collectIdleAccrual(e){return this.send(Et.CollectIdleAccrual,e,Ef)}claimComebackReward(e){return this.send(Et.ClaimComebackReward,e,qf)}claimReward(e){return this.send(Et.ClaimReward,e,Uf)}claimRewardWindow(e){return this.send(Et.ClaimRewardWindow,e,Lf)}};var uo=class extends N{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(ft.GetTutorialDefinitions,e,sc)}getUserTutorialState(e){return this.send(ft.GetUserTutorialState,e,Bi)}startFlow(e){return this.send(ft.StartFlow,e,Qt)}reportStepShown(e){return this.send(ft.ReportStepShown,e,Qt)}completeStep(e){return this.send(ft.CompleteStep,e,Qt)}completeStepsBatch(e){return this.send(ft.CompleteStepsBatch,e,ac)}skipStep(e){return this.send(ft.SkipStep,e,Qt)}skipFlow(e){return this.send(ft.SkipFlow,e,Qt)}claimFlowReward(e){return this.send(ft.ClaimFlowReward,e,oc)}resetFlow(e){return this.send(ft.ResetFlow,e,Qt)}};var UA={Open:"Open",Application:"Application"},LA=zod.z.enum(["Open","Application"]).catch("Open"),BA={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},_f=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),GA={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Ql=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),NA={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var Cn={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},_A=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(),Ff=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:LA.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:_f.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(_A).nullish()}).passthrough(),FA=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(),VA=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:Ql.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(),FA).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),jA=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:Ql.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),Vf=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(VA).nullish(),Payouts:zod.z.array(jA).nullish()}).passthrough(),jf=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:Ql.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),WA=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),HA=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(WA).nullish()}).passthrough(),KA=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(),Wf=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:_f.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(KA).nullish()}).passthrough(),QA=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),$A=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(QA).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(),Hf=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:HA.nullish(),SolanaSignature:$A.nullish(),StateDelta:Nn.nullish()}).passthrough();var co=class extends N{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(Cn.GetCommunityMarketingState,e,Ff)}getEarnings(e){return this.send(Cn.GetEarnings,e,Vf)}claim(e){return this.send(Cn.Claim,e,jf)}checkJoinEligibility(e){return this.send(Cn.CheckJoinEligibility,e,Wf)}withdrawCryptoReward(e){return this.send(Cn.WithdrawCryptoReward,e,Hf)}};var po=class extends N{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(tt.GetChatDefinitions,e,Nc)}getChannels(e){return this.send(tt.GetChannels,e,xs)}poll(e){return this.send(tt.Poll,e,_c)}getHistory(e){return this.send(tt.GetHistory,e,Fc)}getConversations(e){return this.send(tt.GetConversations,e,Wc)}sendMessage(e){return this.send(tt.SendMessage,e,Vc)}openDirectChannel(e){return this.send(tt.OpenDirectChannel,e,jc)}markRead(e){return this.send(tt.MarkRead,e,Ln)}joinChannel(e){return this.send(tt.JoinChannel,e,Ln)}leaveChannel(e){return this.send(tt.LeaveChannel,e,Ln)}reportMessage(e){return this.send(tt.ReportMessage,e,Hc)}ignoreUser(e){return this.send(tt.IgnoreUser,e,Ln)}unignoreUser(e){return this.send(tt.UnignoreUser,e,Ln)}};var ho=class extends N{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(Bn.GetPushConfig,e,$c)}subscribePush(e){return this.send(Bn.SubscribePush,e,wa)}unsubscribePush(e){return this.send(Bn.UnsubscribePush,e,Ke)}getPushSubscriptions(e){return this.send(Bn.GetPushSubscriptions,e,Jc)}};var mo=class extends N{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(Kr.GetLocalizationManifest,e,rf)}getLocalizationTable(e){return this.send(Kr.GetLocalizationTable,e,of)}};var fo=class extends N{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(Dt.GetQuestDefinitions,e,Li)}getUserQuestState(e){return this.send(Dt.GetUserQuestState,e,Hu)}refreshQuestCycles(e){return this.send(Dt.RefreshQuestCycles,e,Ke)}claimQuestReward(e){return this.send(Dt.ClaimQuestReward,e,ma)}claimQuestRewardsBatch(e){return this.send(Dt.ClaimQuestRewardsBatch,e,$u)}claimMilestoneReward(e){return this.send(Dt.ClaimMilestoneReward,e,fa)}claimMilestoneRewardsBatch(e){return this.send(Dt.ClaimMilestoneRewardsBatch,e,Ju)}claimGroupCompletionReward(e){return this.send(Dt.ClaimGroupCompletionReward,e,Ku)}addQuestProgress(e){return this.send(Dt.AddQuestProgress,e,Qu)}};var go=class extends N{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(yt.GetActiveEvents,e,ws)}getDefinitions(e){return this.send(yt.GetDefinitions,e,Ts)}getUserLteState(e){return this.send(yt.GetUserLteState,e,ep)}grantTokens(e){return this.send(yt.GrantTokens,e,E)}spendTokens(e){return this.send(yt.SpendTokens,e,Ma)}claimMilestone(e){return this.send(yt.ClaimMilestone,e,Oa)}claimMilestonesBatch(e){return this.send(yt.ClaimMilestonesBatch,e,Ea)}claimAllMilestones(e){return this.send(yt.ClaimAllMilestones,e,Ea)}spendTokensBatch(e){return this.send(yt.SpendTokensBatch,e,tp)}grantTokensBatch(e){return this.send(yt.GrantTokensBatch,e,np)}};var yo=class extends N{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ze.GetDefinitions,e,Us)}getLeaderboard(e){return this.send(Ze.GetLeaderboard,e,ri)}getMyProgress(e){return this.send(Ze.GetMyProgress,e,zs)}submitScore(e){return this.send(Ze.SubmitScore,e,Ms)}submitScoreFromSource(e){return this.send(Ze.SubmitScoreFromSource,e,Ms)}claimCycleReward(e){return this.send(Ze.ClaimCycleReward,e,Os)}claimMilestone(e){return this.send(Ze.ClaimMilestone,e,Es)}getFriendsLeaderboard(e){return this.send(Ze.GetFriendsLeaderboard,e,ri)}getLeaderboardsBatch(e){return this.send(Ze.GetLeaderboardsBatch,e,rp)}getProgressBatch(e){return this.send(Ze.GetProgressBatch,e,qs)}claimCycleRewardsBatch(e){return this.send(Ze.ClaimCycleRewardsBatch,e,op)}claimMilestonesBatch(e){return this.send(Ze.ClaimMilestonesBatch,e,ap)}submitScoresBatch(e){return this.send(Ze.SubmitScoresBatch,e,lp)}claimAllRewardsBatch(e){return this.send(Ze.ClaimAllRewardsBatch,e,up)}getOverviewBatch(e){return this.send(Ze.GetOverviewBatch,e,cp)}};var Ro=class extends N{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Zt.GetDefinitions,e,Gs)}getActiveSeason(e){return this.send(Zt.GetActiveSeason,e,Bs)}getUserState(e){return this.send(Zt.GetUserState,e,qa)}grantStatusTokens(e){return this.send(Zt.GrantStatusTokens,e,mp)}claimTierReward(e){return this.send(Zt.ClaimTierReward,e,Ua)}claimTierRewardsBatch(e){return this.send(Zt.ClaimTierRewardsBatch,e,fp)}};var Co=class extends N{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(yn.GetDefinitions,e,bf)}getUserState(e){return this.send(yn.GetUserState,e,xf)}activateTrial(e){return this.send(yn.ActivateTrial,e,io)}purchaseItemOrCurrency(e){return this.send(yn.PurchaseWithResources,e,we(io))}purchaseRealMoney(e){return this.send(yn.PurchaseRealMoney,e,io)}};var So=class extends N{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send($e.GetCharacterDefinitions,e,Vs)}getUserCharacters(e){return this.send($e.GetUserCharacters,e,bp)}unlockCharacter(e){return this.send($e.UnlockCharacter,e,we(Ga))}upgradeStatLevel(e){return this.send($e.UpgradeStatLevel,e,we(La))}upgradeCharacterLevel(e){return this.send($e.UpgradeCharacterLevel,e,we(Ba))}equipItems(e){return this.send($e.EquipItems,e,xp)}unequipItems(e){return this.send($e.UnequipItems,e,Dp)}unequipAllCharacters(e){return this.send($e.UnequipAllCharacters,e,Ip)}unlockCharactersBatch(e){return this.send($e.UnlockCharactersBatch,e,kp)}upgradeCharacterLevelsBatch(e){return this.send($e.UpgradeCharacterLevelsBatch,e,zp)}upgradeStatLevelsBatch(e){return this.send($e.UpgradeStatLevelsBatch,e,Mp)}unlockSkin(e){return this.send($e.UnlockSkin,e,we(Pp))}equipSkin(e){return this.send($e.EquipSkin,e,vp)}unequipSkin(e){return this.send($e.UnequipSkin,e,Ap)}getCharacterSkins(e){return this.send($e.GetCharacterSkins,e,Tp)}selectCharacter(e){return this.send($e.SelectCharacter,e,wp)}};var bo=class extends N{constructor(e){super(e,"Match");}createMatch(e){return this.send(Mt.CreateMatch,e,Ph)}updateMatch(e){return this.send(Mt.UpdateMatch,e,vh)}cancelMatch(e){return this.send(Mt.CancelMatch,e,Ah)}instantBattle(e){return this.send(Mt.InstantBattle,e,Th)}saveStrategy(e){return this.send(Mt.SaveStrategy,e,Ke)}getMyMatches(e){return this.send(Mt.GetMyMatches,e,Xa)}getAvailableMatches(e){return this.send(Mt.GetAvailableMatches,e,Xa)}getDefinitions(e){return this.send(Mt.GetDefinitions,e,Mh)}};var JA={Arena:"Arena"},Qf=zod.z.string(),jn={GetState:"GetState",RefreshOpponents:"RefreshOpponents",Attempt:"Attempt",ClaimMilestone:"ClaimMilestone"},ZA=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(),YA=zod.z.object({RuleID:zod.z.string().nullish(),Tiers:zod.z.array(ZA).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(),XA=zod.z.object({ChallengeID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),Mode:Qf.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:Tt.nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),ClaimMode:zod.z.string().nullish(),Arena:YA.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),eT=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(XA).nullish(),Ticket:Tt.nullish(),Gate:ee.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$f=zod.z.object({Chains:zod.z.record(zod.z.string(),eT).nullish()}).passthrough(),Jf=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(),tT=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(),nT=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(),iT=zod.z.object({Opponents:zod.z.array(Jf).nullish(),Revenges:zod.z.array(tT).nullish(),RevengeCost:zod.z.number().nullish(),RevengePoints:zod.z.number().nullish(),RefreshAvailableAtUtc:u.nullish()}).passthrough(),Kf=zod.z.object({ChallengeID:zod.z.string().nullish(),Mode:Qf.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:iT.nullish()}).passthrough(),sT=zod.z.object({ChainID:zod.z.string().nullish(),Tickets:zod.z.number().nullish(),Active:Kf.nullish(),Ended:zod.z.array(Kf).nullish()}).passthrough(),rT=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(),$l=zod.z.object({Chains:zod.z.array(sT).nullish(),ServerTimeUtc:u.nullish(),Burns:zod.z.array(rT).nullish(),Rewards:E.nullish(),Inventory:K.nullish()}).passthrough(),Zf=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),Attempt:nT.nullish(),IsReplay:zod.z.boolean().nullish(),Battle:li.nullish(),Opponent:Jf.nullish(),Tickets:zod.z.number().nullish(),PointsEarned:zod.z.number().nullish(),Rewards:E.nullish(),Inventory:K.nullish()}).passthrough(),Yf=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Rewards:E.nullish(),Inventory:K.nullish()}).passthrough();var xo=class extends N{constructor(e){super(e,"Challenge");}getState(e){return this.send(jn.GetState,e,$l)}refreshOpponents(e){return this.send(jn.RefreshOpponents,e,$l)}attempt(e){return this.send(jn.Attempt,e,Zf)}claimMilestone(e){return this.send(jn.ClaimMilestone,e,Yf)}};var oT={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Xf=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),aT={None:"None",Min:"Min",Average:"Average",Max:"Max"},lT=zod.z.enum(["None","Min","Average","Max"]).catch("None"),uT={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},cT=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),pT={Clamp:"Clamp",Reject:"Reject"},hT=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),dT=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),mT=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:At.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(dT).nullish()}),eg=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,Type:Xf.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:E.nullish(),Inventory:K.nullish(),Results:zod.z.array(mT).nullish()}),fT=zod.z.object({CraftID:zod.z.string().nullish(),Type:Xf.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:pe.nullish(),OutputLevelMode:lT.nullish(),InputSelection:cT.nullish(),OutputLevelOverflow:hT.nullish()}).passthrough(),Jl=zod.z.object({Definitions:zod.z.record(zod.z.string(),fT).nullish()}).passthrough(),tg=zod.z.object({ServerTimeUtc:u.nullish(),CraftDefinitions:Jl.nullish()}),Do={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Io=class extends N{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Do.GetDefinitions,e,tg)}craft(e){return this.send(Do.Craft,e,we(eg))}};var gT=2e5,Po=class extends N{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,we(Qs),{timeoutMs:gT,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Qs,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(je.GetDefinitions,e,Vp)}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,Fp,{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,Np)}getGeneration(e){return this.readGeneration(je.GetGeneration,e)}};var yT={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},RT=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),ng=zod.z.object({}).passthrough().transform(r=>r),Wn=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()}),ig=zod.z.object({GrantedCollectibles:zod.z.array(Wn).nullish(),DuplicateCollectibles:zod.z.array(Wn).nullish(),CollectionCurrencyEarned:Q.nullish()}),sg=zod.z.object({CreditsConfirmation:ye.nullish(),OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(ig).nullish(),GrantedCollectibles:zod.z.array(Wn).nullish(),DuplicateCollectibles:zod.z.array(Wn).nullish(),CollectionCurrencyEarned:Q.nullish(),NewCollectionCurrencyBalance:Q.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:E.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),rg=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(ig).nullish(),GrantedCollectibles:zod.z.array(Wn).nullish(),DuplicateCollectibles:zod.z.array(Wn).nullish(),CollectionCurrencyEarned:Q.nullish(),NewCollectionCurrencyBalance:Q.nullish(),Resources:E.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),og=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:E.nullish(),Inventory:K.nullish()}),Zl=zod.z.object({SetID:zod.z.string(),Resources:E.nullish(),Inventory:K.nullish()}),ag=zod.z.array(Oe(Zl)),lg=zod.z.object({Resources:E.nullish(),Inventory:K.nullish()}),CT=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:RT.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(),ug=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:u.nullish(),Resources:E.nullish()}),cg=zod.z.object({OfferID:zod.z.string(),Resources:E.nullish()}),pg=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()}),hg=zod.z.object({OfferID:zod.z.string(),Resources:E.nullish()}),Yl=zod.z.object({Offers:zod.z.array(CT).nullish()}),ST=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(),bT=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(ST).nullish(),SetCompletionReward:$.nullish()}).passthrough(),xT=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(bT).nullish(),GrandPrize:$.nullish()}).passthrough(),dg=zod.z.object({BonusRewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),DT=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:pe.nullish(),BonusRewardSlots:zod.z.array(Fn).nullish(),PityRules:zod.z.array(Vn).nullish(),Presets:dg.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(),IT=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),PT=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(Fn).nullish(),PityRules:zod.z.array(Vn).nullish(),Presets:dg.nullish(),Tier:zod.z.number().nullish()}).passthrough(),vT=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(),AT=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),vo=zod.z.object({Collections:zod.z.record(zod.z.string(),xT).nullish(),PackTypes:zod.z.record(zod.z.string(),DT).nullish(),CollectionChests:zod.z.array(PT).nullish(),DuplicateConversions:zod.z.array(IT).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(vT).nullish(),RewardPools:ro.nullish(),Settings:AT.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 Ao=class extends N{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Xe.GetDefinitions,e,vo)}getUserState(e){return this.send(Xe.GetUserState,e,ng)}openPack(e){return this.send(Xe.OpenPack,e,we(sg))}openCollectionChest(e){return this.send(Xe.OpenCollectionChest,e,rg)}useCollectibleJoker(e){return this.send(Xe.UseCollectibleJoker,e,og)}claimSetReward(e){return this.send(Xe.ClaimSetReward,e,Zl)}claimSetRewardsBatch(e){return this.send(Xe.ClaimSetRewardsBatch,e,ag)}claimGrandPrize(e){return this.send(Xe.ClaimGrandPrize,e,lg)}sendTradeOffer(e){return this.send(Xe.SendTradeOffer,e,ug)}cancelTradeOffer(e){return this.send(Xe.CancelTradeOffer,e,cg)}acceptTradeOffer(e){return this.send(Xe.AcceptTradeOffer,e,pg)}declineTradeOffer(e){return this.send(Xe.DeclineTradeOffer,e,hg)}getMyTradeOffers(e){return this.send(Xe.GetMyTradeOffers,e,Yl)}getIncomingTradeOffers(e){return this.send(Xe.GetIncomingTradeOffers,e,Yl)}};var To=class extends N{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(Pt.GetDefinitions,e,Ys)}getActiveEvent(e){return this.send(Pt.GetActiveEvent,e,Hp)}getUserState(e){return this.send(Pt.GetUserState,e,Zs)}getGroupState(e){return this.send(Pt.GetGroupState,e,Wa)}joinOrCreateGroup(e){return this.send(Pt.JoinOrCreateGroup,e,Wa)}spin(e){return this.send(Pt.Spin,e,we(Qp))}claimObjectReward(e){return this.send(Pt.ClaimObjectReward,e,Ha)}claimGrandPrize(e){return this.send(Pt.ClaimGrandPrize,e,Ha)}leaveGroup(e){return this.send(Pt.LeaveGroup,e,$p)}};var wo=class extends N{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(zt.GetDefinition,e,oh)}getUserState(e){return this.send(zt.GetUserState,e,ah)}getActiveDeals(e){return this.send(zt.GetActiveDeals,e,tr)}dismissDeal(e){return this.send(zt.DismissDeal,e,uh)}executeNode(e){return this.send(zt.ExecuteNode,e,we(lh))}recordShow(e){return this.send(zt.RecordShow,e,ch)}claimMilestone(e){return this.send(zt.ClaimMilestone,e,ph)}claimMilestonesBatch(e){return this.send(zt.ClaimMilestonesBatch,e,hh)}};var TT=zod.z.object({}).passthrough().transform(r=>r),wT=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(),Xl=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:$.nullish(),InviteRewards:zod.z.record(zod.z.string(),Ve).nullish(),SpendRewards:zod.z.array(wT).nullish(),Qualification:zod.z.object({}).passthrough().transform(r=>r).nullish()}).passthrough(),eu=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(),mg=zod.z.object({ReferralDefinitions:Xl.nullish()}).passthrough(),fg=zod.z.object({Referral:TT.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:eu.nullish()}).passthrough(),gg=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:eu.nullish()}).passthrough(),yg=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:E.nullish(),Inventory:K.nullish(),QualificationPending:zod.z.boolean().nullish(),Qualification:eu.nullish()}).passthrough(),tu=zod.z.object({RewardID:zod.z.string().nullish(),Resources:E.nullish(),Inventory:K.nullish()}).passthrough(),Rg=wt(tu),on={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var ko=class extends N{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(on.GetDefinitions,e,mg)}getUserState(e){return this.send(on.GetUserState,e,fg)}activateReferralCode(e){return this.send(on.ActivateReferralCode,e,yg)}claimInviteReward(e){return this.send(on.ClaimInviteReward,e,tu)}claimInviteRewardsBatch(e){return this.send(on.ClaimInviteRewardsBatch,e,Rg)}checkQualification(e){return this.send(on.CheckQualification,e,gg)}};var zo=class extends N{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(ct.GetDefinitions,e,yh)}getMessages(e){return this.send(ct.GetMessages,e,Rh)}getUnreadCount(e){return this.send(ct.GetUnreadCount,e,sr)}readMessages(e){return this.send(ct.ReadMessages,e,$a)}claimReward(e){return this.send(ct.ClaimReward,e,rr)}claimRewardsBatch(e){return this.send(ct.ClaimRewardsBatch,e,rr)}claimAll(e){return this.send(ct.ClaimAll,e,rr)}deleteMessages(e){return this.send(ct.DeleteMessages,e,$a)}sendGift(e){return this.send(ct.SendGift,e,Ch)}sendTransfer(e){return this.send(ct.SendTransfer,e,Sh)}getGiftStatus(e){return this.send(ct.GetGiftStatus,e,bh)}};var Mo=class extends N{constructor(e){super(e,"Clan");}getDefinitions(e){return this.send(Le.GetDefinitions,e,Kh)}getMyClans(e){return this.send(Le.GetMyClans,e,Eh)}searchClans(e){return this.send(Le.SearchClans,e,sl)}getRecommendedClans(e){return this.send(Le.GetRecommendedClans,e,sl)}getClan(e){return this.send(Le.GetClan,e,qh)}getClanMembers(e){return this.send(Le.GetClanMembers,e,Lh)}getRankings(e){return this.send(Le.GetRankings,e,Bh)}getApplications(e){return this.send(Le.GetApplications,e,rl)}getMyInvites(e){return this.send(Le.GetMyInvites,e,rl)}getClanLog(e){return this.send(Le.GetClanLog,e,Gh)}getRequests(e){return this.send(Le.GetRequests,e,_h)}getGifts(e){return this.send(Le.GetGifts,e,Fh)}getRewards(e){return this.send(Le.GetRewards,e,Vh)}getTreasury(e){return this.send(Le.GetTreasury,e,Qh)}getProjects(e){return this.send(Le.GetProjects,e,$h)}getActivities(e){return this.send(Le.GetActivities,e,Jh)}getClanQuests(e){return this.send(Le.GetClanQuests,e,Zh)}getCompetitions(e){return this.send(Le.GetCompetitions,e,Yh)}getBracket(e){return this.send(Le.GetBracket,e,Xh)}getDiplomacy(e){return this.send(Le.GetDiplomacy,e,ed)}getRevenges(e){return this.send(Le.GetRevenges,e,td)}getLeague(e){return this.send(Le.GetLeague,e,nd)}mutate(e,t){return this.send(e,t,Hh)}};var Oo=class extends N{constructor(e){super(e,"Avatar");}getDefinitions(e){return this.send(Gn.GetDefinitions,e,hr)}getAvatars(e){return this.send(Gn.GetAvatars,e,sd)}getShop(e){return this.send(Gn.GetShop,e,rd)}buyItem(e){return this.send(Gn.BuyItem,e,od)}};var Eo=class extends N{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(mr.RequestAdPermit,e,ad)}completeView(e){return this.send(mr.CompleteView,e,ld)}};var qo=class extends N{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Ie.GetFriendsList,e,ci)}getIncomingRequests(e){return this.send(Ie.GetIncomingRequests,e,ci)}getOutgoingRequests(e){return this.send(Ie.GetOutgoingRequests,e,ci)}getRecommendedFriends(e){return this.send(Ie.GetRecommendedFriends,e,ci)}sendFriendRequest(e){return this.send(Ie.SendFriendRequest,e,pi)}acceptFriendRequest(e){return this.send(Ie.AcceptFriendRequest,e,pi)}declineFriendRequest(e){return this.send(Ie.DeclineFriendRequest,e,pi)}removeFriend(e){return this.send(Ie.RemoveFriend,e,pi)}getPlayerProfile(e){return this.send(Ie.GetPlayerProfile,e,md)}getInbox(e){return this.send(Ie.GetInbox,e,fd)}markInboxSeen(e){return this.send(Ie.MarkInboxSeen,e,hi)}getInboxUnread(e){return this.send(Ie.GetInboxUnread,e,hi)}follow(e){return this.send(Ie.Follow,e,tn)}unfollow(e){return this.send(Ie.Unfollow,e,tn)}getFollowers(e){return this.send(Ie.GetFollowers,e,Rr)}getFollowing(e){return this.send(Ie.GetFollowing,e,Rr)}block(e){return this.send(Ie.Block,e,tn)}unblock(e){return this.send(Ie.Unblock,e,tn)}getBlocked(e){return this.send(Ie.GetBlocked,e,Rr)}react(e){return this.send(Ie.React,e,tn)}unreact(e){return this.send(Ie.Unreact,e,tn)}getMyReactions(e){return this.send(Ie.GetMyReactions,e,yd)}getEntityStates(e){return this.send(Ie.GetEntityStates,e,gd)}addComment(e){return this.send(Ie.AddComment,e,Cr)}editComment(e){return this.send(Ie.EditComment,e,Cr)}deleteComment(e){return this.send(Ie.DeleteComment,e,Cd)}getComments(e){return this.send(Ie.GetComments,e,Rd)}report(e){return this.send(Ie.Report,e,Sd)}};var kT={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Sn=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),zT=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:pe.nullish(),Effect:Sn.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(),Uo=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),nu=zod.z.object({Availability:J.nullish(),Effects:J.nullish()}).passthrough(),MT=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(Sn).nullish(),Availability:Uo.nullish(),Presets:nu.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),OT=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(Sn).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ET=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(OT).nullish(),Availability:Uo.nullish(),Presets:nu.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),qT=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(Sn).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:Uo.nullish(),Presets:nu.nullish()}).passthrough(),UT=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),LT=zod.z.object({Effects:zod.z.array(Sn).nullish()}).passthrough(),BT=zod.z.object({Availability:zod.z.record(zod.z.string(),Uo).nullish(),Effects:zod.z.record(zod.z.string(),LT).nullish()}).passthrough(),GT=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),UT).nullish()}).passthrough(),Lo=zod.z.object({Definitions:zod.z.record(zod.z.string(),zT).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),MT).nullish(),BoostChains:zod.z.record(zod.z.string(),ET).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),qT).nullish(),Settings:GT.nullish(),Presets:BT.nullish()}).passthrough(),Cg=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:Sn.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 Sg=zod.z.object({ServerTimeUtc:u.nullish(),Active:zod.z.record(zod.z.string(),Cg).nullish()}),bg=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:Cg.nullish(),Resources:E.nullish()}),NT={Scheduled:"Scheduled",Chain:"Chain"},_T=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(Sn).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),xg=zod.z.object({ServerTimeUtc:u.nullish(),Windows:zod.z.array(_T).nullish()}),bn={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Bo=class extends N{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(bn.GetDefinitions,e,Lo)}getActive(e){return this.send(bn.GetActive,e,Sg)}getActiveWindows(e){return this.send(bn.GetActiveWindows,e,xg)}activate(e){return this.send(bn.Activate,e,we(bg))}cleanupExpired(e){return this.send(bn.CleanupExpired,e,Ke)}};var Go=class extends N{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(vt.GetUserCustomDataDefinitions,e,yr)}getMyUserCustomData(e){return this.send(vt.GetMyUserCustomData,e,ud)}getPublicUserCustomDataOf(e){return this.send(vt.GetPublicUserCustomDataOf,e,ul)}setPrivateData(e){return this.send(vt.SetPrivateData,e,cl)}setPublicData(e){return this.send(vt.SetPublicData,e,cl)}deleteKey(e){return this.send(vt.DeleteKey,e,Ke)}batchSet(e){return this.send(vt.BatchSet,e,cd)}batchDelete(e){return this.send(vt.BatchDelete,e,pd)}batchGetPublicUserCustomDataOf(e){return this.send(vt.BatchGetPublicUserCustomDataOf,e,hd)}};var FT={Static:"Static",Runtime:"Runtime"},VT={Public:"Public",Private:"Private"},jT=zod.z.enum(["Client","Server","System"]).catch("Client"),WT=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),HT=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:jT.nullish(),ExpiresAt:u.nullish()}).passthrough(),Dg=zod.z.record(zod.z.string(),HT),iu=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:Dg.nullish(),Runtime:Dg.nullish(),NotModified:zod.z.boolean().nullish()}),KT=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:WT.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),No=zod.z.object({Keys:zod.z.record(zod.z.string(),KT).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(),Si={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var _o=class extends N{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Si.GetTitleCustomDataDefinitions,e,No)}getPublicTitleData(e){return this.send(Si.GetPublicTitleData,e,iu)}getPublicTitleDataKeys(e){return this.send(Si.GetPublicTitleDataKeys,e,iu)}};var Ig=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 QT={Mesh:"Mesh",Host:"Host"},su=zod.z.enum(["Mesh","Host"]).catch("Mesh"),$T={ServerRelay:"ServerRelay",P2P:"P2P"},ru=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),JT={Public:"Public",Private:"Private"},ZT=zod.z.enum(["Public","Private"]).catch("Public"),YT={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},XT=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Pg=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),ew=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),vg=zod.z.object({SystemState:ew.nullish(),DefaultTopology:su.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:ru.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(Pg).nullish()}).passthrough(),tw=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(),nw=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:su.nullish(),ChatMode:ru.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(),iw=zod.z.object({Seq:zod.z.number().nullish(),Type:XT.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(),bi=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:su.nullish(),ChatMode:ru.nullish(),Visibility:ZT.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(tw).nullish(),IceServers:zod.z.array(Pg).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ag=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),Tg=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),ou=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),wg=zod.z.object({Rooms:zod.z.array(nw).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),kg=zod.z.object({Envelopes:zod.z.array(iw).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Fo=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 au=zod.z.object({TitleCustomData:No.nullish(),Character:Vs.nullish(),Item:Yr.nullish(),Currency:kr.nullish(),Store:us.nullish(),Lootbox:Wl.nullish(),Quest:Li.nullish(),TimedEvent:Ts.nullish(),Leaderboard:Us.nullish(),Season:Gs.nullish(),Reward:Kl.nullish(),Collection:vo.nullish(),Craft:Jl.nullish(),DealOffer:Ka.nullish(),Premium:Fl.nullish(),TimedBoost:Lo.nullish(),CoopEvent:Ys.nullish(),GameLoop:vr.nullish(),Match:el.nullish(),Challenge:$f.nullish(),Experiment:Xm.nullish(),Blockchain:Rl.nullish(),Marketplace:Al.nullish(),Multiplayer:vg.nullish(),UserCustomData:yr.nullish(),Referral:Xl.nullish(),Localization:nf.nullish(),Analytics:Fm.nullish(),Social:bd.nullish(),PlatformBridge:xd.nullish(),GameSpec:zod.z.string().nullish(),Look:Ig.nullish(),Avatar:hr.nullish()}).passthrough();var xn={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Vo=class extends N{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(xn.GetTitlePublicConfiguration,e,au)}getTitlePublicConfigurationExcept(e){return this.send(xn.GetTitlePublicConfigurationExcept,e,au)}getCurrencyDefinitions(e){return this.send(xn.GetCurrencyDefinitions,e,kr)}getItemDefinitions(e){return this.send(xn.GetItemDefinitions,e,Yr)}getServerTime(e){return this.send(xn.GetServerTime,e,Ke)}};var jo=class extends N{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(We.GetGameLoops,e,vr)}getBoardDefinition(e,t=false){return this.send(We.GetBoardDefinition,e,Pr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(We.GetBoardDefinitionForLevel,e,Pr,{silent:t})}getUserBoardState(e){return this.send(We.GetUserBoardState,e,vd)}boardLoopRoll(e){return this.send(We.BoardLoopRoll,e,Od)}boardLoopAttack(e){return this.send(We.BoardLoopAttack,e,Ud)}boardLoopRaid(e){return this.send(We.BoardLoopRaid,e,ml)}boardLoopRaidFast(e){return this.send(We.BoardLoopRaidFast,e,ml)}boardLoopBuild(e){return this.send(We.BoardLoopBuild,e,Ld)}boardSpecialChoose(e){return this.send(We.BoardSpecialChoose,e,we(Bd))}boardSpecialApplyMultiplier(e){return this.send(We.BoardSpecialApplyMultiplier,e,Gd)}boardRewardBoostApply(e){return this.send(We.BoardRewardBoostApply,e,qd)}boardSpecialClaim(e){return this.send(We.BoardSpecialClaim,e,Nd)}getCommunityChestState(e){return this.send(We.GetCommunityChestState,e,Vd)}joinOrCreateCommunityChest(e){return this.send(We.JoinOrCreateCommunityChest,e,jd)}claimCommunityChestMilestone(e){return this.send(We.ClaimCommunityChestMilestone,e,fl)}claimCommunityChestGrandPrize(e){return this.send(We.ClaimCommunityChestGrandPrize,e,fl)}leaveCommunityChest(e){return this.send(We.LeaveCommunityChest,e,Wd)}};var sw={Live:"Live",Latest:"Latest",Specific:"Specific"},rw={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},ow=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),aw={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"},lw=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),uw=zod.z.object({Level:ow,Message:zod.z.string().nullish(),Data:Yt.nullish()}),cw=zod.z.object({Error:lw,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Mg=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:Yt.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(uw).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:cw.nullish()}),lu={Execute:"Execute"};var Wo=class extends N{constructor(e){super(e,"CloudCode");}execute(e){return this.send(lu.Execute,e,Mg)}};var Ho=class extends N{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(it.GetDefinitions,e,am)}getUserState(e){return this.send(it.GetUserState,e,lm)}depositToken(e){return this.send(it.DepositToken,e,um)}depositNFT(e){return this.send(it.DepositNFT,e,cm)}requestTokenWithdrawal(e){return this.send(it.RequestTokenWithdrawal,e,pm)}requestNFTWithdrawal(e){return this.send(it.RequestNFTWithdrawal,e,hm)}getTransactionHistory(e){return this.send(it.GetTransactionHistory,e,dm)}retryWithdrawal(e){return this.send(it.RetryWithdrawal,e,mm)}confirmWithdrawal(e){return this.send(it.ConfirmWithdrawal,e,fm)}donateToDeveloper(e){return this.send(it.DonateToDeveloper,e,xl)}donateToUsersPool(e){return this.send(it.DonateToUsersPool,e,xl)}getPlayAccess(e){return this.send(it.GetPlayAccess,e,rm)}confirmPlayAccess(e){return this.send(it.ConfirmPlayAccess,e,nn)}};var Ko=class extends N{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Be.GetDefinitions,e,Rm)}getGroupedOffers(e){return this.send(Be.GetGroupedOffers,e,Cm)}getOffersByItem(e){return this.send(Be.GetOffersByItem,e,Tl)}getOffer(e){return this.send(Be.GetOffer,e,Sm)}getBuyOrders(e){return this.send(Be.GetBuyOrders,e,Tl)}getMyState(e){return this.send(Be.GetMyState,e,Ur)}getHistory(e){return this.send(Be.GetHistory,e,xm)}createListing(e){return this.send(Be.CreateListing,e,gi)}cancelListing(e){return this.send(Be.CancelListing,e,Rt)}buy(e){return this.send(Be.Buy,e,Rt)}marketBuy(e){return this.send(Be.MarketBuy,e,Rt)}marketSell(e){return this.send(Be.MarketSell,e,Rt)}createAuction(e){return this.send(Be.CreateAuction,e,gi)}placeBid(e){return this.send(Be.PlaceBid,e,bm)}claimAuction(e){return this.send(Be.ClaimAuction,e,Rt)}createBuyOrder(e){return this.send(Be.CreateBuyOrder,e,gi)}cancelBuyOrder(e){return this.send(Be.CancelBuyOrder,e,Rt)}fillBuyOrder(e){return this.send(Be.FillBuyOrder,e,Rt)}createDirectTrade(e){return this.send(Be.CreateDirectTrade,e,gi)}respondDirectTrade(e){return this.send(Be.RespondDirectTrade,e,Rt)}cancelDirectTrade(e){return this.send(Be.CancelDirectTrade,e,Rt)}claimBack(e){return this.send(Be.ClaimBack,e,Rt)}};var Qo=class extends N{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(st.CreateRoom,e,bi)}joinRoom(e){return this.send(st.JoinRoom,e,bi)}leaveRoom(e,t=false){return this.send(st.LeaveRoom,e,ou,{keepalive:t})}listRooms(e){return this.send(st.ListRooms,e,wg)}getRoom(e){return this.send(st.GetRoom,e,bi)}closeRoom(e){return this.send(st.CloseRoom,e,ou)}poll(e){return this.send(st.Poll,e,kg)}sendSignal(e){return this.send(st.SendSignal,e,Fo,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(st.ClaimHost,e,bi)}kickMember(e){return this.send(st.KickMember,e,Ag)}unbanMember(e){return this.send(st.UnbanMember,e,Tg)}sendChat(e){return this.send(st.SendChat,e,Fo)}setMemberState(e){return this.send(st.SetMemberState,e,Fo)}};var pw={Free:"Free",Price:"Price",Holding:"Holding"},uu=zod.z.enum(["Free","Price","Holding"]).catch("Free"),hw={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},dw=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),mw={All:"All",Any:"Any"},fw=zod.z.enum(["All","Any"]).catch("All"),gw={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},yw=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),Rw={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},Cw=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),Sw={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Eg=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),bw={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},xw={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},Dw=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),Iw=zod.z.object({Type:Tn.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(),Pw=zod.z.object({Requirements:zod.z.array(Iw).nullish(),Match:fw.nullish(),Mode:dw.nullish()}).passthrough(),vw=zod.z.object({OptionID:zod.z.string().nullish(),Mode:uu.nullish(),Price:fe.nullish(),Holding:Pw.nullish()}).passthrough(),Aw=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(),Tw=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),Aw).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(uu).nullish(),PricePolicy:qr.nullish(),PublishGate:ee.nullish(),PublishFeeOptions:pe.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),ww=zod.z.object({Allowed:zod.z.array(ui).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),kw=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),zw=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(),Mw=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(),Ow=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:ee.nullish(),Schedule:Ce.nullish(),ContentTypes:zod.z.record(zod.z.string(),Tw).nullish(),PricePolicy:qr.nullish(),Commission:vl.nullish(),HoldingPolicy:ww.nullish(),Moderation:kw.nullish(),Limits:zw.nullish(),Featured:zod.z.array(Mw).nullish()}).passthrough(),Ew=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(),Dn=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:yw.nullish(),Access:zod.z.array(vw).nullish(),Status:Cw.nullish(),ModerationNote:zod.z.string().nullish(),Stats:Ew.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(),qw=zod.z.object({OptionID:zod.z.string().nullish(),Mode:uu.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),qg=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(),Ug=zod.z.object({Definitions:Ow.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(qg).nullish()}).passthrough(),$o=zod.z.object({Items:zod.z.array(Dn).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Lg=zod.z.object({Content:Dn.nullish(),AccessState:zod.z.array(qw).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Bg=zod.z.object({Collection:qg.nullish(),Items:zod.z.array(Dn).nullish()}).passthrough(),Gg=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(Dn).nullish()}).passthrough(),Og=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(),Ng=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(Og).nullish(),ThumbnailUpload:Og.nullish(),ExpiresAt:u.nullish()}).passthrough(),_g=zod.z.object({CreditsConfirmation:ye.nullish(),Content:Dn.nullish(),Resources:E.nullish()}).passthrough(),cu=zod.z.object({Content:Dn.nullish()}).passthrough(),Fg=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Eg.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:Gt.nullish(),Resources:E.nullish(),CommissionTaken:fe.nullish()}).passthrough(),Uw=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),Vg=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:Dw.nullish(),Files:zod.z.array(Uw).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:u.nullish()}).passthrough(),Lw=zod.z.object({ContentID:zod.z.string().nullish(),Source:Eg.nullish(),OptionID:zod.z.string().nullish(),PricePaid:fe.nullish(),AcquiredAt:u.nullish(),Content:Dn.nullish()}).passthrough(),jg=zod.z.object({Licenses:zod.z.array(Lw).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 Jo=class extends N{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(et.GetDefinitions,e,Ug)}browse(e){return this.send(et.Browse,e,$o)}getContent(e){return this.send(et.GetContent,e,Lg)}getCollection(e){return this.send(et.GetCollection,e,Bg)}getCreatorProfile(e){return this.send(et.GetCreatorProfile,e,Gg)}beginUpload(e){return this.send(et.BeginUpload,e,Ng)}publish(e){return this.send(et.Publish,e,we(_g))}updateContent(e){return this.send(et.UpdateContent,e,cu)}unpublish(e){return this.send(et.Unpublish,e,cu)}getMyContent(e){return this.send(et.GetMyContent,e,$o)}acquire(e){return this.send(et.Acquire,e,Fg)}getDownload(e){return this.send(et.GetDownload,e,Vg)}getMyLicenses(e){return this.send(et.GetMyLicenses,e,jg)}getMyFavorites(e){return this.send(et.GetMyFavorites,e,$o)}};var Zo=class extends N{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,Tm,"defs")}get(e){return this.sendKeyed("Get",e,kl,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,km,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,zl,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,zm,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,Ml,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,Ml,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Mm,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,Em,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Om,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,qm,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,wm,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Um,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,kl,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,zl,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Yo=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??ca(),this.settings=fu(e,this.host),this.emitter=new Qn,this.clientPlatform=e.clientPlatform??this.host.getClientPlatform(),this.acquisition=new hn(this.host),this.acquisition.capture(),this.playtime=new ni(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 ji({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 Qi(this.emitter),this.cache=new Ji(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 Zi(this.host.storage,this.settings.titleID),this.api={authentication:new Qr(this),user:new $r(this),currency:new Jr(this),item:new Xr(this),store:new eo(this),purchase:new so(this),lootbox:new ao(this),reward:new lo(this),quest:new fo(this),tutorial:new uo(this),communityMarketing:new co(this),chat:new po(this),push:new ho(this),localization:new mo(this),timedEvent:new go(this),leaderboard:new yo(this),season:new Ro(this),premium:new Co(this),character:new So(this),match:new bo(this),challenge:new xo(this),craft:new Io(this),ai:new Po(this),collection:new Ao(this),coopEvent:new To(this),dealOffer:new wo(this),referral:new ko(this),mailbox:new zo(this),clan:new Mo(this),avatar:new Oo(this),advertising:new Eo(this),social:new qo(this),timedBoost:new Bo(this),userCustomData:new Go(this),titleCustomData:new _o(this),title:new Vo(this),gameLoop:new jo(this),cloudCode:new Wo(this),blockchain:new Ho(this),marketplace:new Ko(this),multiplayer:new Qo(this),workshop:new Jo(this),dataCollections:new Zo(this),analytics:new Wr(this),experiment:new Hr(this)},this.userService=new is(this),this.cache.attachState(this.userService),this.auth=new Xi(this),this.currency=new rs(this),this.item=new os(this),this.store=new ps(this),this.credits=new hs(this),this.purchase=new ds(this),this.checkout=new ms(this),this.lootbox=new fs(this),this.reward=new ys(this),this.quest=new As(this),this.tutorial=new Cs(this),this.communityMarketing=new Ss(this),this.chat=new Ds(this),this.push=new Is(this),this.localization=new vs(this),this.timedEvent=new ks(this),this.leaderboard=new Ls(this),this.season=new Ns(this),this.premium=new _s(this),this.character=new js(this),this.match=new Ws(this),this.challenge=new Hs(this),this.craft=new Ks(this),this.ai=new $s(this),this.collection=new Js(this),this.coopEvent=new Xs(this),this.dealOffer=new nr(this),this.referral=new ir(this),this.mailbox=new or(this),this.clan=new cr(this),this.avatar=new dr(this),this.ads=new fr(this),this.social=new Sr(this),this.timedBoost=new br(this),this.userCustomData=new xr(this),this.titleCustomData=new Dr(this),this.title=new Ir(this),this.gameLoop=new Tr(this),this.cloudCode=new wr(this),this.blockchain=new Mr(this),this.marketplace=new Lr(this),this.multiplayer=new Br(this),this.workshop=new Gr(this),this.dataCollections=new _r(this),this.analytics=new Vr(this),this.experiments=new jr(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:_()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var Xo=class{ctx;constructor(e){this.ctx=new Yo(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,n={}){let i=this.ctx.buildAuthedBaseRequest(),s=rn(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 Gw(r){return new Xo(r)}var Wg="idos_sso",Hg="state",pu="idos:sso:state",Nw="https://idosgames.com/sso/",_w=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],Fw=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function Vw(){if(typeof window>"u")return false;let{origin:r}=window.location;return _w.includes(r)||Fw.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function jw(){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(Wg);if(!t)return null;let n=e.get(Hg)??"",i=$w();return Zw(e),Jw(),i&&n!==i?null:{code:t,state:n}}function Ww(r){if(typeof window>"u")return;let e=r.returnTo??Hw(),t=Kw();Qw(t);let n=new URL(r.ssoUrl??Nw);n.searchParams.set("title",r.titleID),n.searchParams.set("return_to",e),n.searchParams.set("state",t),window.location.assign(n.toString());}function Hw(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function Kw(){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 Qw(r){try{window.sessionStorage.setItem(pu,r);}catch{}}function $w(){try{return window.sessionStorage.getItem(pu)}catch{return null}}function Jw(){try{window.sessionStorage.removeItem(pu);}catch{}}function Zw(r){r.delete(Wg),r.delete(Hg);let e=r.toString(),{pathname:t,search:n}=window.location;window.history.replaceState(null,"",`${t}${n}${e?`#${e}`:""}`);}var Yw={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 Xw(r,e="Something went wrong. Please try again."){return r?Yw[r]??r:e}function ek(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function tk(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function nk(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function Qg(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*Kg(r,t,1);break;case "TableAbsolute":o=Kg(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 ik(r,e,t=1){return Qg(r,1,e,t)}function sk(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 $g(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function rk(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 $g(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 Kg(r,e,t){let n=$g(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 Jg(r,e){return e?.BonusMode??r?.SetSettings?.BonusMode??"Cumulative"}function Zg(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 ok(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 V=lk(n,m.ItemID,m.CatalogID??null)?.Metadata?.CollectionID;!V||!(V in t)||i.set(V,(i.get(V)??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,V=Jg(e,m);o.push({SetID:p,Definition:m,Pieces:g,Mode:V,ActiveTiers:Zg(m,g,V)});}return o}function ak(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 lk(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 uk={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},hu=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),ck={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},pk=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),hk=zod.z.object({PlacementID:zod.z.string().nullish(),Type:hu.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(),dk=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(),mk=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),fk=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:pk.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),gk=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),yk=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),Rk=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(),Ck=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(),Sk=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),bk=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:hu.nullish()}).passthrough(),xk={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},Dk=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),Ik=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:Dk.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(),bk).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),hk).nullish(),Providers:zod.z.record(zod.z.string(),Ik).nullish(),RewardedVideo:dk.nullish(),Interstitial:mk.nullish(),Banner:fk.nullish(),AppOpen:gk.nullish(),FrequencyCapping:yk.nullish(),PremiumAdReductions:zod.z.array(Rk).nullish(),Consent:Ck.nullish(),Verification:Sk.nullish()}).passthrough();var Pk=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),vk=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(),Ak=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(),Tk=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(),wk=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(),kk=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:hu.nullish(),IssuedAt:u.nullish(),ExpiresAt:u.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),zk=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:Pk.nullish(),Placements:zod.z.record(zod.z.string(),vk).nullish(),Daily:Ak.nullish(),Session:Tk.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:wk.nullish(),PendingRequests:zod.z.record(zod.z.string(),kk).nullish(),FraudFlags:zk.nullish(),UpdatedAt:u.nullish()}).passthrough();
|
|
2
|
-
exports.AIAction=je;exports.AIErrorCode=
|
|
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 yu(r){return {get:e=>r.getString(e),set:(e,t)=>r.setString(e,t),remove:e=>r.remove(e)}}var Ru="https://api.idosgames.com";function Cu(r,e){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??Ru).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??yu(e.storage),locale:r.locale??e.getLanguage(),appVersion:r.appVersion??""}}function F(){return crypto.randomUUID()}var sy="idos-host-files",Ii="files";function Pi(r){return new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function ry(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(sy,1);return e.onupgradeneeded=()=>{e.result.objectStoreNames.contains(Ii)||e.result.createObjectStore(Ii,{keyPath:"key"});},await Pi(e)}catch{return null}})()),this.db}async store(e){let t=await this.open();if(!t)return null;try{return t.transaction(Ii,e).objectStore(Ii)}catch{return null}}async read(e){let t=await this.store("readonly");if(!t)return this.fallback.read(e);try{let n=await Pi(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:ry(t),size:t.byteLength,updatedAt:Date.now()};return await Pi(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 Pi(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 vi(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 Su="idos_device_id",ia="idos:platformSignIn:declined:",tt="UNAVAILABLE",vn=Object.freeze({autoSignIn:false,signIn:false,rewardedAds:false,titleAds:false,storePurchases:false,creditsPayments:true,creditsConfirm:false,cryptoTopUp:false,tokenTrade: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;}openTrade(e){return Promise.resolve({ok:false,error:tt})}buyProduct(e){return Promise.resolve({ok:false,error:tt})}finishPurchase(e,t){return Promise.resolve(false)}pendingPurchases(){return Promise.resolve([])}pickFiles(e){return Promise.resolve([])}requestPushToken(e){return Promise.resolve({error:tt})}getDeviceID(){let e=this.storage.getString(Su);return e||(e=this.newDeviceID(),this.storage.setString(Su,e)),e}newDeviceID(){return F()}setSignInDeclined(e,t){t?this.storage.setString(ia+e,"1"):this.storage.remove(ia+e);}isSignInDeclined(e){return this.storage.getString(ia+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 Ai(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 bt={Virtual:"Virtual",Crypto:"Crypto"},Tn=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),Ti={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"},wi=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),oy={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},ki=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),ay={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Challenge:"Challenge",ChallengePoints:"ChallengePoints"},zi=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season","Challenge","ChallengePoints"]).catch("TimedEvent"),ly={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:tt}}async showRewardedAd(){return {ok:false,error:tt}}async confirmCredits(){return {ok:false,error:tt}}async topUp(){return {ok:false,error:tt}}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 Mi(){return globalThis.crossOriginIsolated===true&&typeof SharedArrayBuffer<"u"}function Oi(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 sa=1,xu="__IDOS_HOST__";function ra(){let r=globalThis[xu];return !r||typeof r!="object"||r.protocol!==1||typeof r.post!="function"?null:r}var uy={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 cy(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"),tokenTrade:false,sceneCaptureRequests:false,share:i("share"),vibration:i("vibration"),sharedMemory:Mi(),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"});},uy[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 cy(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 vi(e)}async shareFile(e){let t=await this.request("shareFile",{name:e.name,mime:e.mime,data:py(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:Ai(e)});}createWorker(e,t){return Oi(e,t)}};function py(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 Du(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return bu(e);let t=r.cordova?.platformId;return t?bu(t):r.navigator?.userAgent??""?Ge.Web:Ge.Unknown}function bu(r){let e=r.toLowerCase();return e==="android"?Ge.Android:e==="ios"?Ge.Ios:e==="web"?Ge.Web:Ge.Unknown}var Dt=["https://idosgames.com","https://www.idosgames.com"],Ei="https://platform.idosgames.com",Iu=/^[a-z0-9]{8}-preview\.idos\.games$/;function oa(r){return r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r.endsWith(".localhost")}function ni(){if(typeof window>"u")return false;let r=window.location.hostname.toLowerCase();return Iu.test(r)?true:oa(r)&&globalThis.__IDOS_PREVIEW__!=null}function cn(r){if(typeof window<"u"&&Iu.test(window.location.hostname.toLowerCase()))return r===Ei;if(Dt.includes(r))return true;if(typeof window>"u"||!oa(window.location.hostname))return false;try{return oa(new URL(r).hostname)}catch{return false}}var Pu="IDOS_PLATFORM_WALLET_ACK",qi="PLATFORM_WALLET_UNAVAILABLE",hy=5e3,dy=18e4;function my(){if(cn(Ei))return [Ei];let r=[...Dt],e=window.location.ancestorOrigins?.[0];return e&&!r.includes(e)&&cn(e)&&r.push(e),r}function fy(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function It(r,e,t,n={}){let i={ok:false,error:qi,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=fy(),p=n.answerTimeoutMs??dy;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 xe=me.data;if(!(!xe||xe.requestId!==o)){if(xe.type===Pu){clearTimeout(j),j=setTimeout(()=>ce({ok:false,error:"TIMEOUT",data:{}}),p);return}xe.type===e&&ce({ok:xe.ok===true,error:typeof xe.error=="string"?xe.error:void 0,data:xe});}};j=setTimeout(()=>ce(i),hy),window.addEventListener("message",ve);for(let me of my())try{s.postMessage({type:r,requestId:o,...t},me);}catch{}})}var aa={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},gy=30*6e4;function vu(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(ni())return false;let r=window.location.ancestorOrigins?.[0];if(r&&!Dt.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 la(){if(typeof window>"u"||!ni())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function Au(r){let e=await It(aa.request,aa.response,{titleID:r,supports:["pgs"]},{answerTimeoutMs:gy}),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 ua={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},yy=15*6e4,Ry=/^[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 !Ry.test(window.location.hostname.toLowerCase())}async function Tu(r){let e=await It(ua.request,ua.response,{titleID:r.titleID,userID:r.userID,currencyID:r.currencyID,amount:r.amount},{answerTimeoutMs:yy});return e.ok?{ok:true}:{ok:false,error:e.error}}var ca={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},Cy=5*6e4;function wu(){return kn()}async function ku(r){let e=await It(ca.request,ca.response,{titleID:r.titleID,userID:r.userID,requestID:r.requestID,placementID:r.placementID,adUnitID:r.adUnitID??null},{answerTimeoutMs:Cy});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var pa={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},Sy=10*6e4,xy=["DECLINED","NOT_ENOUGH_CREDITS"];function zu(){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 Mu(){return kn()}async function Ou(r){let e=await It(pa.request,pa.response,{titleID:r.titleID,confirmationID:r.confirmationID},{answerTimeoutMs:Sy});return e.ok?{ok:true}:{ok:false,error:e.error}}var ha={request:"IDOS_PLATFORM_TRADE_REQUEST",response:"IDOS_PLATFORM_TRADE_RESPONSE"};function Eu(r){return typeof r=="string"&&/^\d{1,15}(\.\d{1,18})?$/.test(r)&&Number(r)>0}function da(r,e,t){let n=`trade=${e}${t?`&amount=${encodeURIComponent(t)}`:""}`;return `${Dt[0]}/app/${encodeURIComponent(r)}?${n}`}async function qu(r){let e=await It(ha.request,ha.response,{titleID:r.titleID,side:r.side,amount:r.amount??null});return e.ok?{ok:true}:{ok:false,error:e.error}}var Lu="IDOS_APP_FRAME_HIDDEN";function pn(){return globalThis.navigator??null}function Ui(){return typeof window<"u"}function Uu(){if(!Ui())return false;try{return window.self!==window.top}catch{return true}}var ii=class extends Ht{id;supports;hiddenBySite=false;documentHidden=false;constructor(e=new un){if(super(e,new ln),!Ui()){this.id="web",this.supports=vn;return}let t=pn(),n=vu();this.supports=Object.freeze({autoSignIn:n,signIn:n||la(),rewardedAds:wu(),titleAds:false,storePurchases:false,creditsPayments:zu(),creditsConfirm:Mu(),cryptoTopUp:kn(),tokenTrade:!ni(),sceneCaptureRequests:Uu(),share:typeof t?.share=="function",vibration:typeof t?.vibrate=="function",sharedMemory:Mi(),filePicker:Jn(),pushNotifications:false}),this.id=Kt()?"telegram":la()?"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();})),Uu()&&window.addEventListener("message",e=>{let t=e.data;!t||t.type!==Lu||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 Du()}getFullURL(){return Ui()?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?Au(e):{error:tt}}async showRewardedAd(e){return this.supports.rewardedAds?ku(e):{ok:false,error:tt}}async confirmCredits(e){return this.supports.creditsConfirm?Ou(e):{ok:false,error:tt}}async topUp(e){return this.supports.cryptoTopUp?Tu(e):{ok:false,error:tt}}async openTrade(e){if(!this.supports.tokenTrade)return {ok:false,error:tt};let t=e?.side,n=e?.amount;if(!e?.titleID||t!=="buy"&&t!=="sell"||n!=null&&n!==""&&!Eu(n))return {ok:false,error:"BAD_REQUEST"};if(this.supports.cryptoTopUp){let i=await qu({titleID:e.titleID,side:t,amount:n||null});return i.ok?{ok:true}:{ok:false,error:i.error===qi?tt:i.error}}return this.openUrl(da(e.titleID,t,n||null)),{ok:true}}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}Ui()&&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 vi(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 by(e)}vibrate(e){try{pn()?.vibrate?.(Ai(e));}catch{}}createWorker(e,t){return Oi(e,t)}};function by(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 ma(){let r=ra();return r?new ti(r):typeof window>"u"?new Xn:new ii}var fa="idos_acq",Bu=["gclid","fbclid","ttclid","msclkid","yclid"],Dy=["ref","r"],Iy=["ref_","ref-","ref=","r_","r-"];var dn=class{constructor(e){this.host=e;}host;capture(){let e=this.readFromEnvironment();Py(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),n=t?{...t.signal}:{},i=Ty(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(fa);}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=_u(Nu(t));if(n)return n}return Li(t)}readFromEnvironment(){let e={},t=Nu(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 Bu){let j=t.get(g);if(j){e.ClickID=j;break}}let n=this.host.getStartParameter()??"",i=Ay(n);if(i){for(let g of vy)hn(e,g,i.get(Fu[g])??null);for(let g of Bu){let j=i.get(g);if(j){e.ClickID=j;break}}}let s=Li(i?i.get("ref")??i.get("r")??"":n),o=_u(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(fa);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(fa,JSON.stringify(e));}catch{}}};function Py(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 Gu="a1_",Fu={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},vy=Object.keys(Fu);function Ay(r){let e=(r||"").trim();if(!e.startsWith(Gu))return null;let t=e.slice(Gu.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 Nu(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function _u(r){for(let e of Dy){let t=r.get(e);if(t)return Li(t)}return null}function Li(r){let e=(r||"").trim();if(!e)return null;for(let t of Iy)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Ty(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 Vu="idos_usage_pending",ju="idos_usage_session",Wu="idos_usage_closed_session",Hu="idos_usage_new_session",Ku="idos_usage_last_activity",si=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(Vu),this.currentSessionSeconds=this.readNumber(ju),this.pendingClosedSessionSeconds=this.readNumber(Wu),this.isNewSessionPending=this.readNumber(Hu)!==0;let e=this.readNumber(Ku);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(Vu,this.pendingSeconds),this.writeNumber(ju,this.currentSessionSeconds),this.writeNumber(Wu,this.pendingClosedSessionSeconds),this.writeNumber(Hu,this.isNewSessionPending?1:0),this.writeNumber(Ku,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 wy(r){return r.ok}function ky(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 kt=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()}),zy=zod.z.object({Type:zi.nullish(),EntityID:zod.z.string()}),My=zod.z.object({Address:zy.nullish(),Amount:Q.nullish(),Source:zod.z.string().nullish()}),pe=zod.z.object({Entries:zod.z.array(kt).nullish(),EventTokens:zod.z.array(My).nullish()}),Qu=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(Qu).nullish()}),Gt=zod.z.object({Standard:pe.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Qu).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 Oy=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ey={Completed:"Completed",Started:"Started",StepReached:"StepReached"},qy=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:Oy.nullish(),Tutorial:qy.nullish(),Platforms:zod.z.array(wi).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 Uy=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Ly=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),By=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 Gy=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:Ly.nullish(),Chain:By.nullish(),Cyclic:Gy.nullish(),ActivationTriggers:zod.z.array(mt).nullish(),Relative:Uy.nullish()}).passthrough();var Ny={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},_y=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Fy={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Vy=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),jy=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Je=zod.z.object({Base:zod.z.number().nullish(),Shape:_y.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(jy).nullish(),Interpolation:Vy.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var Wy=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:$.nullish()}).passthrough(),Hy=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),ga=zod.z.object({Bundles:zod.z.array(Wy).nullish(),Multipliers:zod.z.array(Hy).nullish()}).passthrough();var Ky=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Bi=zod.z.object({Source:Ky.nullish(),SourceKey:zod.z.string().nullish(),Curve:Je.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:pe.nullish(),ExcludeRewards:pe.nullish()}).passthrough(),$u=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:ga.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 Qy=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),zt=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:Qy.nullish()}).passthrough();var $y=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:$y.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()}),Mt=r=>zod.z.object({ServerTimeUtc:u,Items:zod.z.array(Oe(r)),Resources:O.nullish(),Inventory:K.nullish()});var Jy={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Ju=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Zy=zod.z.object({}).passthrough().transform(r=>r),Yy=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()}),ya=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:Ju}),Zu=zod.z.object({State:Zy.nullish(),PointsTracks:zod.z.record(zod.z.string(),Yy).nullish()}),Ra=zod.z.object({ServerTimeUtc:u,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:Ju.nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Ca=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()}),Yu=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()}),Xu=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(ya).nullish()}),ec=zod.z.array(Oe(Ra)),tc=zod.z.array(Oe(Ca)),Xy={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},eR=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),tR={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},nR=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),nc=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:eR.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(),Sa=zod.z.object({Milestones:J.nullish(),Linking:J.nullish(),Availability:J.nullish(),Reward:J.nullish(),Objectives:J.nullish()}).passthrough(),iR=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(),ic=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:nR.nullish()}).passthrough(),sc=zod.z.object({Schedule:Ce.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),rc=zod.z.object({Grant:$.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),sR=zod.z.object({QuestID:zod.z.string().nullish(),Identity:iR.nullish(),Linking:ic.nullish(),Availability:sc.nullish(),Objectives:zod.z.record(zod.z.string(),nc).nullish(),Reward:rc.nullish(),Presets:Sa.nullish()}).passthrough(),rR=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(),oR=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:Sa.nullish(),PointsToken:zt.nullish()}).passthrough(),aR=zod.z.object({Milestones:zod.z.record(zod.z.string(),zn).nullish(),Linking:zod.z.record(zod.z.string(),ic).nullish(),Availability:zod.z.record(zod.z.string(),sc).nullish(),Reward:zod.z.record(zod.z.string(),rc).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),nc)).nullish()}).passthrough(),lR=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:zt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),rR).nullish(),Phases:zod.z.record(zod.z.string(),oR).nullish(),Presets:Sa.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ni=zod.z.object({Cycles:zod.z.record(zod.z.string(),lR).nullish(),Quests:zod.z.record(zod.z.string(),sR).nullish(),Presets:aR.nullish()}).passthrough(),vt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var uR={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},cR=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),pR={Never:"Never",OnRequest:"OnRequest",Always:"Always"},hR=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),dR={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},mR=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),fR={GameLoop:"GameLoop"},gR={Raid:"Raid",Attack:"Attack"},yR=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(),RR=zod.z.object({Mode:cR.nullish(),Triggers:zod.z.array(mt).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),CR=zod.z.object({Grant:$.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),SR=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(),xR=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:SR.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),bR=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),xa=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:yR.nullish(),Completion:RR.nullish(),Effects:CR.nullish(),Script:xR.nullish(),Policy:bR.nullish()}).passthrough(),DR=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(),oc=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(),ac=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:hR.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),lc=zod.z.object({Grant:$.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),IR=zod.z.object({Availability:J.nullish(),Policy:J.nullish(),Reward:J.nullish(),Steps:J.nullish()}).passthrough(),PR=zod.z.object({FlowID:zod.z.string().nullish(),Identity:DR.nullish(),Availability:oc.nullish(),Policy:ac.nullish(),Steps:zod.z.record(zod.z.string(),xa).nullish(),Reward:lc.nullish(),Presets:IR.nullish()}).passthrough(),vR=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(),AR=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:vR.nullish()}).passthrough(),TR=zod.z.object({Availability:zod.z.record(zod.z.string(),oc).nullish(),Policy:zod.z.record(zod.z.string(),ac).nullish(),Reward:zod.z.record(zod.z.string(),lc).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),xa)).nullish()}).passthrough(),uc=zod.z.object({Flows:zod.z.record(zod.z.string(),PR).nullish(),Settings:AR.nullish(),Presets:TR.nullish()}).passthrough(),wR=zod.z.object({}).passthrough().transform(r=>r),cc=zod.z.object({FlowID:zod.z.string(),Status:mR,CurrentStepID:zod.z.string().nullish(),CurrentStep:xa.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(),_i=zod.z.object({State:wR.nullish(),Flows:zod.z.array(cc).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),$t=zod.z.object({Flow:cc.nullish()}).passthrough(),pc=zod.z.object({FlowID:zod.z.string().nullish(),Granted:O.nullish()}).passthrough(),hc=zod.z.array(Oe($t)),dc=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 Fi(r){return Array.isArray(r)?r.filter(e=>e!==null).map(Fi):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,Fi(t)])):r}var Vi=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 ji=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function mc(r){return r===429||r>=500&&r<=599}function Wi(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 fc=15e3;async function gc(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 yc(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function Rc(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var ba=15,Cc=1e3,Hi=class{constructor(e=ba,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]>=Cc;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(Cc-(e-this.starts[0])+5);}}};var kR=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function En(r){if(!r)return null;let e=kR.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 zR=12e3,MR=new Set(["RelatedEntityID"]);function OR(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[n,i]of Object.entries(e))MR.has(n)||(t[n]=i);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var ER=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(ya).nullish(),TutorialProgress:zod.z.array(dc).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),Ki=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new ji;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 Vi(e.throttleMs),this.pacer=new Hi(e.maxRequestsPerSecond??ba),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??OR(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??zR,ce=i.autoRetry??!0,ve=!1,me=!1,xe=0;for(;;){let Bt;i.keepalive||await this.pacer.take();try{Bt=await this.doFetch(o,p,m,j,i.keepalive??!1);}catch{if(ce&&xe<3){xe++,await Jt(Wi(xe));continue}return this.connectionFailure("Internet Connection Error",g)}let at=Bt.status;if(at>=200&&at<300){let ue=!me&&this.cryptoTopUpHandler!==null,Me=await this.parseSuccess(Bt,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(at===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(mc(at)){let ue=at===429?await gc(Bt):null;if(ue!==null&&ue>fc)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ue/1e3)} s`,g);if(ce&&xe<3){xe++,await Jt(ue!==null?yc(ue):at===429?Rc(xe):Wi(xe));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${at})`,g)}let Kn="";try{Kn=await Bt.text();}catch{}if(at===409&&/operation in progress/i.test(Kn)&&ce&&xe<3){xe++,await Jt(Wi(xe));continue}return this.handleWebError(Kn,at,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=ER.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",xe=s&&En(me);return !n&&!xe&&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(Fi(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 ri(r){return `${qn(r)}T00:00:00.000Z`}function Sc(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function xc(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function Pa(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,xe=new Map,Bt=e.Grant?.PremiumTiers??[],at=Bt.length;for(let ue=0;;ue++){let Me,ge;if(ue===0)Me=e.Grant?.Standard?.Entries,ge=false;else if(ue-1<at)Me=Bt[ue-1]?.Resources?.Entries,ge=false;else if(ue===1+at)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=UR(t,fe.CatalogID,fe.ItemID),Te=(Se?Se.IsStackable??true:true)?ge?ve:ce:ge?xe: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:ri(n),Earned:Me,Spent:ge}):s.VirtualCurrencies[ue]={Amount:fe,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:ri(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||xe.size>0,i.itemsChanged){s.Items??={},s.UnstackableItems??={};let ue=s.UnstackableItems,Me=new Set([...ce.keys(),...ve.keys(),...me.keys(),...xe.keys()]);for(let ge of Me){let fe=(ce.get(ge)??0)-(ve.get(ge)??0),Re=(me.get(ge)??0)-(xe.get(ge)??0),Se=fe+Re,dt=s.Items[ge];dt?(fe!==0&&(dt.StackableAmount+=fe),Re!==0&&(dt.UnstackableAmount+=Re),Se!==0&&(dt.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 xe){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(qR).slice(0,fe).map(Se=>Se.ItemInstanceID);for(let Se of Re)delete ue[Se];}for(let[ge,fe]of me){let Re=LR(t,ge);for(let Se=0;Se<fe;Se++){let dt=F();ue[dt]={ItemInstanceID:dt,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<at)Me=Bt[ue-1]?.Resources?.EventTokens,ge=false;else if(ue===1+at)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 dt=BR(Kn,Re.Type);if(!dt)continue;let Te=dt[Re.EntityID];Te||(Te={},dt[Re.EntityID]=Te),Te.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Te.Daily??={Date:ri(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:ri(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 qR(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 UR(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 LR(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 BR(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 bc(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 va(r,e){return r===e||r.startsWith(`${e}:`)}var $i=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=Pa(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=Pa(s,e,n,i),m=bc(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,xe]of Object.entries(m.restore))ve[me]=xe;for(let[me,xe]of g)ve[me]=xe;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=Sc(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(va(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:!va(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 Ji=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 Zi=class{user;config;constructor(e){this.user=new $i(e),this.config=new Ji;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function GR(r){return r}var NR=0,_R=1500,FR=3,Xi=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();},NR),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=Yi(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:Aa(e,g.data,j)}),g;let ce=this.entries.get(i);if(ce&&ce.storedAt>=o)return g;let ve=Aa(e,g.data,j);return this.entries.set(i,{data:g.data,storedAt:j,expiresAt:Math.min(ve??1/0,j+_R)}),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=Yi(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=Dc({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>FR||this.used.set(Dc(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(Yi(e,t))?.data}put(e,t,n){this.register(e);let i=Yi(e,n);this.bump(i);let s=Date.now();this.entries.set(i,{data:t,storedAt:s,expiresAt:Aa(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 Yi(r,e){return e===void 0?r.key:`${r.key}|${e}`}function Dc(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function Aa(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 es=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 VR(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 VR(r){return r!==null&&Object.values(qe).includes(r)}var jR=8,WR=100,HR=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,ts=["GameLoop"];function KR(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var ns=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(ts,ts);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"):(KR(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&&HR.test(e)}static isValidPasswordLength(e){return e.length>=jR&&e.length<=WR}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(ts,ts);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 QR="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:${Ic(t)}`:e&&e.length>0?`f:${Ic(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 `${QR}:${this.titleId}:${e}`}};function Ic(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var Pc="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 `${Pc}:${this.titleId}:${e}`}versionsKey(){return `${Pc}:${this.titleId}:versions`}};var $R="idos:sec",is=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 `${$R}:${this.titleId}`}};var JR="idos:state",ss=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 `${JR}:${this.titleId}:${e}`}};function ZR(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 Ta(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 YR(r){return {...r??{}}}function wa(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.StateEpoch:null}var rs=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=ZR(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=YR(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 vc=h("server","Title configuration is unavailable (CDN and API both failed)."),os=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 is(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new rs(new ss(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?vc:(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=Ta(e.User,t.cached,t.sent,e.StateVersions);e.User=n;let i=wa(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?vc:(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=Ta(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=wa(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 ls=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===bt.Crypto||n===bt.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===bt.Virtual&&n===bt.Virtual)return h("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===bt.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===bt.Virtual&&ce.push({Type:"VirtualCurrency",CurrencyID:j.SourceID,Amount:Math.trunc(Number(j.SourceSpent))}),j.TargetType===bt.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===bt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.SourceID,new mn__default.default(j.SourceSpent).negated(),j.ServerTimeUtc),j.TargetType===bt.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 us=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 cs=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:Gt.nullish(),AllowedPlatforms:zod.z.array(wi).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),de=zod.z.record(zod.z.string(),cs),XR=zod.z.object({Store:ki,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var oi={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(),Ac=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),eC={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"},ka=zod.z.object({ServerTimeUtc:u,OfferID:zod.z.string(),Count:zod.z.number(),Resources:O.nullish(),Inventory:K.nullish(),CreditsConfirmation:ye.nullish()}),Tc=zod.z.array(Oe(ka)),tC=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:u,LastPurchasedAt:u}),nC=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:u}),wc=zod.z.object({Purchases:zod.z.record(zod.z.string(),tC).nullish(),Rotations:zod.z.record(zod.z.string(),nC).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(),ps=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),iC={Fixed:"Fixed",Title:"Title",Player:"Player"},sC=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:ee.nullish()}).passthrough(),kc=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(sC).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),rC=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Rotation:J.nullish()}).passthrough(),oC=zod.z.object({SlotID:zod.z.string().nullish(),Identity:_t.nullish(),Availability:ps.nullish(),Rotation:kc.nullish(),Presets:rC.nullish()}).passthrough(),aC=zod.z.object({Identity:J.nullish(),Availability:J.nullish()}).passthrough(),lC=zod.z.object({SectionID:zod.z.string().nullish(),Identity:_t.nullish(),Availability:ps.nullish(),Slots:zod.z.record(zod.z.string(),oC).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:aC.nullish()}).passthrough(),zc=zod.z.object({Sections:zod.z.record(zod.z.string(),lC).nullish()}).passthrough(),uC=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Layout:J.nullish()}).passthrough(),cC=zod.z.object({StoreID:zod.z.string().nullish(),Identity:_t.nullish(),Availability:ps.nullish(),Layout:zc.nullish(),Presets:uC.nullish()}).passthrough(),Mc=zod.z.object({Options:de.nullish(),CompareAt:zod.z.record(zod.z.string(),Gt).nullish()}).passthrough(),Oc=zod.z.object({Grant:$.nullish()}).passthrough(),Ec=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),pC=zod.z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish(),Availability:J.nullish()}).passthrough(),hC=zod.z.object({OfferID:zod.z.string().nullish(),Identity:_t.nullish(),Pricing:Mc.nullish(),Reward:Oc.nullish(),Availability:Ec.nullish(),Presets:pC.nullish()}).passthrough(),dC=zod.z.object({Identity:zod.z.record(zod.z.string(),_t).nullish(),Availability:zod.z.record(zod.z.string(),ps).nullish(),Layout:zod.z.record(zod.z.string(),zc).nullish(),Rotation:zod.z.record(zod.z.string(),kc).nullish(),Pricing:zod.z.record(zod.z.string(),Mc).nullish(),Reward:zod.z.record(zod.z.string(),Oc).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Ec).nullish()}).passthrough(),hs=zod.z.object({Stores:zod.z.record(zod.z.string(),cC).nullish(),StoreOffers:zod.z.record(zod.z.string(),hC).nullish(),Presets:dC.nullish()}).passthrough(),mC=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(),fC=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(),gC=zod.z.object({OfferID:zod.z.string(),Identity:_t.nullish(),PriceOptions:zod.z.array(fC).nullish(),Rewards:$.nullish(),State:mC.nullish()}).passthrough(),yC=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:gC.nullish()}).passthrough(),RC=zod.z.object({SectionID:zod.z.string(),Identity:_t.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(yC).nullish()}).passthrough(),CC=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(RC).nullish()}).passthrough(),ds=zod.z.object({ServerTimeUtc:u,Stores:zod.z.array(CC).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Ft={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},SC="OFFER_NOT_IN_ROTATION";var qc="Store",Uc={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}},ms=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Uc,{schema:ds,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(qc,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(qc,i.data),this.ctx.emitter.emit("store:definitionsLoaded",i.data)),i}getStorefront(e){return this.ctx.cache.read(Uc,()=>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 fs=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!==oi.Pending)return g===oi.Declined?h("server","CREDITS_CONFIRMATION_DECLINED"):g===oi.Expired?h("server","CREDITS_CONFIRMATION_EXPIRED"):await s()}}};var gs=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 Lc=3,xC=700,ys=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<=Lc;t++){let n=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(n.ok)return;if(n.reason!=="throttled"||t===Lc)break;await Jt(xC);}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===Ti.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!==Ti.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 Bc="Lootbox",Rs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Bc,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(Bc,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 za="Reward";function Cs(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Ss=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(za)?.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(za,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(za,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(!Cs(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(!Cs(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(!Cs(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(!Cs(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 xs="Tutorial",Gc={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"]},bs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Gc,{schema:_i,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(xs)?.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(xs,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(xs,i.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",i.data)),i}getUserTutorialState(e=true,t){return this.ctx.cache.read(Gc,()=>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(xs)?.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 Ds=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 bC={Global:"Global",Announcement:"Announcement",Group:"Group"},_c=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),DC={None:"None",Language:"Language",Region:"Region"},IC=zod.z.enum(["None","Language","Region"]).catch("None"),PC={Anyone:"Anyone",Friends:"Friends"},vC=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),AC={Reject:"Reject",Mask:"Mask"},TC=zod.z.enum(["Reject","Mask"]).catch("Reject"),wC={Player:"Player",Publisher:"Publisher",System:"System"},kC=zod.z.enum(["Player","Publisher","System"]).catch("Player"),zC={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var MC=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),Fc=zod.z.object({Gate:ee.nullish(),Schedule:Ce.nullish()}).passthrough(),Vc=zod.z.object({Gate:ee.nullish(),Limits:Pe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),jc=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),OC=zod.z.object({Availability:J.nullish(),Write:J.nullish(),Retention:J.nullish()}).passthrough(),EC=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:MC.nullish(),Type:_c.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:IC.nullish(),Capacity:zod.z.number().nullish(),Availability:Fc.nullish(),Write:Vc.nullish(),Retention:jc.nullish(),Presets:OC.nullish()}).passthrough(),qC=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:ee.nullish(),WhoCanMessage:vC.nullish(),Limits:Pe.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),UC=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:TC.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Pe.nullish()}).passthrough(),LC=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),BC=zod.z.object({Availability:zod.z.record(zod.z.string(),Fc).nullish(),Write:zod.z.record(zod.z.string(),Vc).nullish(),Retention:zod.z.record(zod.z.string(),jc).nullish()}).passthrough(),Wc=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),EC).nullish(),Direct:qC.nullish(),Moderation:UC.nullish(),Polling:LC.nullish(),Presets:BC.nullish()}).passthrough(),GC=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(),GC).nullish(),Limits:zod.z.record(zod.z.string(),Nc).nullish(),ReportLimits:Nc.nullish()}).passthrough();var Ma=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),Is=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:kC.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(),NC=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:_c.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(),Ps=zod.z.object({Channels:zod.z.array(NC).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),_C=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Is).nullish(),NextCursor:Ma.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Hc=zod.z.object({Rooms:zod.z.array(_C).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Kc=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Is).nullish(),NextBefore:Ma.nullish()}).passthrough(),Qc=zod.z.object({Message:Is.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),$c=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ne.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),FC=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ne.nullish(),LastMessage:Is.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Jc=zod.z.object({Conversations:zod.z.array(FC).nullish()}).passthrough(),Bn=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:Ma.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),Zc=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),nt={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",Xc={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},vs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Xc,{schema:Ps,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),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(Yc,i.data),this.ctx.emitter.emit("chat:definitionsLoaded",i.data)),i}getChannels(e,t){return this.ctx.cache.read(Xc,()=>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 VC={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},jC=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),WC={Player:"player",Title:"title",Creator:"creator"},Gn={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},ep=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),HC=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),Oa=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:jC.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(HC).nullish()}).passthrough(),tp=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(Oa).nullish()}).passthrough(),it={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var KC="IDOS_PLATFORM_PUSH_REQUEST",QC="IDOS_PLATFORM_PUSH_RESPONSE",$C=12e4;function np(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!==QC||g.requestId!==t||Dt.includes(m.origin)&&s(g.ok===true);},p=setTimeout(()=>s(false),$C);window.addEventListener("message",o);for(let m of Dt)try{e.postMessage({type:KC,requestId:t,titleID:r},m);}catch{}})}var JC="idos:push:deviceToken:",As=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 it.Unsupported;let s=await this.ctx.host.requestPushToken({prompt:false});return s.error==="BLOCKED"?it.Blocked:s.token?this.ctx.host.storage.getString(this.deviceTokenKey())===s.token?it.Subscribed:it.Idle:s.error==="NOT_GRANTED"?it.Idle:it.Unsupported}if(!e.Configured||!e.PublicKey)return it.Unsupported;if(this.isEmbedded())return it.Embedded;if(!this.isSupported())return it.Unsupported;let t=Notification.permission;return t==="denied"?it.Blocked:t!=="granted"?it.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?it.Subscribed:it.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 np(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:ZC(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 JC+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 ZC(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 Ts=Object.freeze({}),ws=class{constructor(e){this.ctx=e;}ctx;table={...Ts};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?YC(i,t):i}applyState(e,t){if(!e){this.reset();return}let n=e.Locale??null;this.table=t.table??{...Ts},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={...Ts},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(ip(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??ip(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??{...Ts},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 YC(r,e){return r.replace(/\{(\w+)\}/g,(t,n)=>{let i=e[n];return i===void 0?t:String(i)})}function ip(r){return r.trim().replace(/_/g,"-").toLowerCase()}var Ea="Quest",XC={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}},ks=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(Ea)?.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(Ea,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(Ea,i.data),this.ctx.emitter.emit("quest:definitionsLoaded",i.data)),i}getUserQuestState(e=true,t){return this.ctx.cache.read(XC,()=>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 sp=zod.z.object({}).passthrough().transform(r=>r);var eS=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),tS=zod.z.object({Schedule:zod.z.array(eS).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),nS=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(),iS=zod.z.object({Milestones:J.nullish()}).passthrough(),qa=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:zt.nullish(),TokenSources:zod.z.array(mt).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),Presets:iS.nullish(),BonusWindow:tS.nullish()}).passthrough(),sS=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:qa.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rS=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:qa.nullish(),Events:zod.z.array(sS).nullish(),Gate:ee.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),oS=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),aS=zod.z.object({Milestones:zod.z.record(zod.z.string(),zn).nullish()}).passthrough(),zs=zod.z.object({Definitions:zod.z.record(zod.z.string(),rS).nullish(),Settings:oS.nullish(),Presets:aS.nullish()}).passthrough(),lS=zod.z.object({Type:Yn,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:qa.nullish(),Progress:sp.nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:Ve.nullish(),BonusWindow:nS.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),Ms=zod.z.object({ActiveEvents:zod.z.array(lS).nullish()}).passthrough(),rp=zod.z.object({Tokens:zod.z.record(zod.z.string(),sp).nullish()}),Ua=zod.z.object({Type:Yn.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),La=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()}),uS=zod.z.object({Type:Yn.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),Ba=zod.z.array(Oe(La)),op=zod.z.array(Oe(Ua)),ap=zod.z.array(Oe(uS)),yt={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var lp="TimedEvent",up={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}},Os=class{constructor(e){this.ctx=e;e.cache.bindLoginView(up,{schema:Ms,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(up,()=>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(lp,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(lp,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 cS=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(),ai=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:Q.nullish(),CycleEndUtc:u.nullish(),TopUsers:zod.z.array(cS).nullish(),BracketID:zod.z.string().nullish()}),pS=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(),Es=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(pS).nullish()}),qs=zod.z.object({LeaderboardID:zod.z.string(),NewScore:Q,CycleVersion:zod.z.number()}),Us=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Ls=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish()}),cp=zod.z.array(Oe(ai)),Bs=zod.z.array(Oe(Es)),pp=zod.z.array(Oe(Us)),hp=zod.z.array(Oe(Ls)),dp=zod.z.array(Oe(qs)),hS=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:Oe(Us).nullish(),Milestones:zod.z.array(Oe(Ls)).nullish()}),mp=zod.z.array(hS),dS=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:Oe(ai).nullish(),Progress:Oe(Es).nullish()}),fp=zod.z.array(dS),mS=zod.z.string(),gp=zod.z.object({Rank:zod.z.string().nullish(),Rewards:$.nullish(),SeasonTierRewards:ga.nullish()}).passthrough(),fS=zod.z.object({RankRewards:zod.z.array(gp).nullish()}).passthrough(),gS=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),yS=zod.z.object({Milestones:J.nullish(),RankRewards:J.nullish()}).passthrough(),RS=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:mS.nullish(),Schedule:Ce.nullish(),ChainEvents:zod.z.array(gS).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(gp).nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),Presets:yS.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(mt).nullish()}).passthrough(),CS=zod.z.object({Milestones:zod.z.record(zod.z.string(),zn).nullish(),RankRewards:zod.z.record(zod.z.string(),fS).nullish()}).passthrough(),Gs=zod.z.object({Definitions:zod.z.record(zod.z.string(),RS).nullish(),Presets:CS.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 yp="Leaderboard",Rp={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"]},Ns=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Rp,{schema:Bs,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(yp,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(yp,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(Rp,()=>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 Ga=zod.z.object({}).passthrough().transform(r=>r),_s=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>bp).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:Q.nullish(),UserState:Ga.nullish(),NextTier:zod.z.lazy(()=>xp).nullish()}).passthrough(),Cp=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()}),Na=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:O.nullish(),Inventory:K.nullish()}),Sp=Mt(Na);var xp=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(),bp=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(xp).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var SS=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Ce.nullish(),Seasons:zod.z.array(bp).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:ee.nullish()}).passthrough(),Fs=zod.z.object({Chains:zod.z.record(zod.z.string(),SS).nullish()}).passthrough(),Yt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Dp="Season",Ip={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}},Vs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ip,{schema:_s,apply:(t,n)=>this.applyActiveSeason(n??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Dp,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(Dp,i.data),this.ctx.emitter.emit("season:definitionsLoaded",i.data)),i}getActiveSeason(e,t){return e?this.ctx.cache.read(Ip,()=>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 Pp="Premium",js=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Pp,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(Pp,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 Ws=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()}),li=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(),Ws).nullish(),UpdatedAt:u.nullish()}).passthrough(),vp=zod.z.object({Characters:zod.z.record(zod.z.string(),li).nullish(),SelectedCharacterID:zod.z.string().nullish()}),_a=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()}),Fa=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Ap=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Ws).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(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),xS=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),wp=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),xS).nullish(),Inventory:K.nullish()}),Va=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:O.nullish()}),kp=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:Ws.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),zp=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Ws.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Mp=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),bS=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()}),DS=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(bS).nullish()}),Op=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),DS).nullish()}),Ep=zod.z.object({ServerTimeUtc:u,SelectedCharacterID:zod.z.string().nullish()}),qp=Mt(Va),Up=Mt(Fa),Lp=Mt(_a),ja=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),Bp=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(ja).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),IS=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(ja).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(),Gp=zod.z.object({Slots:zod.z.record(zod.z.string(),IS).nullish()}).passthrough(),Np=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(),PS=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),vS=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:de.nullish()}).passthrough(),AS=zod.z.object({Stats:J.nullish(),Levels:J.nullish(),Equipment:J.nullish()}).passthrough(),_p=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:de.nullish(),CostCurve:Je.nullish()}).passthrough(),Wa="@skin";function TS(r){return !!r&&r.startsWith("@")}var wS=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),kS=zod.z.object({PriceOptions:de.nullish(),Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),zS=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(ja).nullish()}).passthrough(),MS=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Np.nullish(),Item:wS.nullish(),Sale:kS.nullish(),Requirements:zS.nullish()}).passthrough(),OS=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),MS).nullish()}).passthrough(),ES=zod.z.object({CharacterID:zod.z.string(),Identity:Np.nullish(),Classification:PS.nullish(),Unlock:vS.nullish(),Presets:AS.nullish(),Equipment:Gp.nullish(),Stats:zod.z.record(zod.z.string(),Bp).nullish(),RankLadder:_p.nullish(),RankStatCurve:Je.nullish(),StatMaxLevelCurve:Je.nullish(),Skins:OS.nullish()}).passthrough(),qS=zod.z.object({Stats:zod.z.record(zod.z.string(),Bp).nullish()}).passthrough(),US=zod.z.object({RankLadder:_p.nullish()}).passthrough(),LS=zod.z.object({Equipment:Gp.nullish()}).passthrough(),BS=zod.z.object({Stats:zod.z.record(zod.z.string(),qS).nullish(),Levels:zod.z.record(zod.z.string(),US).nullish(),Equipment:zod.z.record(zod.z.string(),LS).nullish()}).passthrough(),Hs=zod.z.object({Definitions:zod.z.record(zod.z.string(),ES).nullish(),Presets:BS.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"},GS="SKIN_ALREADY_OWNED";var Ha="Character",Ks=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Ha)?.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(Ha,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(Ha,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,Wa,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 Fp="Match",Qs=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(Fp,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(Fp,i.data),this.ctx.emitter.emit("match:definitionsLoaded",i.data)),i}};var NS="Challenge",$s=class{constructor(e){this.ctx=e;}ctx;lastState=null;get definitions(){return this.ctx.cache.configSection(NS)??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 Vp="Craft",Js=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Vp,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(Vp,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"},jp=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),fn={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function ui(r){return r!==fn.Pending&&r!==fn.Running}var _S={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 FS(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var VS=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),jS=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),Zs=zod.z.object({CreditsConfirmation:ye.nullish(),GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:jp.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(VS).nullish(),Error:jS.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()}),Wp=zod.z.object({Data:zod.z.array(Zs).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),WS=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(),At=zod.z.record(zod.z.string(),zod.z.string()),HS=zod.z.object({Key:zod.z.string().nullish(),Role:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),Label:At.nullish()}).passthrough(),KS=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:At.nullish(),Placeholder:At.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string().nullish(),Label:At.nullish()}).passthrough()).nullish()}).passthrough(),Hp=zod.z.object({Key:zod.z.string(),Kind:zod.z.string().nullish(),Name:At.nullish(),Hint:At.nullish(),Unit:At.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string(),Name:At.nullish(),Group:zod.z.string().nullish()}).passthrough()).nullish(),Groups:zod.z.array(zod.z.object({Key:zod.z.string(),Name:At.nullish()}).passthrough()).nullish(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),Step:zod.z.number().nullish()}).passthrough(),Kp=zod.z.object({PriceOptions:de.nullish()}).passthrough(),QS=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:At.nullish(),Description:At.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(HS).nullish(),Variables:zod.z.array(KS).nullish(),Settings:zod.z.array(Hp).nullish()}).passthrough(),$S=zod.z.object({Modality:jp.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(WS).nullish(),AllowFreePrompt:zod.z.boolean().nullish(),PlatformTemplateId:zod.z.string().nullish(),PlatformTemplate:QS.nullish(),Settings:zod.z.array(Hp).nullish(),FreePerDay:zod.z.number().nullish(),FreeLeftToday:zod.z.number().nullish()}).passthrough(),Qp=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),$S).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 $p="AI",JS=/^[A-Za-z0-9_-]{1,128}$/,ZS=2e3,YS=5e3,XS=30*6e4;function ex(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 Ys=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection($p,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($p,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 ui(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??XS),s=Math.max(1,t.intervalMs??ZS),o=Math.max(s,t.maxIntervalMs??YS);for(;!ui(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 ex(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,ui(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&&!JS.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 Ka="Collection",Xs=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(Ka),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(Ka,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(Ka,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 tx=zod.z.object({}).passthrough().transform(r=>r),nx={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},ix={Active:"Active",Left:"Left",Replaced:"Replaced"},sx=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),rx=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ne.nullish(),BuildObjectsProgress:sx.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(),ox=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(),ax=zod.z.object({Objects:zod.z.array(ox).nullish()}).passthrough(),Jp=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(rx).nullish(),BuildObjectsState:ax.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),Zp=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>Yp).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),lx=zod.z.string(),Qa=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(),ux=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(),cx=zod.z.object({Objects:zod.z.array(ux).nullish(),PriceOptions:de.nullish(),SpinnerTable:zod.z.array(Qa).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),Yp=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:lx.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:cx.nullish(),GrandPrize:$.nullish()}).passthrough(),px=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Ce.nullish(),Events:zod.z.array(Yp).nullish(),Gate:ee.nullish()}).passthrough(),er=zod.z.object({ServerTimeUtc:u.nullish(),UserState:tx.nullish(),ActiveGroup:Jp.nullish()}),$a=zod.z.object({ServerTimeUtc:u.nullish(),Group:Jp.nullish(),SecondsRemaining:Q.nullish()}),Xp=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Resources:O.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:Qa.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(Qa).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:Q.nullish(),MaxProgress:Q.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),Ja=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),eh=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),tr=zod.z.object({Chains:zod.z.record(zod.z.string(),px).nullish()}).passthrough(),Tt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var th="CoopEvent",nh={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},nr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(nh,{schema:er,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(th,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(th,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(nh,()=>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 hx={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},dx={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},mx=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(),fx=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),ih=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(),mx).nullish(),Tracks:zod.z.record(zod.z.string(),fx).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),gx=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:ih.nullish(),NextCycleStartsAtUtc:u.nullish(),LastUpdatedUtc:u.nullish(),DismissSkipAvailableAtUtc:u.nullish(),LastDismissedAtUtc:u.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),yx=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),Rx=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(),yx).nullish()}).passthrough(),Cx=zod.z.object({Slots:zod.z.record(zod.z.string(),gx).nullish(),OfferHistory:zod.z.record(zod.z.string(),Rx).nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),Sx={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},xx={Eq:"Eq",Gte:"Gte",Lte:"Lte"},bx=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),ir=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(),sh=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),rh=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),Dx=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Behaviour:J.nullish()}).passthrough(),Ix=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:ir.nullish(),Availability:sh.nullish(),Behaviour:rh.nullish(),Queue:zod.z.array(bx).nullish(),Presets:Dx.nullish()}).passthrough(),Px=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),vx=zod.z.object({RewardedVideo:Px.nullish()}).passthrough(),Ax=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),Tx=zod.z.object({Identity:J.nullish(),Graph:J.nullish(),Milestones:J.nullish()}).passthrough(),wx=zod.z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish()}).passthrough(),kx=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),zx=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(),Mx=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(Ax).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),oh=zod.z.object({Options:de.nullish()}).passthrough(),ah=zod.z.object({Grants:$.nullish(),TrackChanges:zod.z.array(kx).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),Ox=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:ir.nullish(),Pricing:oh.nullish(),Reward:ah.nullish(),Action:vx.nullish(),UnlockRules:Mx.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:wx.nullish()}).passthrough(),lh=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(Ox).nullish(),Tracks:zod.z.array(zx).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),uh=zod.z.object({Milestones:zod.z.record(zod.z.string(),Ve).nullish(),ClaimMode:zod.z.string().nullish(),Token:zt.nullish()}).passthrough(),ch=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:ir.nullish(),Graph:lh.nullish(),Milestones:uh.nullish(),Presets:Tx.nullish()}).passthrough(),Ex=zod.z.object({Identity:zod.z.record(zod.z.string(),ir).nullish(),Availability:zod.z.record(zod.z.string(),sh).nullish(),Behaviour:zod.z.record(zod.z.string(),rh).nullish(),Graph:zod.z.record(zod.z.string(),lh).nullish(),Milestones:zod.z.record(zod.z.string(),uh).nullish(),Pricing:zod.z.record(zod.z.string(),oh).nullish(),Reward:zod.z.record(zod.z.string(),ah).nullish()}).passthrough(),Za=zod.z.object({Slots:zod.z.record(zod.z.string(),Ix).nullish(),Offers:zod.z.record(zod.z.string(),ch).nullish(),Presets:Ex.nullish()}).passthrough(),ph=zod.z.object({DealOfferDefinitions:Za.nullish()}),hh=zod.z.object({DealOffers:Cx.nullish()}),qx=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(),Ux=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:ch.nullish(),ActivationState:ih.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:u.nullish(),Cost:Gt.nullish(),Milestone:qx.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),sr=zod.z.object({Slots:zod.z.array(Ux).nullish()}),dh=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()}),mh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),fh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),gh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),yh=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()}),Et={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var Lx="DealOffer",Rh={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},rr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Rh,{schema:sr,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(Lx,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(Rh,()=>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 Ch="Referral",or=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ch,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(Ch,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 Sh=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}),xh=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}),bh=zod.z.object({ServerTimeUtc:u,SpendID:zod.z.string(),Resources:O.nullish()}),ci={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},Bx={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},Dh=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),Gx={Automatic:"Automatic",Manual:"Manual"},Nx=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),_x=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(),Fx=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),Vx=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),jx=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(),Ih=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:Nx.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(jx).nullish()}).passthrough(),Ph=zod.z.object({CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough(),Wx=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:_x.nullish(),Recharge:Fx.nullish(),Conversion:Ih.nullish(),Permissions:Vx.nullish(),Audit:Ph.nullish(),Status:Dh.nullish()}).passthrough(),Hx=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(),Kx=zod.z.object({DailyWithdrawUsd:ne.nullish(),MonthlyWithdrawUsd:ne.nullish(),KycRequiredAboveUsd:ne.nullish()}).passthrough(),Qx=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),$x=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(),Ya=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(Hx).nullish(),Limits:Kx.nullish(),Permissions:Qx.nullish(),Conversion:Ih.nullish(),Audit:Ph.nullish(),Status:Dh.nullish(),ServerGrantPolicy:$x.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),Jx=zod.z.object({SpendID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),PriceOptions:zod.z.record(zod.z.string(),cs).nullish()}).passthrough(),ar=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),Wx).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),Ya).nullish(),Spends:zod.z.record(zod.z.string(),Jx).nullish()}).passthrough(),Zx={Marketplace:"Marketplace",MailboxTransfer:"MailboxTransfer",Match:"Match",Workshop:"Workshop"},Yx={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(),vh=zod.z.object({Pending:zod.z.array(Rt).nullish(),Released:zod.z.array(Rt).nullish(),Voided:zod.z.array(Rt).nullish()}).passthrough();var Xx={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Ah=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),eb={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},tb=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),nb={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},ib=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),pt={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},sb={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"},rb=100,ob=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),Th=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(),ab=zod.z.object({Texts:zod.z.record(zod.z.string(),ob).nullish(),Category:Ah.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:Th.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),lb=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(),ub=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(),cb=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(ub).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(),wh=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(),ab).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),lb).nullish(),Transfer:cb.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(),pb=zod.z.object({MessageID:zod.z.string(),Source:tb,Category:Ah,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:Th.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(),hb=zod.z.object({MessageID:zod.z.string(),Module:ib,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(),Xa=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),kh=zod.z.object({ServerTimeUtc:u.nullish(),Messages:zod.z.array(pb).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(hb).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),lr=zod.z.object({ServerTimeUtc:u.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),el=zod.z.object({ServerTimeUtc:u.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(Xa).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),db=zod.z.object({MessageID:zod.z.string(),Rewards:pe.nullish(),Instances:zod.z.array(Mn).nullish(),HeldPayout:Rt.nullish()}).passthrough(),ur=zod.z.object({ServerTimeUtc:u.nullish(),Claimed:zod.z.array(db).default([]),Failed:zod.z.array(Xa).default([]),Resources:O.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),zh=zod.z.object({ServerTimeUtc:u.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(Xa).default([]),Resources:O.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough(),Mh=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(),Oh=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 tl="Mailbox",nl={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},cr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(nl,{schema:lr,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(nl,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(tl)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(tl,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(tl,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(nl,()=>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 mb={Head:"Head",Torso:"Torso",Legs:"Legs"},pr=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),fb={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},il=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),qh=zod.z.object({AttackTarget:pr,DefenseTarget:pr});var gb=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),yb=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:pr.nullish(),DefenseZone:pr.nullish(),HitType:gb.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),Rb=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:u,ExpiresAt:u.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Eh=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:li.nullish(),BattleStrategy:zod.z.array(qh).nullish(),UnstackableItems:zod.z.record(zod.z.string(),Cb).nullish(),Stats:Rb.nullish()}).passthrough(),pi=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:pe.nullish(),NetReward:pe.nullish(),BattleLog:zod.z.array(yb).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:Eh.nullish(),P2BattleProfile:Eh.nullish()}).passthrough(),Uh=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(qh).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:il.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:u.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:u.nullish()}).passthrough(),Lh=zod.z.object({Status:il,MatchID:zod.z.string(),Entry:pe.nullish(),Resources:O.nullish()}),Bh=zod.z.object({Match:Uh.nullish()}),Gh=zod.z.object({MatchID:zod.z.string(),Status:il,Resources:O.nullish()}),Nh=zod.z.object({Battle:pi.nullish(),Resources:O.nullish(),ResourcesDual:Nt.nullish(),HeldPayout:Rt.nullish()}),sl=zod.z.object({Matches:zod.z.array(Uh).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),qt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var Sb=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var xb=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),bb=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(),Db=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),Ib=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:Db.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),Pb=zod.z.object({Kind:xb.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(),vb=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(Pb).nullish()}).passthrough(),gn=zod.z.object({Terms:zod.z.array(vb).nullish()}).passthrough(),Ab=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(),_h=zod.z.object({StatMapping:bb.nullish(),Combat:Ib.nullish(),Formula:Ab.nullish()}).passthrough(),Tb=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),hi=zod.z.object({Kind:Sb.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:zi.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),Fh=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(hi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Vh=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(),wb=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:Tb.nullish(),Entry:Fh.nullish(),Creation:Vh.nullish(),Settings:_h.nullish()}).passthrough(),kb=zod.z.object({Rules:zod.z.record(zod.z.string(),wb).nullish(),Defaults:_h.nullish(),EntryDefaults:Fh.nullish(),CreationDefaults:Vh.nullish()}).passthrough(),rl=zod.z.object({InstantBattle:kb.nullish()}).passthrough(),jh=rl;var zb={Open:"Open",Request:"Request",InviteOnly:"InviteOnly"},Mb=zod.z.enum(["Open","Request","InviteOnly"]).catch("Open"),Ob={Application:"Application",Invite:"Invite"},Eb={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"},qb={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"},Ub={Duel:"Duel",Battle:"Battle",League:"League",War:"War"},Lb={Ally:"Ally",Pact:"Pact",Enemy:"Enemy",None:"None"},hr="clan",yn=zod.z.array(zod.z.string()).nullish(),Z=zod.z.number().nullish(),Bb=zod.z.record(zod.z.string(),zod.z.number()).nullish(),Gb=zod.z.object({NounKey:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SortOrder:Z}).passthrough(),Nb=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(),_b=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(),Fb=zod.z.object({Rank:zod.z.number().catch(0),NameKey:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),MaxCount:Z,Permissions:yn}).passthrough(),Vb=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(kt.passthrough()).nullish(),Funding:zod.z.string().nullish(),MaxPerDonor:Z,MaxHelps:Z,MaxItemLevel:Z,MinMembershipHoursToDonate:Z}).passthrough(),jb=zod.z.object({Enabled:zod.z.boolean().nullish(),Identity:Gb.nullish(),Create:Nb.nullish(),Membership:_b.nullish(),Roles:zod.z.object({Roles:zod.z.record(zod.z.string(),Fb).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(),Vb).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:kt.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:Bb,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:kt.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(),Wb=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Kinds:zod.z.record(zod.z.string(),jb).nullish(),RefreshSeconds:Z}).passthrough(),al=zod.z.record(zod.z.string(),zod.z.string()).nullish(),ol=zod.z.record(zod.z.string(),zod.z.number()).nullish(),tn=zod.z.object({ClanID:zod.z.string(),KindID:zod.z.string().catch(hr),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:al,JoinMode:Mb,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:ol,Perks:ol,Modifiers:zod.z.array(zod.z.object({}).passthrough()).nullish(),Treasury:ol,RecommendedProjectID:zod.z.string().nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),CreatedAt:u.nullish(),ActiveAt:u.nullish()}).passthrough(),ll=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(),Hb=zod.z.object({KindID:zod.z.string(),Clan:tn.nullish(),Membership:ll.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(),Hh=zod.z.object({ServerTimeUtc:u.nullish(),RefreshSeconds:zod.z.number().catch(30),Kinds:zod.z.array(Hb).catch([])}).passthrough(),ul=zod.z.object({ServerTimeUtc:u.nullish(),Clans:zod.z.array(tn).catch([]),NextCursor:zod.z.string().nullish()}).passthrough(),Kh=zod.z.object({ServerTimeUtc:u.nullish(),Clan:tn,Membership:ll.nullish(),Applied:zod.z.boolean().catch(false)}).passthrough(),Qh=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(),$h=zod.z.object({ServerTimeUtc:u.nullish(),ClanID:zod.z.string().nullish(),Members:zod.z.array(Qh).catch([])}).passthrough(),Wh=zod.z.object({Rank:zod.z.number().catch(0),Value:zod.z.number().catch(0),Clan:tn}).passthrough(),Jh=zod.z.object({ServerTimeUtc:u.nullish(),Metric:zod.z.string().nullish(),Slice:zod.z.string().nullish(),Rows:zod.z.array(Wh).catch([]),Mine:Wh.nullish()}).passthrough(),Kb=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:Qh.nullish(),InviterUserID:zod.z.string().nullish(),Message:zod.z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),cl=zod.z.object({ServerTimeUtc:u.nullish(),Items:zod.z.array(Kb).catch([])}).passthrough(),Qb=zod.z.object({Type:zod.z.string().catch(""),ActorUserID:zod.z.string().nullish(),TargetUserID:zod.z.string().nullish(),Params:al,At:u.nullish()}).passthrough(),Zh=zod.z.object({ServerTimeUtc:u.nullish(),Entries:zod.z.array(Qb).catch([]),NextCursor:zod.z.string().nullish()}).passthrough(),Yh=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:kt.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(),Xh=zod.z.object({ServerTimeUtc:u.nullish(),Requests:zod.z.array(Yh).catch([])}).passthrough(),$b=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(),ed=zod.z.object({ServerTimeUtc:u.nullish(),GiftLevel:zod.z.number().catch(0),GiftPoints:zod.z.number().catch(0),NextGiftLevelPoints:Z,Gifts:zod.z.array($b).catch([])}).passthrough(),dr=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(),td=zod.z.object({ServerTimeUtc:u.nullish(),Rewards:zod.z.array(dr).catch([])}).passthrough(),nd=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(),id=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(),sd=zod.z.object({ServerTimeUtc:u.nullish(),Clan:tn.nullish(),Membership:ll.nullish(),Request:Yh.nullish(),Resources:O.nullish(),Inventory:K.nullish(),Done:zod.z.array(zod.z.string()).nullish(),Failed:al,WarAttack:nd.nullish(),WarBattle:pi.nullish(),Relation:id.nullish()}).passthrough(),rd=zod.z.object({ServerTimeUtc:u.nullish(),Definitions:Wb.nullish(),DefaultKindID:zod.z.string().nullish()}).passthrough(),Jb=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(),Zb=zod.z.object({PurchaseID:zod.z.string(),ExpiresAt:u.nullish(),Modifiers:zod.z.array(Jb).nullish()}).passthrough(),Yb=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(),od=zod.z.object({ServerTimeUtc:u.nullish(),Balances:zod.z.record(zod.z.string(),zod.z.number()).catch({}),Buffs:zod.z.array(Zb).catch([]),Ledger:zod.z.array(Yb).catch([]),NextCursor:zod.z.string().nullish(),MyDepositsToday:zod.z.record(zod.z.string(),zod.z.number()).catch({})}).passthrough(),Xb=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(),ad=zod.z.object({ServerTimeUtc:u.nullish(),RecommendedProjectID:zod.z.string().nullish(),Projects:zod.z.array(Xb).catch([])}).passthrough(),eD=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(dr).catch([])}).passthrough(),ld=zod.z.object({ServerTimeUtc:u.nullish(),Activities:zod.z.array(eD).catch([])}).passthrough(),tD=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(),nD=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(tD).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(),iD=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(nD).catch([]),Rewards:zod.z.array(dr).catch([])}).passthrough(),ud=zod.z.object({ServerTimeUtc:u.nullish(),Boards:zod.z.array(iD).catch([])}).passthrough(),sD=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(dr).catch([])}).passthrough(),cd=zod.z.object({ServerTimeUtc:u.nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),Competitions:zod.z.array(sD).catch([])}).passthrough(),rD=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(),oD=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(),pd=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(rD).catch([]),War:zod.z.array(oD).nullish(),MyAttacks:zod.z.array(nd).nullish()}).passthrough(),hd=zod.z.object({ServerTimeUtc:u.nullish(),CanManage:zod.z.boolean().catch(false),Relations:zod.z.array(id).catch([]),Limits:zod.z.record(zod.z.string(),zod.z.number()).catch({}),Counts:zod.z.record(zod.z.string(),zod.z.number()).catch({})}).passthrough(),aD=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(),dd=zod.z.object({ServerTimeUtc:u.nullish(),Revenges:zod.z.array(aD).catch([]),TakenToday:zod.z.number().catch(0),DailyLimit:zod.z.number().catch(0)}).passthrough(),lD=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(),md=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:lD.nullish()}).passthrough();var pl="Clan",mr=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(pl)}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]??hr]}async getDefinitions(e){let t=this.ctx.cache.configSection(pl,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(pl,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"},uD={TooManyUsers:"AVATAR_TOO_MANY_USERS",Disabled:"AVATAR_DISABLED",NotForSale:"AVATAR_ITEM_NOT_FOR_SALE"},fr=50,gr=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(),cD=48,pD=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(),fd=zod.z.object({id:zod.z.string(),slot:zod.z.string()}).passthrough(),gd=zod.z.object({Enabled:zod.z.boolean(),Avatars:zod.z.array(pD).nullish().transform(r=>r??[]),Items:zod.z.record(zod.z.string(),fd).nullish().transform(r=>r??{})}).passthrough(),hD=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(),yd=zod.z.object({Enabled:zod.z.boolean(),Offers:zod.z.array(hD).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(),fd).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(),Rd=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 dD="Avatar",yr=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(dD)??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+=fr){let p=s.slice(o,o+fr),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?mD(i,e.Items):[]}),t.push(n.UserID);}t.length>0&&this.ctx.emitter.emit("avatar:changed",{userIDs:t});}};function mD(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 Rr={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},hl="idos-app",Cd=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()}),Sd=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 fD=new Set(["CANCELLED","DECLINED","CLOSED"]),gD=45e3,yD=r=>new Promise(e=>setTimeout(e,r)),Cr=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!==hl&&(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:fD.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()+gD;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 yD(o);}}};var jt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},RD={Client:"Client",Server:"Server",System:"System"},CD=zod.z.enum(["Client","Server","System"]).catch("Client"),dl=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:CD.nullish(),ExpiresAt:u.nullish()}).passthrough(),Sr=zod.z.record(zod.z.string(),dl),xd=zod.z.object({Version:zod.z.number().nullish(),Private:Sr.nullish(),Public:Sr.nullish(),ReadOnly:Sr.nullish()}),ml=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Sr.nullish()}),fl=zod.z.object({ServerTimeUtc:u.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),SD=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),bd=zod.z.object({ServerTimeUtc:u.nullish(),Results:zod.z.array(SD).nullish()}),Dd=zod.z.object({ServerTimeUtc:u.nullish(),DeletedCount:zod.z.number().nullish()}),Id=zod.z.object({Results:zod.z.array(ml).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),xD={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},bD=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),DD=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:bD.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),xr=zod.z.object({Keys:zod.z.record(zod.z.string(),DD).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(),wt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var ID={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},PD={Title:"Title",Platform:"Platform"},Pd=zod.z.object({UserID:zod.z.string(),PublicData:Ne.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()});var vD=zod.z.object({StageLevel:zod.z.number().nullish(),SpecialPlayedCount:zod.z.number().nullish()}),vd=zod.z.object({UserID:zod.z.string(),IsSelf:zod.z.boolean().nullish(),PublicData:Ne.nullish(),Characters:zod.z.record(zod.z.string(),li).nullish(),StrongestCharacterID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),Board:vD.nullish(),PublicCustomData:zod.z.record(zod.z.string(),dl).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 di=zod.z.object({Friends:zod.z.array(Pd).nullish()}),AD=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),mi=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:Pd.nullish(),Counters:AD.nullish()}),TD={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},wD={Like:"Like",Favorite:"Favorite"},kD={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},zD={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},MD={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived",ArenaDefeat:"ArenaDefeat"},OD=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),ED=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(OD).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(),Ad=zod.z.object({Items:zod.z.array(ED).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(),fi=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),qD=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:qD.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),Td=zod.z.object({Items:zod.z.array(nn).nullish()}).passthrough(),gl={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},UD=zod.z.object({UserID:zod.z.string(),PublicData:Ne.nullish(),Mutual:zod.z.boolean().nullish(),Since:u.nullish()}).passthrough(),br=zod.z.object({Items:zod.z.array(UD).nullish(),...gl}).passthrough(),LD=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:u.nullish()}).passthrough(),wd=zod.z.object({Items:zod.z.array(LD).nullish(),...gl}).passthrough(),Dr=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(),kd=zod.z.object({Items:zod.z.array(Dr).nullish(),...gl,TotalCount:zod.z.number().nullish()}).passthrough(),zd=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),Md=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),Od=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(),BD="FRIENDS_FROM_PLATFORM",GD={Off:"Off",Default:"Default",Always:"Always"},ND={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Ed=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 yl={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Ir=class{constructor(e){this.ctx=e;e.cache.bindLoginView(yl,{schema:fi,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(yl,()=>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(yl,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 qd="TimedBoost";function _D(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Pr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(qd,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(qd,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(!_D(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 FD="UserCustomData";function Ud(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var vr=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(FD,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(!Ud(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(!Ud(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 VD="TitleCustomDataDefinitions",Ld=50;function jD(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function Rl(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function WD(r){let e={};for(let[t,n]of Object.entries(r))Rl(n)||(e[t]=n);return e}var Ar=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(VD,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=>!jD(s)))return h("client",'KeyID must not contain "." or "$".');if(t.length>Ld)return h("client",`At most ${Ld} 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&&!Rl(t))return t.Value;let n=this.staticCache[e];if(n?.Value!=null&&!Rl(n))return n.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=WD(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 Tr=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 HD={Fast:"Fast",Sequential:"Sequential"},KD={Instant:"Instant",Timed:"Timed"};var QD={Hit:"Hit",Blocked:"Blocked"},$D=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),JD=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 ZD=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:$.nullish()}).passthrough(),YD=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(ZD).nullish(),Rate:YD.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 Bd=zod.z.object({}).passthrough().transform(r=>r),Gd=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(),XD=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),eI=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(),tI=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(),nI=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(),Nd=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(),iI=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(),sI=zod.z.object({Tiles:zod.z.record(zod.z.string(),iI).nullish()}).passthrough(),rI=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Ye.nullish(),Tag:zod.z.string().nullish()}).passthrough(),oI=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(rI).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(),aI=zod.z.object({Variants:zod.z.array(oI).nullish()}).passthrough(),lI=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(),uI=zod.z.object({Outcomes:zod.z.array(lI).nullish()}).passthrough(),_d=zod.z.object({PerAdMultiplierRange:Gd.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(),cI=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Ye.nullish()}).passthrough(),pI=zod.z.object({Tiers:zod.z.array(cI).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Ye.nullish()}).passthrough(),hI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Ye.nullish()}).passthrough(),dI=zod.z.object({Reward:Ye.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),mI=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(hI).nullish(),Rate:dI.nullish()}).passthrough(),Fd=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),mI).nullish()}).passthrough(),fI=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:_d.nullish(),Gradation:pI.nullish(),RunStats:Fd.nullish()}).passthrough(),gI=zod.z.object({Choices:zod.z.array(fI).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),yI=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Ye.nullish(),Tag:zod.z.string().nullish()}).passthrough(),RI=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(yI).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),uI).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),gI).nullish()}).passthrough(),Vd=zod.z.object({BaseAttackReward:$.nullish(),BaseRaidReward:$.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Nd).nullish(),HeistGridBonusConfig:aI.nullish(),StageOperations:RI.nullish(),TileLandingMultiplier:Gd.nullish(),EconomyOverride:nI.nullish()}).passthrough(),CI=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(Nd).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:Vd.nullish()}).passthrough(),SI=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(),xI=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(),bI=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(),wr=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(),sI).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),Vd).nullish(),StagesByLevel:zod.z.record(zod.z.string(),CI).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:tI.nullish(),Dice:XD.nullish(),Bots:eI.nullish(),Targeting:SI.nullish(),BotRaids:xI.nullish(),RewardBoost:bI.nullish()}).passthrough(),DI=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(),kr=zod.z.object({Board:wr.nullish(),CommunityChest:DI.nullish()}).passthrough(),jd=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),pe).nullish()}).passthrough(),II=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:Ne.nullish(),TargetBuildingStates:zod.z.array($D).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:jd.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:_d.nullish(),RunStats:Fd.nullish()}).passthrough(),vI=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(PI).nullish()}).passthrough(),AI=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(),Wd=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:II.nullish(),SpecialModeOffer:vI.nullish(),CommunityChestContribution:AI.nullish()}).passthrough(),zr={Ad:"Ad",Premium:"Premium"},Hd=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(kt).nullish()}).passthrough(),Kd=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(),Qd=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:Hd.nullish()}).passthrough(),Cl=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(JD).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:Nt.nullish(),RaidRewardPreview:jd.nullish(),RewardBoost:Hd.nullish()}).passthrough(),$d=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(),Jd=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(),Zd=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(),TI=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),Yd=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(TI).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:$.nullish()}).passthrough(),wI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Xd=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),kI={Active:"Active",Left:"Left",Replaced:"Replaced"},zI=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),MI=zod.z.object({CurrentProgress:Q.nullish(),MaxProgress:Q.nullish()}).passthrough(),OI=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(),$u).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:zI.nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),em=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(OI).nullish(),SharedProgress:MI.nullish(),Status:Xd.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),EI=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:Xd.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:u.nullish()}).passthrough(),qI=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(EI).nullish()}).passthrough(),tm=zod.z.object({ServerTimeUtc:u.nullish(),UserState:qI.nullish(),ActiveGroup:em.nullish(),SecondsRemaining:Q.nullish()}),nm=zod.z.object({ServerTimeUtc:u.nullish(),Group:em.nullish(),SecondsRemaining:Q.nullish()}),Sl=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()}),im=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 UI=15,LI="GameLoop",sm="BoardDefinition",gi="InventoryV2",BI="GameLoop",Mr=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(LI,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let n=this.ctx.cache.configSection(sm,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(sm,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[gi]!==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([gi]),this.ctx.cache.ensureState([gi]),this.ctx.emitter.emit("user:changedElsewhere",{containers:[gi]}))),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=xc(new Date,UI);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([gi,BI],{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=zr.Ad){let n=this.ctx.auth.context;if(!n)return l;let i=t===zr.Premium,s={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_${i?"vip":"ad"}_${n.userID}_${F()}`,...i?{BoostMode:zr.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 Or=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 GI={EVM:"EVM",Solana:"Solana"},NI=zod.z.enum(["EVM","Solana"]).catch("EVM"),_I={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},FI=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),VI={Token:"Token",Nft:"Nft"},rm=zod.z.enum(["Token","Nft"]).catch("Token"),jI={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},WI=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),HI={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},KI=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),QI={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},xl=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),om={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Er(r){let e=r?.trim();return e||om.GameTopUp}var $I={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},am=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),JI=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(),lm=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),ZI=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:NI.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:lm.nullish(),NftCollections:zod.z.array(JI).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(),YI=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:lm.nullish()}).passthrough(),XI=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),eP={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},tP=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),um=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:ne.nullish(),BalanceSource:tP.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),nP=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),iP={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},yi=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),sP=zod.z.object({Mode:yi.nullish(),TokenGates:zod.z.array(um).nullish()}).passthrough(),bl=zod.z.object({SystemState:YI.nullish(),Networks:zod.z.record(zod.z.string(),ZI).nullish(),AccountSafety:XI.nullish(),WalletLogin:nP.nullish(),PlayAccess:sP.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),rP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:u.nullish(),LastUsedAt:u.nullish(),LinkType:FI.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),cm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:rm.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:ne.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),oP=zod.z.object({Status:WI.nullish(),Tier:KI.nullish(),VerifiedAt:u.nullish(),ExpiresAt:u.nullish(),RejectedAt:u.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),aP=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(),lP=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(),aP).nullish()}).passthrough(),uP=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(),cP=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(),uP).nullish()}).passthrough(),pP=zod.z.object({Tokens:lP.nullish(),Nfts:cP.nullish()}).passthrough(),Dl=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:ne.nullish(),MinBalance:ne.nullish()}).passthrough(),sn=zod.z.object({Granted:zod.z.boolean(),Mode:yi.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(Dl).nullish()}).passthrough(),hP=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(Dl).nullish()}).passthrough(),dP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),pm=zod.z.object({Mode:yi.nullish(),TokenGates:zod.z.array(um).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(dP).nullish(),Status:sn.nullish()}).passthrough(),mP=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(Dl).nullish()}).passthrough(),fP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:u.nullish()}).passthrough(),gP=zod.z.object({Version:zod.z.number().nullish(),Stats:pP.nullish(),LinkedWallets:zod.z.record(zod.z.string(),rP).nullish(),LastWalletLogin:mP.nullish(),PlayAccess:hP.nullish(),PendingWithdrawals:zod.z.array(cm).nullish(),Kyc:oP.nullish(),FirstActivityAt:u.nullish(),LastActivityAt:u.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(fP).nullish()}).passthrough(),yP=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(),yP).nullish(),PendingAdded:cm.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),RP=zod.z.object({Amount:ne,Frozen:ne,CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough().transform(r=>r),CP=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:am.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:ne.nullish(),Status:xl.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(),SP=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:am.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:ne.nullish(),Status:xl.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(),hm=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Il=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(hm).nullish(),Signature:zod.z.string().nullish()}).passthrough(),Pl=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(hm).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(),dm=zod.z.object({Blockchain:bl.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),Ya).nullish()}).passthrough(),mm=zod.z.object({State:gP.nullish(),CryptoBalances:zod.z.record(zod.z.string(),RP).nullish()}).passthrough(),fm=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(),gm=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(),ym=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:Il.nullish(),SolanaSignature:Pl.nullish(),StateDelta:_n.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),Rm=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:Il.nullish(),SolanaSignature:Pl.nullish(),StateDelta:_n.nullish(),Inventory:K.nullish()}).passthrough(),Cm=zod.z.object({TokenTransactions:zod.z.array(CP).nullish(),NFTTransactions:zod.z.array(SP).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),vl=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(),Sm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:rm.nullish(),EvmSignature:Il.nullish(),SolanaSignature:Pl.nullish()}).passthrough(),xm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:xl.nullish(),StateDelta:_n.nullish()}).passthrough(),st={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 xP="Blockchain",bm="Blockchain:Definitions",qr=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(bm,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(xP,s.data.Blockchain),this.ctx.data.config.patchSection(bm,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=Er(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=Er(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 bP={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Al=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),DP={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Tl=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),IP={Burn:"Burn",Ledger:"Ledger"},PP=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Lr={Item:"Item",VirtualCurrency:"VirtualCurrency"},wl=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),vP=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:Q.nullish()}).passthrough(),Br=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(hi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),kl=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:Q.nullish(),Sink:PP.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),vP).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),AP=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(),TP=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(),wP=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(),kP=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(),zP=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(),MP=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),zl=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:ee.nullish(),Schedule:Ce.nullish(),PricePolicy:Br.nullish(),Commission:kl.nullish(),Tradability:AP.nullish(),Listings:TP.nullish(),Auctions:wP.nullish(),BuyOrders:kP.nullish(),DirectTrades:zP.nullish(),Matching:MP.nullish()}).passthrough(),Dm=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(),OP=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(Dm).nullish()}).passthrough(),Ur=zod.z.object({LastAt:u.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),EP=zod.z.object({Create:Ur.nullish(),Buy:Ur.nullish(),Sell:Ur.nullish(),Bid:Ur.nullish()}).passthrough(),qP=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),UP=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:qP.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:Al.nullish(),Status:Tl.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:Ne.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:wl.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:Q.nullish(),GoodsInstances:zod.z.array(UP).nullish(),Price:pe.nullish(),Auction:OP.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),LP=zod.z.object({GoodsType:wl.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(Al,Q).nullish()}).passthrough(),Im=zod.z.object({Definitions:zl.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),Ml=zod.z.object({Offers:zod.z.array(Wt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Pm=zod.z.object({Groups:zod.z.array(LP).nullish()}).passthrough(),vm=zod.z.object({Offer:Wt.nullish()}).passthrough(),Ct=zod.z.object({OfferID:zod.z.string().nullish(),Status:Tl.nullish(),Settlement:Nt.nullish(),Resources:O.nullish(),CommissionTaken:pe.nullish(),HeldPayout:Rt.nullish()}).passthrough(),Ri=zod.z.object({OfferID:zod.z.string().nullish(),Offer:Wt.nullish(),Resources:O.nullish(),Matched:zod.z.boolean().nullish(),Settlement:Ct.nullish()}).passthrough(),Am=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:Q.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish()}).passthrough(),Gr=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(Dm).nullish(),Limits:EP.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(),BP=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Al.nullish(),FinalStatus:Tl.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:wl.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(),Tm=zod.z.object({Entries:zod.z.array(BP).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 GP="Marketplace",wm={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"]},Nr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(wm,{schema:Gr,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(GP,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(wm,()=>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=Lr.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Lr.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 _r=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 km=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Fr=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=zm(m.data,m.contentType);return t.set(g,j),{Role:m.role,ContentType:m.contentType,Size:j.size}}),i=e.thumbnail?zm(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)}${km}`)}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)}${km}`)}}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 zm(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 NP={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},_P=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),FP={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Mm=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),VP={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Om=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),jP={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},WP=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),HP={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},KP=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),QP={Count:"Count",Sum:"Sum"},$P=zod.z.enum(["Count","Sum"]).catch("Count"),JP={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},ZP=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),YP={Strict:"Strict",Loose:"Loose"},XP=zod.z.enum(["Strict","Loose"]).catch("Strict"),ev=zod.z.object({Kind:KP,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),tv=zod.z.object({Type:Mm,ItemType:Mm.nullish(),Ref:ev.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:Om.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()}),nv=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Vr=zod.z.object({Mode:WP,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),iv=zod.z.object({Read:zod.z.array(Vr).nullish(),Create:zod.z.array(Vr).nullish(),Update:zod.z.array(Vr).nullish(),Delete:zod.z.array(Vr).nullish()}),Ol=zod.z.object({Cost:pe.nullish(),Grant:pe.nullish()}),sv=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()}),rv=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:_P,Mode:XP.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),tv).nullish(),SortKeys:zod.z.array(nv).nullish(),Access:iv.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:ZP.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:$P,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:Om.optional()})).nullish(),Economy:zod.z.object({OnCreate:Ol.nullish(),OnUpdate:Ol.nullish(),OnDelete:Ol.nullish()}).nullish(),WriteGate:ee.nullish(),PublicViews:zod.z.array(sv).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()}),Em=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),rv).default({})}),ov=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),qm=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(),ov).nullish()}),El=zod.z.object({Item:Fn}),Um=zod.z.object({Items:zod.z.array(Fn).default([]),Missing:zod.z.array(zod.z.string()).default([])}),ql=zod.z.object({Items:zod.z.array(Fn).default([]),NextCursor:zod.z.string().nullish()}),Lm=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),Ul=zod.z.object({Item:Fn,AlreadyExists:zod.z.boolean().optional(),Economy:O.nullish()}),Bm=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:O.nullish()}),Gm=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),Nm=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([])}),_m=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),Fm=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),Vm=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({})}),jm=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(Fn).default([])}),av={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 lv=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Km=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Bl=100,Wm=25,Hm=100;function uv(r,e,t){return {Field:r,Op:e,Value:t}}var jr=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=ht(e)??Ci(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=ht(e);if(i)return Promise.resolve(i);let s=[...new Set(t.filter(o=>Km.test(o)))];return s.length?s.length>Hm?Promise.resolve(h("client",`At most ${Hm} 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=ht(e)??Ll(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??Bl},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=ht(e)??Ll(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=ht(e)??(n.itemID?Ci(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=ht(e)??Ci(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=ht(e)??Ci(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>Wm)return Promise.resolve(h("client",`At most ${Wm} operations per batch.`));let t=e.map(n=>ht(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=ht(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=ht(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=ht(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,Vm);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`,jm);return g.ok?B({pointer:o.data,page:g.data}):g}getPublic(e,t){let n=ht(e)??Ci(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let n=ht(e)??Ll(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 ht(r){return lv.test(r??"")?null:h("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function Ci(r){return Km.test(r??"")?null:h("client",`Item id '${r}' is invalid.`)}function Ll(r){return r.Limit!=null&&(r.Limit<1||r.Limit>Bl)?h("client",`Limit must be 1..${Bl}.`):(r.Where?.length??0)>8?h("client","At most 8 filters per query."):null}var Gl={Open:"Open",Declared:"Declared"},cv=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),pv=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),Qm=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),cv).nullish(),Dimensions:zod.z.array(pv).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"},Ut={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Wr=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,hv={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},dv=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),$m=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(dv).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Nl={LogEvents:"LogEvents"};function Jm(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 Zm(r){let e=typeof navigator>"u"?void 0:navigator,t=Jm(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 mv=25,fv=3e4,Ym=1800*1e3,Xm=500,gv=5,yv=1e3,Rv=3600*1e3,ef="idos_analytics_queue",_l="idos_analytics_pending",Fl="idos_analytics_opt_out",tf="idos_analytics_first_open",nf="idos_analytics_last_activity",sf="idos_analytics_last_context",rf="idos_analytics_owner",Hr=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"||!Wr.test(e)?h("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Cv(e)?h("client",`Event name "${e}" uses a reserved prefix (${Ut.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,Ut.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>=gv)&&(this.pending=null),this.persist(),n)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Fl);return}this.write(Fl,"1"),this.clear();}get isEnabled(){return this.read(Fl)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(rf);e&&t&&t!==e&&this.clear(),e&&this.write(rf,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},fv),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(nf)??"0");this.read(tf)||(this.write(tf,new Date().toISOString()),this.enqueue(rn.FirstOpen,void 0,void 0,true));let t=this.clientContext(),n=this.readJson(sf);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(sf,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Ym)&&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>=Ym&&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()===Gl.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=Sv(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>Xm&&this.queue.splice(0,this.queue.length-Xm),this.touch(),this.persist(),this.started&&this.queue.length>=mv&&this.flush(),B(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},yv));}dropStale(){let e=Date.now()-(Ut.maxEventAgeMs-Rv);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??=Zm({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(ef);Array.isArray(e)&&(this.queue=e.filter(n=>typeof n?.Name=="string").concat(this.queue));let t=this.readJson(_l);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(ef,this.queue),this.pending?this.writeJson(_l,this.pending):this.remove(_l);}touch(){this.write(nf,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 Cv(r){let e=r.toLowerCase();return Ut.reservedPrefixes.some(t=>e.startsWith(t))}function Sv(r){if(!r)return {};let e=Object.keys(r);if(e.length===0)return {};if(e.length>Ut.maxParams)return {error:`Too many parameters: ${e.length}, max ${Ut.maxParams}.`};let t={};for(let n of e){if(!Wr.test(n))return {error:`Invalid parameter name "${n}".`};let i=r[n];typeof i=="string"?t[n]=i.length>Ut.maxStringValueLength?i.slice(0,Ut.maxStringValueLength):i:typeof i=="number"?Number.isFinite(i)&&(t[n]=i):typeof i=="boolean"&&(t[n]=i);}return {params:t}}var xv="idos_experiments",Kr=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 `${xv}:${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 Qr=class extends _{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Nl.LogEvents,e,$m,{silent:true})}};var bv=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(),Dv={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Iv=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),Pv=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(bv).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(Iv).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),of=zod.z.object({Experiments:zod.z.record(zod.z.string(),Pv).nullish()}).passthrough(),vv={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Av=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(),af=zod.z.object({Experiments:zod.z.array(Av).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),Vl={GetExperiments:"GetExperiments"};var $r=class extends _{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Vl.GetExperiments,e,af)}};var Tv={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},lf=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),wv=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),uf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),wv).nullish(),MissingKeyMode:lf.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),kv=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),cf=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:kv.nullish()}).passthrough(),Jr={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},zv=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),pf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:lf.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(zv).nullish()}).passthrough(),hf=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 Si=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:cf.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:vh.nullish()}).passthrough().transform(r=>r),df=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(r=>r),mf=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),ff=zod.z.object({}).passthrough().transform(r=>r),gf=zod.z.object({}).passthrough().transform(r=>r),yf=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(),Rf=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 Cf=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:Si.nullish()}),Sf=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,RefreshToken:zod.z.string(),RefreshTokenExpiration:u.nullish(),PlayAccess:sn.nullish()}),Mv=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),xf=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:yi.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:Mv.nullish()}).passthrough(),bf=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(),Df=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:u.nullish(),PlayAccess:sn.nullish()}).passthrough(),If=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()}),Pf=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 Zr=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,Cf,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(He.RefreshSession),e,Sf,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(He.GetAuthOptions),e,xf,{ticket:null})}linkWallet(e){return this.ctx.transport.post(on(this.ctx.settings.titleID,"Authentication",He.LinkWallet,e.UserID??""),e,bf,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(on(this.ctx.settings.titleID,"Authentication",He.UnlinkWallet,e.UserID??""),e,Df,{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,If,{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,Pf,{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 Yr=class extends _{constructor(e){super(e,"User");}getClientState(e){return this.send(St.GetClientState,e,Si)}getClientStateExcept(e){return this.send(St.GetClientStateExcept,e,Si)}getStateVersions(e){return this.send(St.GetStateVersions,e,df)}getUserState(e){return this.send(St.GetUserState,e,mf)}getInventory(e){return this.send(St.GetInventory,e,ff)}getEventTokens(e){return this.send(St.GetEventTokens,e,gf)}getUsageTime(e){return this.send(St.GetUsageTime,e,yf)}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,Rf)}};var Xr=class extends _{constructor(e){super(e,"Currency");}convert(e){return this.send(ci.Convert,e,Sh)}spend(e){return this.send(ci.Spend,e,bh)}cryptoConvert(e){return this.send(ci.CryptoConvert,e,xh)}};var Ov=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),jl=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(Ov).nullish()}),vf=zod.z.array(Oe(jl)),eo={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Ev={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},qv=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Uv={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Lv=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Bv=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),Gv=zod.z.object({Networks:zod.z.record(zod.z.string(),Bv).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),Nv=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(),_v=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(),Fv=zod.z.object({ValuationMode:qv.nullish(),WeightCurve:Je.nullish(),Selection:Lv.nullish()}).passthrough(),Vv=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:de.nullish(),CostCurve:Je.nullish(),FlatBonusCurve:Je.nullish(),PercentBonusCurve:Je.nullish(),PowerCurve:Je.nullish(),Fodder:Fv.nullish()}).passthrough(),jv=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),Wv=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:Gv.nullish(),Stats:Nv.nullish(),Equipment:_v.nullish(),Upgrade:Vv.nullish(),Metadata:jv.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),Hv=zod.z.object({Items:zod.z.record(zod.z.string(),Wv).nullish()}).passthrough(),Kv={Cumulative:"Cumulative",HighestOnly:"HighestOnly"},Qv=zod.z.enum(["Cumulative","HighestOnly"]).catch("Cumulative"),$v=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(),Jv=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($v).nullish()}).passthrough(),Zv=zod.z.object({BonusMode:Qv.nullish()}).passthrough(),to=zod.z.object({Catalogs:zod.z.record(zod.z.string(),Hv).nullish(),Sets:zod.z.record(zod.z.string(),Jv).nullish(),SetSettings:Zv.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 no=class extends _{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(eo.UpgradeLevel,e,we(jl))}upgradeLevelsBatch(e){return this.send(eo.UpgradeLevelsBatch,e,vf)}};var io=class extends _{constructor(e){super(e,"Store");}purchase(e){return this.send(Ft.Purchase,e,ka)}purchaseBatch(e){return this.send(Ft.PurchaseBatch,e,Tc)}getDefinitions(e){return this.send(Ft.GetDefinitions,e,hs)}getUserState(e){return this.send(Ft.GetUserState,e,wc)}getStorefront(e){return this.send(Ft.GetStorefront,e,ds)}getCreditsConfirmation(e){return this.send(Ft.GetCreditsConfirmation,e,ye)}getCreditsBalance(e){return this.send(Ft.GetCreditsBalance,e,Ac)}};var Yv={Apple:"Apple",Google:"Google"},so=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(),ro=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),so).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(r=>r),Xv=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(),Hl=zod.z.object({Definitions:zod.z.record(zod.z.string(),Xv).nullish()}).passthrough(),Af=zod.z.object({Premium:Hl.nullish()}),Tf=zod.z.object({ServerTimeUtc:u.nullish(),Premium:ro.nullish()}),oo=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),Premium:ro.nullish(),Subscription:so.nullish(),Resources:O.nullish()}),Rn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var eA={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},tA=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),wf=zod.z.object({StartUtc:u.nullish(),EndUtc:u.nullish(),Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),Kl=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),nA=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:$.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),iA=zod.z.object({Rewards:J.nullish(),Rules:J.nullish(),Refund:J.nullish()}).passthrough(),sA=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:tA.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:wf.nullish(),Refund:Kl.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:nA.nullish(),Presets:iA.nullish()}).passthrough(),rA=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(),oA=zod.z.object({Rewards:$.nullish()}).passthrough(),aA=zod.z.object({Rules:wf.nullish()}).passthrough(),lA=zod.z.object({Refund:Kl.nullish()}).passthrough(),uA=zod.z.object({Rewards:zod.z.record(zod.z.string(),oA).nullish(),Rules:zod.z.record(zod.z.string(),aA).nullish(),Refund:zod.z.record(zod.z.string(),lA).nullish()}).passthrough(),cA=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(),pA=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),sA).nullish(),Stores:zod.z.record(zod.z.string(),rA).nullish(),Presets:uA.nullish(),Validation:cA.nullish(),Refund:Kl.nullish()}).passthrough(),kf=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(),zf=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(),hA=zod.z.object({Products:zod.z.record(zod.z.string(),kf).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),zf).nullish(),LastRefundCheckAt:u.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:u.nullish(),LastPurchaseAt:u.nullish()}).passthrough(),dA=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(),Mf=zod.z.object({ServerTimeUtc:u,Purchase:pA.nullish(),Availability:zod.z.array(dA).nullish()}),Of=zod.z.object({ServerTimeUtc:u,Purchase:hA.nullish()}),mA={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},fA=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Ql=zod.z.object({ServerTimeUtc:u,Store:ki.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:fA.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish(),ProductState:kf.nullish(),Premium:ro.nullish(),Subscription:so.nullish(),SubscriptionMirror:zf.nullish()}).passthrough(),Ef=zod.z.object({ServerTimeUtc:u,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:u.nullish()}).passthrough(),qf=Mt(Ql),Cn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var ao=class extends _{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(Cn.GetDefinitions,e,Mf)}getUserState(e){return this.send(Cn.GetUserState,e,Of)}validatePurchase(e){return this.send(Cn.ValidatePurchase,e,Ql)}validatePurchasesBatch(e){return this.send(Cn.ValidatePurchasesBatch,e,qf)}createTelegramInvoice(e){return this.send(Cn.CreateTelegramInvoice,e,Ef)}};var gA=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Uf=zod.z.object({Reward:$.nullish(),Weight:zod.z.number().nullish(),AmountRange:gA.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(Uf).nullish()}).passthrough(),jn=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(Uf).nullish()}).passthrough(),yA=zod.z.object({RewardSlots:zod.z.array(Vn).nullish()}).passthrough(),RA=zod.z.object({PityRules:zod.z.array(jn).nullish()}).passthrough(),lo=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),yA).nullish(),PityPresets:zod.z.record(zod.z.string(),RA).nullish()}).passthrough();var CA=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),Lf=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(CA).nullish()}),SA=zod.z.object({RewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),xA=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:Q.nullish()}).passthrough(),bA=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:SA.nullish(),RewardMultiplier:Bi.nullish(),SupplyLimits:zod.z.array(xA).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),DA=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),$l=zod.z.object({Definitions:zod.z.record(zod.z.string(),bA).nullish(),RewardPools:lo.nullish(),Settings:DA.nullish()}).passthrough(),Bf=zod.z.object({LootboxDefinitions:$l.nullish()}),uo={GetDefinitions:"GetDefinitions",Open:"Open"};var co=class extends _{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(uo.GetDefinitions,e,Bf)}open(e){return this.send(uo.Open,e,we(Lf))}};var IA=zod.z.object({}).passthrough().transform(r=>r),PA=zod.z.object({}).passthrough().transform(r=>r),vA=zod.z.object({}).passthrough().transform(r=>r),AA=zod.z.object({}).passthrough().transform(r=>r),TA=zod.z.object({}).passthrough().transform(r=>r),wA=zod.z.object({}).passthrough().transform(r=>r),Gf=zod.z.object({ServerTimeUtc:u,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:IA,Resources:O.nullish(),Inventory:K.nullish()}),Nf=zod.z.object({ServerTimeUtc:u,AccrualID:zod.z.string(),AccruedSeconds:Q.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:PA,Resources:O.nullish(),Inventory:K.nullish()}),_f=zod.z.object({ServerTimeUtc:u,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:vA,Resources:O.nullish(),Inventory:K.nullish()}),Ff=zod.z.object({ServerTimeUtc:u,ClaimID:zod.z.string(),ClaimState:AA,Resources:O.nullish(),Inventory:K.nullish()}),kA={None:"None",Ad:"Ad",Vip:"Vip"},Vf=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:TA,Resources:O.nullish(),Inventory:K.nullish()}),jf=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()}),zA=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),MA=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(),xi=zod.z.object({Gate:ee.nullish(),Limits:Pe.nullish()}).passthrough(),Jl=zod.z.object({Availability:J.nullish()}).passthrough(),OA=zod.z.object({Availability:zod.z.record(zod.z.string(),xi).nullish()}).passthrough(),EA=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(MA).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:xi.nullish(),Presets:Jl.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),qA=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),UA=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(qA).nullish()}).passthrough(),LA=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:xi.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),BA=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:UA.nullish(),Rewards:$.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:LA.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),GA=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:$.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),NA=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(GA).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:xi.nullish(),Presets:Jl.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),_A=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(),FA=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(_A).nullish(),Availability:xi.nullish(),Presets:Jl.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),VA=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(),Zl=zod.z.object({TierRewards:zA.nullish(),MilestoneRewardMultiplier:Bi.nullish(),DailyCalendars:zod.z.record(zod.z.string(),EA).nullish(),IdleAccruals:zod.z.record(zod.z.string(),BA).nullish(),Comebacks:zod.z.record(zod.z.string(),NA).nullish(),Claims:zod.z.record(zod.z.string(),FA).nullish(),Windows:zod.z.record(zod.z.string(),VA).nullish(),Presets:OA.nullish()}).passthrough(),Wf=zod.z.object({RewardDefinitions:Zl.nullish()}),Hf=zod.z.object({Rewards:wA.nullish()}),Lt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var po=class extends _{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Lt.GetRewardDefinitions,e,Wf)}getUserRewardsState(e){return this.send(Lt.GetUserRewardsState,e,Hf)}getMilestoneRewardMultiplier(e){return this.send(Lt.GetMilestoneRewardMultiplier,e,jf)}claimDailyReward(e){return this.send(Lt.ClaimDailyReward,e,Gf)}collectIdleAccrual(e){return this.send(Lt.CollectIdleAccrual,e,Nf)}claimComebackReward(e){return this.send(Lt.ClaimComebackReward,e,_f)}claimReward(e){return this.send(Lt.ClaimReward,e,Ff)}claimRewardWindow(e){return this.send(Lt.ClaimRewardWindow,e,Vf)}};var ho=class extends _{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(ft.GetTutorialDefinitions,e,uc)}getUserTutorialState(e){return this.send(ft.GetUserTutorialState,e,_i)}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,hc)}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,pc)}resetFlow(e){return this.send(ft.ResetFlow,e,$t)}};var jA={Open:"Open",Application:"Application"},WA=zod.z.enum(["Open","Application"]).catch("Open"),HA={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Kf=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),KA={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Yl=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),QA={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"},$A=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(),Qf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:WA.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:Kf.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array($A).nullish()}).passthrough(),JA=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(),ZA=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:Yl.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(),JA).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),YA=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:Yl.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),$f=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(ZA).nullish(),Payouts:zod.z.array(YA).nullish()}).passthrough(),Jf=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:Yl.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),XA=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),eT=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(XA).nullish()}).passthrough(),tT=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(),Zf=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:Kf.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(tT).nullish()}).passthrough(),nT=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),iT=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(nT).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(),Yf=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:eT.nullish(),SolanaSignature:iT.nullish(),StateDelta:_n.nullish()}).passthrough();var mo=class extends _{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(Sn.GetCommunityMarketingState,e,Qf)}getEarnings(e){return this.send(Sn.GetEarnings,e,$f)}claim(e){return this.send(Sn.Claim,e,Jf)}checkJoinEligibility(e){return this.send(Sn.CheckJoinEligibility,e,Zf)}withdrawCryptoReward(e){return this.send(Sn.WithdrawCryptoReward,e,Yf)}};var fo=class extends _{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(nt.GetChatDefinitions,e,Wc)}getChannels(e){return this.send(nt.GetChannels,e,Ps)}poll(e){return this.send(nt.Poll,e,Hc)}getHistory(e){return this.send(nt.GetHistory,e,Kc)}getConversations(e){return this.send(nt.GetConversations,e,Jc)}sendMessage(e){return this.send(nt.SendMessage,e,Qc)}openDirectChannel(e){return this.send(nt.OpenDirectChannel,e,$c)}markRead(e){return this.send(nt.MarkRead,e,Bn)}joinChannel(e){return this.send(nt.JoinChannel,e,Bn)}leaveChannel(e){return this.send(nt.LeaveChannel,e,Bn)}reportMessage(e){return this.send(nt.ReportMessage,e,Zc)}ignoreUser(e){return this.send(nt.IgnoreUser,e,Bn)}unignoreUser(e){return this.send(nt.UnignoreUser,e,Bn)}};var go=class extends _{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(Gn.GetPushConfig,e,ep)}subscribePush(e){return this.send(Gn.SubscribePush,e,Oa)}unsubscribePush(e){return this.send(Gn.UnsubscribePush,e,Ke)}getPushSubscriptions(e){return this.send(Gn.GetPushSubscriptions,e,tp)}};var yo=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(Jr.GetLocalizationManifest,e,pf)}getLocalizationTable(e){return this.send(Jr.GetLocalizationTable,e,hf)}};var Ro=class extends _{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(vt.GetQuestDefinitions,e,Ni)}getUserQuestState(e){return this.send(vt.GetUserQuestState,e,Zu)}refreshQuestCycles(e){return this.send(vt.RefreshQuestCycles,e,Ke)}claimQuestReward(e){return this.send(vt.ClaimQuestReward,e,Ra)}claimQuestRewardsBatch(e){return this.send(vt.ClaimQuestRewardsBatch,e,ec)}claimMilestoneReward(e){return this.send(vt.ClaimMilestoneReward,e,Ca)}claimMilestoneRewardsBatch(e){return this.send(vt.ClaimMilestoneRewardsBatch,e,tc)}claimGroupCompletionReward(e){return this.send(vt.ClaimGroupCompletionReward,e,Yu)}addQuestProgress(e){return this.send(vt.AddQuestProgress,e,Xu)}};var Co=class extends _{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(yt.GetActiveEvents,e,Ms)}getDefinitions(e){return this.send(yt.GetDefinitions,e,zs)}getUserLteState(e){return this.send(yt.GetUserLteState,e,rp)}grantTokens(e){return this.send(yt.GrantTokens,e,O)}spendTokens(e){return this.send(yt.SpendTokens,e,Ua)}claimMilestone(e){return this.send(yt.ClaimMilestone,e,La)}claimMilestonesBatch(e){return this.send(yt.ClaimMilestonesBatch,e,Ba)}claimAllMilestones(e){return this.send(yt.ClaimAllMilestones,e,Ba)}spendTokensBatch(e){return this.send(yt.SpendTokensBatch,e,op)}grantTokensBatch(e){return this.send(yt.GrantTokensBatch,e,ap)}};var So=class extends _{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ze.GetDefinitions,e,Gs)}getLeaderboard(e){return this.send(Ze.GetLeaderboard,e,ai)}getMyProgress(e){return this.send(Ze.GetMyProgress,e,Es)}submitScore(e){return this.send(Ze.SubmitScore,e,qs)}submitScoreFromSource(e){return this.send(Ze.SubmitScoreFromSource,e,qs)}claimCycleReward(e){return this.send(Ze.ClaimCycleReward,e,Us)}claimMilestone(e){return this.send(Ze.ClaimMilestone,e,Ls)}getFriendsLeaderboard(e){return this.send(Ze.GetFriendsLeaderboard,e,ai)}getLeaderboardsBatch(e){return this.send(Ze.GetLeaderboardsBatch,e,cp)}getProgressBatch(e){return this.send(Ze.GetProgressBatch,e,Bs)}claimCycleRewardsBatch(e){return this.send(Ze.ClaimCycleRewardsBatch,e,pp)}claimMilestonesBatch(e){return this.send(Ze.ClaimMilestonesBatch,e,hp)}submitScoresBatch(e){return this.send(Ze.SubmitScoresBatch,e,dp)}claimAllRewardsBatch(e){return this.send(Ze.ClaimAllRewardsBatch,e,mp)}getOverviewBatch(e){return this.send(Ze.GetOverviewBatch,e,fp)}};var xo=class extends _{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Yt.GetDefinitions,e,Fs)}getActiveSeason(e){return this.send(Yt.GetActiveSeason,e,_s)}getUserState(e){return this.send(Yt.GetUserState,e,Ga)}grantStatusTokens(e){return this.send(Yt.GrantStatusTokens,e,Cp)}claimTierReward(e){return this.send(Yt.ClaimTierReward,e,Na)}claimTierRewardsBatch(e){return this.send(Yt.ClaimTierRewardsBatch,e,Sp)}};var bo=class extends _{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Rn.GetDefinitions,e,Af)}getUserState(e){return this.send(Rn.GetUserState,e,Tf)}activateTrial(e){return this.send(Rn.ActivateTrial,e,oo)}purchaseItemOrCurrency(e){return this.send(Rn.PurchaseWithResources,e,we(oo))}purchaseRealMoney(e){return this.send(Rn.PurchaseRealMoney,e,oo)}};var Do=class extends _{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send($e.GetCharacterDefinitions,e,Hs)}getUserCharacters(e){return this.send($e.GetUserCharacters,e,vp)}unlockCharacter(e){return this.send($e.UnlockCharacter,e,we(Va))}upgradeStatLevel(e){return this.send($e.UpgradeStatLevel,e,we(_a))}upgradeCharacterLevel(e){return this.send($e.UpgradeCharacterLevel,e,we(Fa))}equipItems(e){return this.send($e.EquipItems,e,Ap)}unequipItems(e){return this.send($e.UnequipItems,e,Tp)}unequipAllCharacters(e){return this.send($e.UnequipAllCharacters,e,wp)}unlockCharactersBatch(e){return this.send($e.UnlockCharactersBatch,e,qp)}upgradeCharacterLevelsBatch(e){return this.send($e.UpgradeCharacterLevelsBatch,e,Up)}upgradeStatLevelsBatch(e){return this.send($e.UpgradeStatLevelsBatch,e,Lp)}unlockSkin(e){return this.send($e.UnlockSkin,e,we(kp))}equipSkin(e){return this.send($e.EquipSkin,e,zp)}unequipSkin(e){return this.send($e.UnequipSkin,e,Mp)}getCharacterSkins(e){return this.send($e.GetCharacterSkins,e,Op)}selectCharacter(e){return this.send($e.SelectCharacter,e,Ep)}};var Io=class extends _{constructor(e){super(e,"Match");}createMatch(e){return this.send(qt.CreateMatch,e,Lh)}updateMatch(e){return this.send(qt.UpdateMatch,e,Bh)}cancelMatch(e){return this.send(qt.CancelMatch,e,Gh)}instantBattle(e){return this.send(qt.InstantBattle,e,Nh)}saveStrategy(e){return this.send(qt.SaveStrategy,e,Ke)}getMyMatches(e){return this.send(qt.GetMyMatches,e,sl)}getAvailableMatches(e){return this.send(qt.GetAvailableMatches,e,sl)}getDefinitions(e){return this.send(qt.GetDefinitions,e,jh)}};var sT={Arena:"Arena"},eg=zod.z.string(),Wn={GetState:"GetState",RefreshOpponents:"RefreshOpponents",Attempt:"Attempt",ClaimMilestone:"ClaimMilestone"},rT=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(),oT=zod.z.object({RuleID:zod.z.string().nullish(),Tiers:zod.z.array(rT).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(),aT=zod.z.object({ChallengeID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),Mode:eg.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:zt.nullish(),Milestones:zod.z.record(zod.z.string(),Ve).nullish(),ClaimMode:zod.z.string().nullish(),Arena:oT.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),lT=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(aT).nullish(),Ticket:zt.nullish(),Gate:ee.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),tg=zod.z.object({Chains:zod.z.record(zod.z.string(),lT).nullish()}).passthrough(),ng=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(),uT=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(),cT=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(),pT=zod.z.object({Opponents:zod.z.array(ng).nullish(),Revenges:zod.z.array(uT).nullish(),RevengeCost:zod.z.number().nullish(),RevengePoints:zod.z.number().nullish(),RefreshAvailableAtUtc:u.nullish()}).passthrough(),Xf=zod.z.object({ChallengeID:zod.z.string().nullish(),Mode:eg.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:pT.nullish()}).passthrough(),hT=zod.z.object({ChainID:zod.z.string().nullish(),Tickets:zod.z.number().nullish(),Active:Xf.nullish(),Ended:zod.z.array(Xf).nullish()}).passthrough(),dT=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(),Xl=zod.z.object({Chains:zod.z.array(hT).nullish(),ServerTimeUtc:u.nullish(),Burns:zod.z.array(dT).nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough(),ig=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),Attempt:cT.nullish(),IsReplay:zod.z.boolean().nullish(),Battle:pi.nullish(),Opponent:ng.nullish(),Tickets:zod.z.number().nullish(),PointsEarned:zod.z.number().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough(),sg=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 Po=class extends _{constructor(e){super(e,"Challenge");}getState(e){return this.send(Wn.GetState,e,Xl)}refreshOpponents(e){return this.send(Wn.RefreshOpponents,e,Xl)}attempt(e){return this.send(Wn.Attempt,e,ig)}claimMilestone(e){return this.send(Wn.ClaimMilestone,e,sg)}};var mT={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},rg=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),fT={None:"None",Min:"Min",Average:"Average",Max:"Max",Weighted:"Weighted"},gT=zod.z.enum(["None","Min","Average","Max","Weighted"]).catch("None"),yT={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},RT=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),CT={Clamp:"Clamp",Reject:"Reject"},ST=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),xT=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),bT=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:kt.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(xT).nullish()}),og=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,Type:rg.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(bT).nullish()}),DT=zod.z.object({CraftID:zod.z.string().nullish(),Type:rg.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:gT.nullish(),OutputLevelWeightPower:zod.z.number().nullish(),InputSelection:RT.nullish(),OutputLevelOverflow:ST.nullish()}).passthrough(),eu=zod.z.object({Definitions:zod.z.record(zod.z.string(),DT).nullish()}).passthrough(),ag=zod.z.object({ServerTimeUtc:u.nullish(),CraftDefinitions:eu.nullish()}),vo={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Ao=class extends _{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(vo.GetDefinitions,e,ag)}craft(e){return this.send(vo.Craft,e,we(og))}};var IT=2e5,To=class extends _{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,we(Zs),{timeoutMs:IT,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Zs,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(je.GetDefinitions,e,Qp)}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,Kp,{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,Wp)}getGeneration(e){return this.readGeneration(je.GetGeneration,e)}};var PT={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},vT=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),lg=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()}),ug=zod.z.object({GrantedCollectibles:zod.z.array(Hn).nullish(),DuplicateCollectibles:zod.z.array(Hn).nullish(),CollectionCurrencyEarned:Q.nullish()}),cg=zod.z.object({CreditsConfirmation:ye.nullish(),OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(ug).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()}),pg=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(ug).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()}),hg=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),tu=zod.z.object({SetID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish()}),dg=zod.z.array(Oe(tu)),mg=zod.z.object({Resources:O.nullish(),Inventory:K.nullish()}),AT=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:vT.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(),fg=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:u.nullish(),Resources:O.nullish()}),gg=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),yg=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()}),Rg=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),nu=zod.z.object({Offers:zod.z.array(AT).nullish()}),TT=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(),wT=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(TT).nullish(),SetCompletionReward:$.nullish()}).passthrough(),kT=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(wT).nullish(),GrandPrize:$.nullish()}).passthrough(),Cg=zod.z.object({BonusRewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),zT=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:de.nullish(),BonusRewardSlots:zod.z.array(Vn).nullish(),PityRules:zod.z.array(jn).nullish(),Presets:Cg.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(),MT=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),OT=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:Cg.nullish(),Tier:zod.z.number().nullish()}).passthrough(),ET=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(),qT=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),wo=zod.z.object({Collections:zod.z.record(zod.z.string(),kT).nullish(),PackTypes:zod.z.record(zod.z.string(),zT).nullish(),CollectionChests:zod.z.array(OT).nullish(),DuplicateConversions:zod.z.array(MT).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(ET).nullish(),RewardPools:lo.nullish(),Settings:qT.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 ko=class extends _{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Xe.GetDefinitions,e,wo)}getUserState(e){return this.send(Xe.GetUserState,e,lg)}openPack(e){return this.send(Xe.OpenPack,e,we(cg))}openCollectionChest(e){return this.send(Xe.OpenCollectionChest,e,pg)}useCollectibleJoker(e){return this.send(Xe.UseCollectibleJoker,e,hg)}claimSetReward(e){return this.send(Xe.ClaimSetReward,e,tu)}claimSetRewardsBatch(e){return this.send(Xe.ClaimSetRewardsBatch,e,dg)}claimGrandPrize(e){return this.send(Xe.ClaimGrandPrize,e,mg)}sendTradeOffer(e){return this.send(Xe.SendTradeOffer,e,fg)}cancelTradeOffer(e){return this.send(Xe.CancelTradeOffer,e,gg)}acceptTradeOffer(e){return this.send(Xe.AcceptTradeOffer,e,yg)}declineTradeOffer(e){return this.send(Xe.DeclineTradeOffer,e,Rg)}getMyTradeOffers(e){return this.send(Xe.GetMyTradeOffers,e,nu)}getIncomingTradeOffers(e){return this.send(Xe.GetIncomingTradeOffers,e,nu)}};var zo=class extends _{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(Tt.GetDefinitions,e,tr)}getActiveEvent(e){return this.send(Tt.GetActiveEvent,e,Zp)}getUserState(e){return this.send(Tt.GetUserState,e,er)}getGroupState(e){return this.send(Tt.GetGroupState,e,$a)}joinOrCreateGroup(e){return this.send(Tt.JoinOrCreateGroup,e,$a)}spin(e){return this.send(Tt.Spin,e,we(Xp))}claimObjectReward(e){return this.send(Tt.ClaimObjectReward,e,Ja)}claimGrandPrize(e){return this.send(Tt.ClaimGrandPrize,e,Ja)}leaveGroup(e){return this.send(Tt.LeaveGroup,e,eh)}};var Mo=class extends _{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(Et.GetDefinition,e,ph)}getUserState(e){return this.send(Et.GetUserState,e,hh)}getActiveDeals(e){return this.send(Et.GetActiveDeals,e,sr)}dismissDeal(e){return this.send(Et.DismissDeal,e,mh)}executeNode(e){return this.send(Et.ExecuteNode,e,we(dh))}recordShow(e){return this.send(Et.RecordShow,e,fh)}claimMilestone(e){return this.send(Et.ClaimMilestone,e,gh)}claimMilestonesBatch(e){return this.send(Et.ClaimMilestonesBatch,e,yh)}};var UT=zod.z.object({}).passthrough().transform(r=>r),LT=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(),iu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:$.nullish(),InviteRewards:zod.z.record(zod.z.string(),Ve).nullish(),SpendRewards:zod.z.array(LT).nullish(),Qualification:zod.z.object({}).passthrough().transform(r=>r).nullish()}).passthrough(),su=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(),Sg=zod.z.object({ReferralDefinitions:iu.nullish()}).passthrough(),xg=zod.z.object({Referral:UT.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:su.nullish()}).passthrough(),bg=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:su.nullish()}).passthrough(),Dg=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:su.nullish()}).passthrough(),ru=zod.z.object({RewardID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),Ig=Mt(ru),an={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var Oo=class extends _{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(an.GetDefinitions,e,Sg)}getUserState(e){return this.send(an.GetUserState,e,xg)}activateReferralCode(e){return this.send(an.ActivateReferralCode,e,Dg)}claimInviteReward(e){return this.send(an.ClaimInviteReward,e,ru)}claimInviteRewardsBatch(e){return this.send(an.ClaimInviteRewardsBatch,e,Ig)}checkQualification(e){return this.send(an.CheckQualification,e,bg)}};var Eo=class extends _{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(pt.GetDefinitions,e,wh)}getMessages(e){return this.send(pt.GetMessages,e,kh)}getUnreadCount(e){return this.send(pt.GetUnreadCount,e,lr)}readMessages(e){return this.send(pt.ReadMessages,e,el)}claimReward(e){return this.send(pt.ClaimReward,e,ur)}claimRewardsBatch(e){return this.send(pt.ClaimRewardsBatch,e,ur)}claimAll(e){return this.send(pt.ClaimAll,e,ur)}deleteMessages(e){return this.send(pt.DeleteMessages,e,el)}sendGift(e){return this.send(pt.SendGift,e,zh)}sendTransfer(e){return this.send(pt.SendTransfer,e,Mh)}getGiftStatus(e){return this.send(pt.GetGiftStatus,e,Oh)}};var qo=class extends _{constructor(e){super(e,"Clan");}getDefinitions(e){return this.send(Le.GetDefinitions,e,rd)}getMyClans(e){return this.send(Le.GetMyClans,e,Hh)}searchClans(e){return this.send(Le.SearchClans,e,ul)}getRecommendedClans(e){return this.send(Le.GetRecommendedClans,e,ul)}getClan(e){return this.send(Le.GetClan,e,Kh)}getClanMembers(e){return this.send(Le.GetClanMembers,e,$h)}getRankings(e){return this.send(Le.GetRankings,e,Jh)}getApplications(e){return this.send(Le.GetApplications,e,cl)}getMyInvites(e){return this.send(Le.GetMyInvites,e,cl)}getClanLog(e){return this.send(Le.GetClanLog,e,Zh)}getRequests(e){return this.send(Le.GetRequests,e,Xh)}getGifts(e){return this.send(Le.GetGifts,e,ed)}getRewards(e){return this.send(Le.GetRewards,e,td)}getTreasury(e){return this.send(Le.GetTreasury,e,od)}getProjects(e){return this.send(Le.GetProjects,e,ad)}getActivities(e){return this.send(Le.GetActivities,e,ld)}getClanQuests(e){return this.send(Le.GetClanQuests,e,ud)}getCompetitions(e){return this.send(Le.GetCompetitions,e,cd)}getBracket(e){return this.send(Le.GetBracket,e,pd)}getDiplomacy(e){return this.send(Le.GetDiplomacy,e,hd)}getRevenges(e){return this.send(Le.GetRevenges,e,dd)}getLeague(e){return this.send(Le.GetLeague,e,md)}mutate(e,t){return this.send(e,t,sd)}};var Uo=class extends _{constructor(e){super(e,"Avatar");}getDefinitions(e){return this.send(Nn.GetDefinitions,e,gr)}getAvatars(e){return this.send(Nn.GetAvatars,e,gd)}getShop(e){return this.send(Nn.GetShop,e,yd)}buyItem(e){return this.send(Nn.BuyItem,e,Rd)}};var Lo=class extends _{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Rr.RequestAdPermit,e,Cd)}completeView(e){return this.send(Rr.CompleteView,e,Sd)}};var Bo=class extends _{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Ie.GetFriendsList,e,di)}getIncomingRequests(e){return this.send(Ie.GetIncomingRequests,e,di)}getOutgoingRequests(e){return this.send(Ie.GetOutgoingRequests,e,di)}getRecommendedFriends(e){return this.send(Ie.GetRecommendedFriends,e,di)}sendFriendRequest(e){return this.send(Ie.SendFriendRequest,e,mi)}acceptFriendRequest(e){return this.send(Ie.AcceptFriendRequest,e,mi)}declineFriendRequest(e){return this.send(Ie.DeclineFriendRequest,e,mi)}removeFriend(e){return this.send(Ie.RemoveFriend,e,mi)}getPlayerProfile(e){return this.send(Ie.GetPlayerProfile,e,vd)}getInbox(e){return this.send(Ie.GetInbox,e,Ad)}markInboxSeen(e){return this.send(Ie.MarkInboxSeen,e,fi)}getInboxUnread(e){return this.send(Ie.GetInboxUnread,e,fi)}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,br)}getFollowing(e){return this.send(Ie.GetFollowing,e,br)}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,br)}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,wd)}getEntityStates(e){return this.send(Ie.GetEntityStates,e,Td)}addComment(e){return this.send(Ie.AddComment,e,Dr)}editComment(e){return this.send(Ie.EditComment,e,Dr)}deleteComment(e){return this.send(Ie.DeleteComment,e,zd)}getComments(e){return this.send(Ie.GetComments,e,kd)}report(e){return this.send(Ie.Report,e,Md)}};var BT={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var xn=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),GT=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:xn.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(),Go=zod.z.object({Schedule:Ce.nullish(),Gate:ee.nullish()}).passthrough(),ou=zod.z.object({Availability:J.nullish(),Effects:J.nullish()}).passthrough(),NT=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(xn).nullish(),Availability:Go.nullish(),Presets:ou.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),_T=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(xn).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),FT=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(_T).nullish(),Availability:Go.nullish(),Presets:ou.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),VT=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(xn).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:Go.nullish(),Presets:ou.nullish()}).passthrough(),jT=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),WT=zod.z.object({Effects:zod.z.array(xn).nullish()}).passthrough(),HT=zod.z.object({Availability:zod.z.record(zod.z.string(),Go).nullish(),Effects:zod.z.record(zod.z.string(),WT).nullish()}).passthrough(),KT=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),jT).nullish()}).passthrough(),No=zod.z.object({Definitions:zod.z.record(zod.z.string(),GT).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),NT).nullish(),BoostChains:zod.z.record(zod.z.string(),FT).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),VT).nullish(),Settings:KT.nullish(),Presets:HT.nullish()}).passthrough(),Pg=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:xn.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 vg=zod.z.object({ServerTimeUtc:u.nullish(),Active:zod.z.record(zod.z.string(),Pg).nullish()}),Ag=zod.z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:Pg.nullish(),Resources:O.nullish()}),QT={Scheduled:"Scheduled",Chain:"Chain"},$T=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(xn).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Tg=zod.z.object({ServerTimeUtc:u.nullish(),Windows:zod.z.array($T).nullish()}),bn={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var _o=class extends _{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(bn.GetDefinitions,e,No)}getActive(e){return this.send(bn.GetActive,e,vg)}getActiveWindows(e){return this.send(bn.GetActiveWindows,e,Tg)}activate(e){return this.send(bn.Activate,e,we(Ag))}cleanupExpired(e){return this.send(bn.CleanupExpired,e,Ke)}};var Fo=class extends _{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(wt.GetUserCustomDataDefinitions,e,xr)}getMyUserCustomData(e){return this.send(wt.GetMyUserCustomData,e,xd)}getPublicUserCustomDataOf(e){return this.send(wt.GetPublicUserCustomDataOf,e,ml)}setPrivateData(e){return this.send(wt.SetPrivateData,e,fl)}setPublicData(e){return this.send(wt.SetPublicData,e,fl)}deleteKey(e){return this.send(wt.DeleteKey,e,Ke)}batchSet(e){return this.send(wt.BatchSet,e,bd)}batchDelete(e){return this.send(wt.BatchDelete,e,Dd)}batchGetPublicUserCustomDataOf(e){return this.send(wt.BatchGetPublicUserCustomDataOf,e,Id)}};var JT={Static:"Static",Runtime:"Runtime"},ZT={Public:"Public",Private:"Private"},YT=zod.z.enum(["Client","Server","System"]).catch("Client"),XT=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),ew=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:YT.nullish(),ExpiresAt:u.nullish()}).passthrough(),wg=zod.z.record(zod.z.string(),ew),au=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:wg.nullish(),Runtime:wg.nullish(),NotModified:zod.z.boolean().nullish()}),tw=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:XT.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Vo=zod.z.object({Keys:zod.z.record(zod.z.string(),tw).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 jo=class extends _{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(bi.GetTitleCustomDataDefinitions,e,Vo)}getPublicTitleData(e){return this.send(bi.GetPublicTitleData,e,au)}getPublicTitleDataKeys(e){return this.send(bi.GetPublicTitleDataKeys,e,au)}};var kg=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 nw={Mesh:"Mesh",Host:"Host"},lu=zod.z.enum(["Mesh","Host"]).catch("Mesh"),iw={ServerRelay:"ServerRelay",P2P:"P2P"},uu=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),sw={Public:"Public",Private:"Private"},rw=zod.z.enum(["Public","Private"]).catch("Public"),ow={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},aw=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),zg=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),lw=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Mg=zod.z.object({SystemState:lw.nullish(),DefaultTopology:lu.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:uu.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(zg).nullish()}).passthrough(),uw=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(),cw=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:lu.nullish(),ChatMode:uu.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(),pw=zod.z.object({Seq:zod.z.number().nullish(),Type:aw.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(),Di=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:lu.nullish(),ChatMode:uu.nullish(),Visibility:rw.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(uw).nullish(),IceServers:zod.z.array(zg).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Og=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),Eg=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),cu=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),qg=zod.z.object({Rooms:zod.z.array(cw).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Ug=zod.z.object({Envelopes:zod.z.array(pw).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Wo=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),rt={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 pu=zod.z.object({TitleCustomData:Vo.nullish(),Character:Hs.nullish(),Item:to.nullish(),Currency:ar.nullish(),Store:hs.nullish(),Lootbox:$l.nullish(),Quest:Ni.nullish(),TimedEvent:zs.nullish(),Leaderboard:Gs.nullish(),Season:Fs.nullish(),Reward:Zl.nullish(),Collection:wo.nullish(),Craft:eu.nullish(),DealOffer:Za.nullish(),Premium:Hl.nullish(),TimedBoost:No.nullish(),CoopEvent:tr.nullish(),GameLoop:kr.nullish(),Match:rl.nullish(),Challenge:tg.nullish(),Experiment:of.nullish(),Blockchain:bl.nullish(),Marketplace:zl.nullish(),Multiplayer:Mg.nullish(),UserCustomData:xr.nullish(),Referral:iu.nullish(),Localization:uf.nullish(),Analytics:Qm.nullish(),Social:Od.nullish(),PlatformBridge:Ed.nullish(),GameSpec:zod.z.string().nullish(),Look:kg.nullish(),Avatar:gr.nullish()}).passthrough();var Dn={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Ho=class extends _{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(Dn.GetTitlePublicConfiguration,e,pu)}getTitlePublicConfigurationExcept(e){return this.send(Dn.GetTitlePublicConfigurationExcept,e,pu)}getCurrencyDefinitions(e){return this.send(Dn.GetCurrencyDefinitions,e,ar)}getItemDefinitions(e){return this.send(Dn.GetItemDefinitions,e,to)}getServerTime(e){return this.send(Dn.GetServerTime,e,Ke)}};var Ko=class extends _{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(We.GetGameLoops,e,kr)}getBoardDefinition(e,t=false){return this.send(We.GetBoardDefinition,e,wr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(We.GetBoardDefinitionForLevel,e,wr,{silent:t})}getUserBoardState(e){return this.send(We.GetUserBoardState,e,Bd)}boardLoopRoll(e){return this.send(We.BoardLoopRoll,e,Wd)}boardLoopAttack(e){return this.send(We.BoardLoopAttack,e,Qd)}boardLoopRaid(e){return this.send(We.BoardLoopRaid,e,Cl)}boardLoopRaidFast(e){return this.send(We.BoardLoopRaidFast,e,Cl)}boardLoopBuild(e){return this.send(We.BoardLoopBuild,e,$d)}boardSpecialChoose(e){return this.send(We.BoardSpecialChoose,e,we(Jd))}boardSpecialApplyMultiplier(e){return this.send(We.BoardSpecialApplyMultiplier,e,Zd)}boardRewardBoostApply(e){return this.send(We.BoardRewardBoostApply,e,Kd)}boardSpecialClaim(e){return this.send(We.BoardSpecialClaim,e,Yd)}getCommunityChestState(e){return this.send(We.GetCommunityChestState,e,tm)}joinOrCreateCommunityChest(e){return this.send(We.JoinOrCreateCommunityChest,e,nm)}claimCommunityChestMilestone(e){return this.send(We.ClaimCommunityChestMilestone,e,Sl)}claimCommunityChestGrandPrize(e){return this.send(We.ClaimCommunityChestGrandPrize,e,Sl)}leaveCommunityChest(e){return this.send(We.LeaveCommunityChest,e,im)}};var hw={Live:"Live",Latest:"Latest",Specific:"Specific"},dw={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},mw=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),fw={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"},gw=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),yw=zod.z.object({Level:mw,Message:zod.z.string().nullish(),Data:Xt.nullish()}),Rw=zod.z.object({Error:gw,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Bg=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(yw).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:Rw.nullish()}),hu={Execute:"Execute"};var Qo=class extends _{constructor(e){super(e,"CloudCode");}execute(e){return this.send(hu.Execute,e,Bg)}};var $o=class extends _{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(st.GetDefinitions,e,dm)}getUserState(e){return this.send(st.GetUserState,e,mm)}depositToken(e){return this.send(st.DepositToken,e,fm)}depositNFT(e){return this.send(st.DepositNFT,e,gm)}requestTokenWithdrawal(e){return this.send(st.RequestTokenWithdrawal,e,ym)}requestNFTWithdrawal(e){return this.send(st.RequestNFTWithdrawal,e,Rm)}getTransactionHistory(e){return this.send(st.GetTransactionHistory,e,Cm)}retryWithdrawal(e){return this.send(st.RetryWithdrawal,e,Sm)}confirmWithdrawal(e){return this.send(st.ConfirmWithdrawal,e,xm)}donateToDeveloper(e){return this.send(st.DonateToDeveloper,e,vl)}donateToUsersPool(e){return this.send(st.DonateToUsersPool,e,vl)}getPlayAccess(e){return this.send(st.GetPlayAccess,e,pm)}confirmPlayAccess(e){return this.send(st.ConfirmPlayAccess,e,sn)}};var Jo=class extends _{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Be.GetDefinitions,e,Im)}getGroupedOffers(e){return this.send(Be.GetGroupedOffers,e,Pm)}getOffersByItem(e){return this.send(Be.GetOffersByItem,e,Ml)}getOffer(e){return this.send(Be.GetOffer,e,vm)}getBuyOrders(e){return this.send(Be.GetBuyOrders,e,Ml)}getMyState(e){return this.send(Be.GetMyState,e,Gr)}getHistory(e){return this.send(Be.GetHistory,e,Tm)}createListing(e){return this.send(Be.CreateListing,e,Ri)}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,Ri)}placeBid(e){return this.send(Be.PlaceBid,e,Am)}claimAuction(e){return this.send(Be.ClaimAuction,e,Ct)}createBuyOrder(e){return this.send(Be.CreateBuyOrder,e,Ri)}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,Ri)}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 Zo=class extends _{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(rt.CreateRoom,e,Di)}joinRoom(e){return this.send(rt.JoinRoom,e,Di)}leaveRoom(e,t=false){return this.send(rt.LeaveRoom,e,cu,{keepalive:t})}listRooms(e){return this.send(rt.ListRooms,e,qg)}getRoom(e){return this.send(rt.GetRoom,e,Di)}closeRoom(e){return this.send(rt.CloseRoom,e,cu)}poll(e){return this.send(rt.Poll,e,Ug)}sendSignal(e){return this.send(rt.SendSignal,e,Wo,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(rt.ClaimHost,e,Di)}kickMember(e){return this.send(rt.KickMember,e,Og)}unbanMember(e){return this.send(rt.UnbanMember,e,Eg)}sendChat(e){return this.send(rt.SendChat,e,Wo)}setMemberState(e){return this.send(rt.SetMemberState,e,Wo)}};var Cw={Free:"Free",Price:"Price",Holding:"Holding"},du=zod.z.enum(["Free","Price","Holding"]).catch("Free"),Sw={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},xw=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),bw={All:"All",Any:"Any"},Dw=zod.z.enum(["All","Any"]).catch("All"),Iw={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},Pw=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),vw={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},Aw=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),Tw={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Ng=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),ww={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},kw={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},zw=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),Mw=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(),Ow=zod.z.object({Requirements:zod.z.array(Mw).nullish(),Match:Dw.nullish(),Mode:xw.nullish()}).passthrough(),Ew=zod.z.object({OptionID:zod.z.string().nullish(),Mode:du.nullish(),Price:pe.nullish(),Holding:Ow.nullish()}).passthrough(),qw=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(),Uw=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),qw).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(du).nullish(),PricePolicy:Br.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(),Lw=zod.z.object({Allowed:zod.z.array(hi).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),Bw=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),Gw=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(),Nw=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(),_w=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:ee.nullish(),Schedule:Ce.nullish(),ContentTypes:zod.z.record(zod.z.string(),Uw).nullish(),PricePolicy:Br.nullish(),Commission:kl.nullish(),HoldingPolicy:Lw.nullish(),Moderation:Bw.nullish(),Limits:Gw.nullish(),Featured:zod.z.array(Nw).nullish()}).passthrough(),Fw=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:Pw.nullish(),Access:zod.z.array(Ew).nullish(),Status:Aw.nullish(),ModerationNote:zod.z.string().nullish(),Stats:Fw.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(),Vw=zod.z.object({OptionID:zod.z.string().nullish(),Mode:du.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),_g=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(),Fg=zod.z.object({Definitions:_w.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(_g).nullish()}).passthrough(),Yo=zod.z.object({Items:zod.z.array(In).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Vg=zod.z.object({Content:In.nullish(),AccessState:zod.z.array(Vw).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),jg=zod.z.object({Collection:_g.nullish(),Items:zod.z.array(In).nullish()}).passthrough(),Wg=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(),Gg=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(),Hg=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(Gg).nullish(),ThumbnailUpload:Gg.nullish(),ExpiresAt:u.nullish()}).passthrough(),Kg=zod.z.object({CreditsConfirmation:ye.nullish(),Content:In.nullish(),Resources:O.nullish()}).passthrough(),mu=zod.z.object({Content:In.nullish()}).passthrough(),Qg=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Ng.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:Nt.nullish(),Resources:O.nullish(),CommissionTaken:pe.nullish()}).passthrough(),jw=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),$g=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:zw.nullish(),Files:zod.z.array(jw).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:u.nullish()}).passthrough(),Ww=zod.z.object({ContentID:zod.z.string().nullish(),Source:Ng.nullish(),OptionID:zod.z.string().nullish(),PricePaid:pe.nullish(),AcquiredAt:u.nullish(),Content:In.nullish()}).passthrough(),Jg=zod.z.object({Licenses:zod.z.array(Ww).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 Xo=class extends _{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(et.GetDefinitions,e,Fg)}browse(e){return this.send(et.Browse,e,Yo)}getContent(e){return this.send(et.GetContent,e,Vg)}getCollection(e){return this.send(et.GetCollection,e,jg)}getCreatorProfile(e){return this.send(et.GetCreatorProfile,e,Wg)}beginUpload(e){return this.send(et.BeginUpload,e,Hg)}publish(e){return this.send(et.Publish,e,we(Kg))}updateContent(e){return this.send(et.UpdateContent,e,mu)}unpublish(e){return this.send(et.Unpublish,e,mu)}getMyContent(e){return this.send(et.GetMyContent,e,Yo)}acquire(e){return this.send(et.Acquire,e,Qg)}getDownload(e){return this.send(et.GetDownload,e,$g)}getMyLicenses(e){return this.send(et.GetMyLicenses,e,Jg)}getMyFavorites(e){return this.send(et.GetMyFavorites,e,Yo)}};var ea=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,Em,"defs")}get(e){return this.sendKeyed("Get",e,El,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Um,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,ql,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Lm,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,Ul,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,Ul,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Bm,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,Nm,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Gm,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,_m,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,qm,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Fm,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,El,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,ql,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var ta=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??ma(),this.settings=Cu(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 si(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 Ki({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 Zi(this.emitter),this.cache=new Xi(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 es(this.host.storage,this.settings.titleID),this.api={authentication:new Zr(this),user:new Yr(this),currency:new Xr(this),item:new no(this),store:new io(this),purchase:new ao(this),lootbox:new co(this),reward:new po(this),quest:new Ro(this),tutorial:new ho(this),communityMarketing:new mo(this),chat:new fo(this),push:new go(this),localization:new yo(this),timedEvent:new Co(this),leaderboard:new So(this),season:new xo(this),premium:new bo(this),character:new Do(this),match:new Io(this),challenge:new Po(this),craft:new Ao(this),ai:new To(this),collection:new ko(this),coopEvent:new zo(this),dealOffer:new Mo(this),referral:new Oo(this),mailbox:new Eo(this),clan:new qo(this),avatar:new Uo(this),advertising:new Lo(this),social:new Bo(this),timedBoost:new _o(this),userCustomData:new Fo(this),titleCustomData:new jo(this),title:new Ho(this),gameLoop:new Ko(this),cloudCode:new Qo(this),blockchain:new $o(this),marketplace:new Jo(this),multiplayer:new Zo(this),workshop:new Xo(this),dataCollections:new ea(this),analytics:new Qr(this),experiment:new $r(this)},this.userService=new os(this),this.cache.attachState(this.userService),this.auth=new ns(this),this.currency=new ls(this),this.item=new us(this),this.store=new ms(this),this.credits=new fs(this),this.purchase=new gs(this),this.checkout=new ys(this),this.lootbox=new Rs(this),this.reward=new Ss(this),this.quest=new ks(this),this.tutorial=new bs(this),this.communityMarketing=new Ds(this),this.chat=new vs(this),this.push=new As(this),this.localization=new ws(this),this.timedEvent=new Os(this),this.leaderboard=new Ns(this),this.season=new Vs(this),this.premium=new js(this),this.character=new Ks(this),this.match=new Qs(this),this.challenge=new $s(this),this.craft=new Js(this),this.ai=new Ys(this),this.collection=new Xs(this),this.coopEvent=new nr(this),this.dealOffer=new rr(this),this.referral=new or(this),this.mailbox=new cr(this),this.clan=new mr(this),this.avatar=new yr(this),this.ads=new Cr(this),this.social=new Ir(this),this.timedBoost=new Pr(this),this.userCustomData=new vr(this),this.titleCustomData=new Ar(this),this.title=new Tr(this),this.gameLoop=new Mr(this),this.cloudCode=new Or(this),this.blockchain=new qr(this),this.marketplace=new Nr(this),this.multiplayer=new _r(this),this.workshop=new Fr(this),this.dataCollections=new jr(this),this.analytics=new Hr(this),this.experiments=new Kr(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 na=class{ctx;constructor(e){this.ctx=new ta(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 Kw(r){return new na(r)}var Zg="idos_sso",Yg="state",fu="idos:sso:state",Qw="https://idosgames.com/sso/",$w=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],Jw=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function Zw(){if(typeof window>"u")return false;let{origin:r}=window.location;return $w.includes(r)||Jw.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function Yw(){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(Zg);if(!t)return null;let n=e.get(Yg)??"",i=ik();return rk(e),sk(),i&&n!==i?null:{code:t,state:n}}function Xw(r){if(typeof window>"u")return;let e=r.returnTo??ek(),t=tk();nk(t);let n=new URL(r.ssoUrl??Qw);n.searchParams.set("title",r.titleID),n.searchParams.set("return_to",e),n.searchParams.set("state",t),window.location.assign(n.toString());}function ek(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function tk(){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 nk(r){try{window.sessionStorage.setItem(fu,r);}catch{}}function ik(){try{return window.sessionStorage.getItem(fu)}catch{return null}}function sk(){try{window.sessionStorage.removeItem(fu);}catch{}}function rk(r){r.delete(Zg),r.delete(Yg);let e=r.toString(),{pathname:t,search:n}=window.location;window.history.replaceState(null,"",`${t}${n}${e?`#${e}`:""}`);}var ok={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 ak(r,e="Something went wrong. Please try again."){return r?ok[r]??r:e}function lk(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function uk(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function ck(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function ey(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*Xg(r,t,1);break;case "TableAbsolute":o=Xg(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 pk(r,e,t=1){return ey(r,1,e,t)}function hk(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 ty(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function dk(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 ty(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 Xg(r,e,t){let n=ty(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 ny(r,e){return e?.BonusMode??r?.SetSettings?.BonusMode??"Cumulative"}function iy(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 mk(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=gk(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=ny(e,m);o.push({SetID:p,Definition:m,Pieces:g,Mode:j,ActiveTiers:iy(m,g,j)});}return o}function fk(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 gk(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 yk={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},gu=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),Rk={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Ck=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),Sk=zod.z.object({PlacementID:zod.z.string().nullish(),Type:gu.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(),xk=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(),bk=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),Dk=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:Ck.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),Ik=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),Pk=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),vk=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(),Ak=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(),Tk=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),wk=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:gu.nullish()}).passthrough(),kk={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},zk=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),Mk=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:zk.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(),wk).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),Sk).nullish(),Providers:zod.z.record(zod.z.string(),Mk).nullish(),RewardedVideo:xk.nullish(),Interstitial:bk.nullish(),Banner:Dk.nullish(),AppOpen:Ik.nullish(),FrequencyCapping:Pk.nullish(),PremiumAdReductions:zod.z.array(vk).nullish(),Consent:Ak.nullish(),Verification:Tk.nullish()}).passthrough();var Ok=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),Ek=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(),qk=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(),Uk=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(),Lk=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(),Bk=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:gu.nullish(),IssuedAt:u.nullish(),ExpiresAt:u.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),Gk=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:Ok.nullish(),Placements:zod.z.record(zod.z.string(),Ek).nullish(),Daily:qk.nullish(),Session:Uk.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:Lk.nullish(),PendingRequests:zod.z.record(zod.z.string(),Bk).nullish(),FraudFlags:Gk.nullish(),UpdatedAt:u.nullish()}).passthrough();
|
|
2
|
+
exports.AIAction=je;exports.AIErrorCode=_S;exports.AIGenerationStatus=fn;exports.AIModality=en;exports.AVATAR_MAX_USERS=fr;exports.AVATAR_SHOP_PAGE_SIZE=cD;exports.AcquisitionCapture=dn;exports.AdProviderKind=kk;exports.AdType=yk;exports.AdvertisingAction=Rr;exports.AnalyticsAction=Nl;exports.AnalyticsDropReason=hv;exports.AnalyticsEventNaming=Gl;exports.AnalyticsLimits=Ut;exports.AttackOutcome=QD;exports.AuthType=qe;exports.AuthenticationAction=He;exports.AutomaticEvent=rn;exports.AvatarAction=Nn;exports.AvatarErrors=uD;exports.BannerPosition=Rk;exports.BlockchainAction=st;exports.BlockchainNetworkType=GI;exports.BlockchainOperationCategory=om;exports.BlockchainTransactionStatus=QI;exports.BlockchainTransactionType=VI;exports.BodyPart=mb;exports.BoostWindowKind=QT;exports.BrowserFileStore=ln;exports.BrowserStorage=un;exports.CLAN_DEFAULT_KIND_ID=hr;exports.ChallengeAction=Wn;exports.ChallengeMode=sT;exports.CharacterAction=$e;exports.ChatAction=nt;exports.ChatAuthorType=wC;exports.ChatBlockedTermAction=AC;exports.ChatChannelType=bC;exports.ChatDirectAudience=PC;exports.ChatPartitioning=DC;exports.ChatReportReason=zC;exports.ClanAction=Le;exports.ClanCompetitionType=Ub;exports.ClanErrors=qb;exports.ClanInviteType=Ob;exports.ClanJoinMode=zb;exports.ClanPermission=Eb;exports.ClanRelation=Lb;exports.ClientPlatform=Ge;exports.CloudCodeAction=hu;exports.CloudCodeErrorCode=fw;exports.CloudCodeLogLevel=dw;exports.CloudCodeRevisionSelection=hw;exports.CollectionAction=Xe;exports.CommissionSink=IP;exports.CommunityChestMemberStatus=kI;exports.CommunityChestStatus=wI;exports.CommunityCreatorStatus=HA;exports.CommunityMarketingAction=Sn;exports.CommunityMetricKind=QA;exports.CommunityParticipationMode=jA;exports.CommunityPayoutCurrencyKind=KA;exports.ConversionRateMode=Gx;exports.CoopEventAction=Tt;exports.CoopGroupStatus=nx;exports.CoopMemberStatus=ix;exports.CraftAction=vo;exports.CraftInputSelectionMode=yT;exports.CraftOutputLevelMode=fT;exports.CraftOutputLevelOverflow=CT;exports.CraftType=mT;exports.CreditsConfirmationStatus=oi;exports.CreditsError=eC;exports.CurrencyAction=ci;exports.CurrencyStatus=Bx;exports.CurrencyType=bt;exports.CurveInterpolation=Fy;exports.CurveShape=Ny;exports.CustomDataBucket=jt;exports.CustomDataValueType=xD;exports.CustomDataWriter=RD;exports.DEFAULT_BASE_URL=Ru;exports.DataAccessMode=jP;exports.DataCollectionKind=NP;exports.DataCollectionSchemaMode=YP;exports.DataCollectionsAction=av;exports.DataCounterKind=QP;exports.DataFieldType=FP;exports.DataFieldVisibility=VP;exports.DataOwnerDeletedPolicy=JP;exports.DataRefKind=HP;exports.DealComparisonOperator=xx;exports.DealNodeRuntimeStatus=dx;exports.DealNodeType=Sx;exports.DealOfferAction=Et;exports.DealOfferActivationStatus=hx;exports.EVENT_NAME_PATTERN=Wr;exports.EnvelopeType=ow;exports.EventTokenType=ay;exports.ExperimentAction=Vl;exports.ExperimentGoalKind=Dv;exports.FRIENDS_FROM_PLATFORM=BD;exports.FodderSelectionMode=Uv;exports.FodderValuationMode=Ev;exports.FriendActionStatus=ID;exports.FriendSource=PD;exports.GameLoopAction=We;exports.IDosGamesClient=na;exports.IapProductType=eA;exports.IapPurchaseStatus=mA;exports.IapStoreValues=oy;exports.ItemAction=eo;exports.ItemSetBonusMode=Kv;exports.KycStatus=jI;exports.KycTier=HI;exports.LeaderboardAction=Ze;exports.LocalizationAction=Jr;exports.LocalizationMissingKeyMode=Tv;exports.LootboxAction=uo;exports.MAILBOX_COUNTER_CAP=rb;exports.MailboxAction=pt;exports.MailboxCategory=Xx;exports.MailboxErrors=sb;exports.MailboxLetterSource=eb;exports.MailboxRewardModule=nb;exports.MarketGoodsType=Lr;exports.MarketOfferStatus=DP;exports.MarketOfferType=bP;exports.MarketplaceAction=Be;exports.MatchAction=qt;exports.MatchStatus=fb;exports.MemoryFileStore=Pn;exports.MemoryHost=Xn;exports.MemoryStorage=Zn;exports.MultiplayerAction=rt;exports.MultiplayerChatMode=iw;exports.MultiplayerTopology=nw;exports.NATIVE_HOST_GLOBAL=xu;exports.NATIVE_HOST_PROTOCOL=sa;exports.NativeHost=ti;exports.OFFER_NOT_IN_ROTATION=SC;exports.PLATFORM_AD_MESSAGES=ca;exports.PLATFORM_AD_PROVIDER=hl;exports.PLATFORM_BRIDGE_ACK=Pu;exports.PLATFORM_CREDITS_CONFIRM_FINAL=xy;exports.PLATFORM_CREDITS_CONFIRM_MESSAGES=pa;exports.PLATFORM_ORIGINS=Dt;exports.PLATFORM_PAGE_UNAVAILABLE=qi;exports.PLATFORM_SIGN_IN_MESSAGES=aa;exports.PLATFORM_TOPUP_MESSAGES=ua;exports.PLATFORM_TRADE_MESSAGES=ha;exports.PeerPayoutSource=Zx;exports.PeerPayoutStatus=Yx;exports.PlatformFriendsMode=ND;exports.PlatformProfileMode=GD;exports.PlayAccessMode=iP;exports.PlayerExperimentStatus=vv;exports.PlaytimeTracker=si;exports.PremiumAction=Rn;exports.PurchaseAction=Cn;exports.PushAction=Gn;exports.PushPermissionState=it;exports.PushTopic=WC;exports.PushTransport=VC;exports.QuestAction=vt;exports.QuestObjectiveSource=Xy;exports.QuestPrerequisiteMode=tR;exports.QuestStatus=Jy;exports.RaidMode=HD;exports.ReferralAction=an;exports.ResourceEntryType=Ti;exports.RewardAction=Lt;exports.RewardWindowBoost=kA;exports.RoomVisibility=sw;exports.SITE_FRAME_HIDDEN_MESSAGE=Lu;exports.SKIN_ALREADY_OWNED=GS;exports.SKIN_SLOT=Wa;exports.ScheduleMode=ly;exports.SeasonAction=Yt;exports.SocialAction=Ie;exports.SocialContentStatus=zD;exports.SocialEntityType=TD;exports.SocialInboxVerb=MD;exports.SocialReactionKind=wD;exports.SocialReportReason=kD;exports.SpecialChoiceMode=KD;exports.StoreAction=Ft;exports.StoreRotationMode=iC;exports.StoreType=Yv;exports.TimedBoostAction=bn;exports.TimedBoostStackingPolicy=BT;exports.TimedEventAction=yt;exports.TitleAction=Dn;exports.TitleCustomDataAction=bi;exports.TitleDataBucket=ZT;exports.TitleDataScope=JT;exports.TradeOfferStatus=PT;exports.TransactionDirection=$I;exports.TutorialAction=ft;exports.TutorialBoardAction=gR;exports.TutorialFlowStatus=dR;exports.TutorialGateMode=Ey;exports.TutorialRestartPolicy=pR;exports.TutorialScriptModule=fR;exports.TutorialStepCompletionMode=uR;exports.TypedEmitter=$n;exports.UserAction=St;exports.UserCustomDataAction=wt;exports.WalletGateBalanceSource=eP;exports.WalletLinkType=_I;exports.WebHost=ii;exports.WorkshopAccessMode=Cw;exports.WorkshopAccessVia=kw;exports.WorkshopAction=et;exports.WorkshopContentStatus=vw;exports.WorkshopHoldingMatch=bw;exports.WorkshopHoldingMode=Sw;exports.WorkshopLicenseSource=Tw;exports.WorkshopSort=ww;exports.WorkshopVisibility=Iw;exports.activeSetTiers=iy;exports.askPlatformPage=It;exports.authErrorText=ak;exports.beginSsoRedirect=Xw;exports.claimedMilestoneIDs=uk;exports.countSetMembers=fk;exports.createDefaultHost=ma;exports.createIDosGamesClient=Kw;exports.cryptoShortfallFromError=En;exports.curveMultiplier=pk;exports.defineView=GR;exports.describeUserAgent=Jm;exports.effectiveSetMode=ny;exports.evaluateCurve=ey;exports.getTelegramWebApp=Kt;exports.grantedPremiumTiers=ck;exports.isAIGenerationTerminal=ui;exports.isCurveConfigured=hk;exports.isFail=ky;exports.isMilestoneClaimed=lk;exports.isOk=wy;exports.isPlatformParentOrigin=cn;exports.isReservedSlot=TS;exports.isSsoAvailable=Zw;exports.normalizeBlockchainCategory=Er;exports.parseAIErrorCode=FS;exports.platformTradeUrl=da;exports.readNativeHostGlobal=ra;exports.readSsoCodeFromUrl=Yw;exports.resolveItemSets=mk;exports.roundAmount=dk;exports.shareFallbackText=ei;exports.where=uv;exports.zPaymentProof=XR;exports.zPriceOption=cs;exports.zPriceOptions=de;
|