@idosgames/core 0.26.1 → 0.26.2
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/dist/{VoiceController-BD33ZRHg.d.ts → VoiceController-0Lyo_Tcb.d.ts} +43 -2
- package/dist/{VoiceController-DpMCYqPG.d.cts → VoiceController-C_GJOxvz.d.cts} +43 -2
- package/dist/{chunk-YSPGQWAB.js → chunk-4VTWZXB4.js} +2 -2
- package/dist/{index-DMmtsWR2.d.cts → index-BCY6F_tf.d.cts} +10 -1
- package/dist/{index-BKjfSSxG.d.ts → index-YNXpT5ol.d.ts} +10 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/platform/index.cjs +2 -2
- package/dist/platform/index.d.cts +1 -1
- package/dist/platform/index.d.ts +1 -1
- package/dist/platform/index.js +1 -1
- package/dist/realtime/index.d.cts +2 -2
- package/dist/realtime/index.d.ts +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var zod=require('zod'),Jt=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Jt__default=/*#__PURE__*/_interopDefault(Jt);var wi=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,n=>{i(),t(n);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let n of [...i])n(t);}removeAllListeners(){this.listeners.clear();}};function af(){let s=new Map;return {get:e=>s.get(e)??null,set:(e,t)=>{s.set(e,t);},remove:e=>{s.delete(e);}}}function Cl(){return lf()??af()}function lf(){try{let s=globalThis.localStorage;if(!s)return null;let e="__idos_probe__";return s.setItem(e,"1"),s.removeItem(e),{get:t=>{try{return s.getItem(t)}catch{return null}},set:(t,i)=>{try{s.setItem(t,i);}catch{try{s.removeItem(t);}catch{}}},remove:t=>{try{s.removeItem(t);}catch{}}}}catch{return null}}var Sl="https://api.idosgames.com";function xl(s){return {titleID:s.titleID,titleTemplateID:s.titleTemplateID??"default",buildKey:s.buildKey??"",baseUrl:(s.baseUrl??Sl).replace(/\/+$/,""),devBuild:s.devBuild??false,debugLogging:s.debugLogging??false,configStorage:s.configStorage??Cl(),locale:s.locale??uf(),appVersion:s.appVersion??""}}function uf(){try{return globalThis.navigator?.language??""}catch{return ""}}var ai=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{}}},li=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);}};function ui(){return globalThis.Telegram?.WebApp??null}function B(){return crypto.randomUUID()}var bl="idos_device_id",ci=class{storage;constructor(e=new ai){this.storage=e;}getPlatform(){return ui()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=ui()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=ui()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(bl);return e||(e=B(),this.storage.setString(bl,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let t=ui();if(t?.openTelegramLink){t.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let t=ui();if(t?.openInvoice){t.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let t=globalThis;typeof t.showAd=="function"&&await t.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var uo="idos_acq",Dl=["gclid","fbclid","ttclid","msclkid","yclid"],cf=["ref","r"],pf=["ref_","ref-","ref=","r_","r-"];var Ht=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();df(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},n=ff(this.platform.getDeviceModel());return n&&(i.OsVersion=n),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(uo);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let i=vl(Il(t));if(i)return i}return Hi(t)}readFromEnvironment(){let e={},t=Il(this.platform.getFullURL());Qt(e,"UtmSource",t.get("utm_source")),Qt(e,"UtmMedium",t.get("utm_medium")),Qt(e,"UtmCampaign",t.get("utm_campaign")),Qt(e,"UtmTerm",t.get("utm_term")),Qt(e,"UtmContent",t.get("utm_content")),Qt(e,"ClaimToken",t.get("idos_click"));for(let y of Dl){let F=t.get(y);if(F){e.ClickID=F;break}}let i=this.platform.getStartParameter()??"",n=mf(i);if(n){for(let y of hf)Qt(e,y,n.get(Tl[y])??null);for(let y of Dl){let F=n.get(y);if(F){e.ClickID=F;break}}}let r=Hi(n?n.get("ref")??n.get("r")??"":i),o=vl(t),c=r||o;c&&(e.ReferralCode=c,e.ChannelHint=r?"telegram":"query");let h=this.platform.getReferrer?.();return h&&(e.Referrer=h),e}read(){try{let e=this.platform.storage.getString(uo);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.platform.storage.setString(uo,JSON.stringify(e));}catch{}}};function df(s){return !!(s.UtmSource||s.UtmMedium||s.UtmCampaign||s.ClickID||s.Referrer||s.ReferralCode||s.ClaimToken)}function Qt(s,e,t){t&&(s[e]=t);}var Pl="a1_",Tl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},hf=Object.keys(Tl);function mf(s){let e=(s||"").trim();if(!e.startsWith(Pl))return null;let t=e.slice(Pl.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(i+"=".repeat((4-i.length%4)%4)),r=Uint8Array.from(n,h=>h.charCodeAt(0)),o=new TextDecoder().decode(r),c=new URLSearchParams(o);return [...c.keys()].length>0?c:null}catch{return null}}function Il(s){try{let e=s.indexOf("?");return new URLSearchParams(e>=0?s.slice(e):"")}catch{return new URLSearchParams}}function vl(s){for(let e of cf){let t=s.get(e);if(t)return Hi(t)}return null}function Hi(s){let e=(s||"").trim();if(!e)return null;for(let t of pf)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function ff(s){let e=s||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var Al="idos_usage_pending",wl="idos_usage_session",kl="idos_usage_closed_session",zl="idos_usage_new_session",Ml="idos_usage_last_activity",ki=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;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=typeof document<"u"&&document.visibilityState==="hidden",this.timer=setInterval(()=>this.tick(),200*1e3),window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide)),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();}};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,i=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,i,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(Al),this.currentSessionSeconds=this.readNumber(wl),this.pendingClosedSessionSeconds=this.readNumber(kl),this.isNewSessionPending=this.readNumber(zl)!==0;let e=this.readNumber(Ml);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(Al,this.pendingSeconds),this.writeNumber(wl,this.currentSessionSeconds),this.writeNumber(kl,this.pendingClosedSessionSeconds),this.writeNumber(zl,this.isNewSessionPending?1:0),this.writeNumber(Ml,Date.now());}readNumber(e){let t=this.ctx.platform.storage.getString(e),i=t?Number(t):0;return Number.isFinite(i)&&i>0?i:0}writeNumber(e,t){try{this.ctx.platform.storage.setString(e,String(Math.floor(t)));}catch{}}};var dt={Virtual:"Virtual",Crypto:"Crypto"},di=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),$i={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},hi=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),yt={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Ji=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),gf={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Zi=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),yf={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Yi=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),Rf={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},zi=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),ze={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function El(){let s=globalThis,e=s.Capacitor?.getPlatform?.();if(e)return Ol(e);let t=s.cordova?.platformId;return t?Ol(t):s.navigator?.userAgent??""?yt.Web:yt.Unknown}function Ol(s){let e=s.toLowerCase();return e==="android"?yt.Android:e==="ios"?yt.Ios:e==="web"?yt.Web:yt.Unknown}function V(s){return {ok:true,data:s}}function u(s,e){return {ok:false,reason:s,error:e}}var a=u("unauthorized","Not logged in.");function Cf(s){return s.ok}function Sf(s){return !s.ok}var j=zod.z.union([zod.z.number(),zod.z.string()]).transform((s,e)=>{let t=typeof s=="string"?Number(s):s;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(s)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((s,e)=>{let t=typeof s=="number"?String(s):s.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(s)}`}),zod.z.NEVER):t}),p=zod.z.string();var co=zod.z.object({Type:hi.nullish(),CurrencyID:zod.z.string().nullish(),Amount:j.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),xf=zod.z.object({Type:Yi.nullish(),EntityID:zod.z.string()}),bf=zod.z.object({Address:xf.nullish(),Amount:j.nullish(),Source:zod.z.string().nullish()}),pe=zod.z.object({Entries:zod.z.array(co).nullish(),EventTokens:zod.z.array(bf).nullish()}),Ul=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:pe.nullish()}),H=zod.z.object({Standard:pe.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Ul).nullish()}),It=zod.z.object({Standard:pe.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Ul).nullish()}),M=zod.z.object({Grant:H.nullish(),Consume:It.nullish()}),vt=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:pe.nullish()});var Df=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Pf={Completed:"Completed",Started:"Started",StepReached:"StepReached"},If=zod.z.object({FlowIDs:zod.z.array(zod.z.string()).nullish(),Mode:zod.z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:zod.z.string().nullish(),Negate:zod.z.boolean().nullish(),SkippedCountsAsCompleted:zod.z.boolean().nullish()}).passthrough(),Z=zod.z.object({Segments:zod.z.array(zod.z.string()).nullish(),MinPremiumTier:zod.z.number().nullish(),RequiredPremiumIDs:zod.z.array(zod.z.string()).nullish(),MinLevel:zod.z.number().nullish(),MaxLevel:zod.z.number().nullish(),Countries:zod.z.array(zod.z.string()).nullish(),RegisteredWithinDays:zod.z.number().nullish(),ActiveWithinDays:zod.z.number().nullish(),Experiment:Df.nullish(),Tutorial:If.nullish(),Platforms:zod.z.array(Ji).nullish()}).passthrough();var Se=zod.z.object({TotalCap:zod.z.number().nullish(),DailyCap:zod.z.number().nullish(),DailyWeightCap:zod.z.number().nullish(),PerActivationCap:zod.z.number().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish()}).passthrough();var vf=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Tf=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Af=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 wf=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 ot=zod.z.object({SourceType:zod.z.string().nullish(),BaseWeight:zod.z.number().nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish(),TileTypeFilter:zod.z.array(zod.z.string()).nullish(),TileIndexFilter:zod.z.array(zod.z.number()).nullish(),ChanceOutcomeFilter:zod.z.array(zod.z.string()).nullish(),OutcomeFilter:zod.z.array(zod.z.string()).nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Limits:Se.nullish()}).passthrough(),Re=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:Tf.nullish(),Chain:Af.nullish(),Cyclic:wf.nullish(),ActivationTriggers:zod.z.array(ot).nullish(),Relative:vf.nullish()}).passthrough();var kf={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},zf=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Mf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Of=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),Ef=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Ne=zod.z.object({Base:zod.z.number().nullish(),Shape:zf.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(Ef).nullish(),Interpolation:Of.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var Uf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:H.nullish()}).passthrough(),qf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),po=zod.z.object({Bundles:zod.z.array(Uf).nullish(),Multipliers:zod.z.array(qf).nullish()}).passthrough();var Lf=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Xi=zod.z.object({Source:Lf.nullish(),SourceKey:zod.z.string().nullish(),Curve:Ne.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:pe.nullish(),ExcludeRewards:pe.nullish()}).passthrough(),ql=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),_e=zod.z.object({MilestoneID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredProgress:zod.z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:po.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),mi=zod.z.object({Milestones:zod.z.record(zod.z.string(),_e).nullish()}).passthrough();var Q=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var Bf=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),$t=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:Bf.nullish()}).passthrough();var Gf=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),Ll=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:Gf.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),K=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),Ll).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var we=s=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:s.nullish()}),Rt=s=>zod.z.object({ServerTimeUtc:p,Items:zod.z.array(we(s)),Resources:M.nullish(),Inventory:K.nullish()});var _f={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Bl=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Ff=zod.z.object({}).passthrough().transform(s=>s),Vf=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:p.nullish(),CycleEndUtc:p.nullish(),PointsTotalEarned:j.nullish(),PointsCurrent:j.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),ho=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:j.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:Bl}),Gl=zod.z.object({State:Ff.nullish(),PointsTracks:zod.z.record(zod.z.string(),Vf).nullish()}),mo=zod.z.object({ServerTimeUtc:p,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:Bl.nullish(),Resources:M.nullish(),Inventory:K.nullish()}),fo=zod.z.object({ServerTimeUtc:p,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:j.nullish(),Resources:M.nullish(),Inventory:K.nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),_l=zod.z.object({ServerTimeUtc:p,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Fl=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(ho).nullish()}),Vl=zod.z.array(we(mo)),Nl=zod.z.array(we(fo)),Nf={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},jf=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Wf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Kf=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),jl=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:jf.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(ot).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),go=zod.z.object({Milestones:Q.nullish(),Linking:Q.nullish(),Availability:Q.nullish(),Reward:Q.nullish(),Objectives:Q.nullish()}).passthrough(),Qf=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(),Wl=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:Kf.nullish()}).passthrough(),Kl=zod.z.object({Schedule:Re.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Ql=zod.z.object({Grant:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Hf=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Qf.nullish(),Linking:Wl.nullish(),Availability:Kl.nullish(),Objectives:zod.z.record(zod.z.string(),jl).nullish(),Reward:Ql.nullish(),Presets:go.nullish()}).passthrough(),$f=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Jf=zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Gate:Z.nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:go.nullish(),PointsToken:$t.nullish()}).passthrough(),Zf=zod.z.object({Milestones:zod.z.record(zod.z.string(),mi).nullish(),Linking:zod.z.record(zod.z.string(),Wl).nullish(),Availability:zod.z.record(zod.z.string(),Kl).nullish(),Reward:zod.z.record(zod.z.string(),Ql).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),jl)).nullish()}).passthrough(),Yf=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Gate:Z.nullish(),PointsToken:$t.nullish(),GroupCompletions:zod.z.record(zod.z.string(),$f).nullish(),Phases:zod.z.record(zod.z.string(),Jf).nullish(),Presets:go.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),tn=zod.z.object({Cycles:zod.z.record(zod.z.string(),Yf).nullish(),Quests:zod.z.record(zod.z.string(),Hf).nullish(),Presets:Zf.nullish()}).passthrough(),mt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var Xf={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},eg=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),tg={Never:"Never",OnRequest:"OnRequest",Always:"Always"},ig=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),ng={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},rg=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),sg={GameLoop:"GameLoop"},og={Raid:"Raid",Attack:"Attack"},ag=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(),lg=zod.z.object({Mode:eg.nullish(),Triggers:zod.z.array(ot).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),ug=zod.z.object({Grant:H.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),cg=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(),pg=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:cg.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),dg=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),yo=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:ag.nullish(),Completion:lg.nullish(),Effects:ug.nullish(),Script:pg.nullish(),Policy:dg.nullish()}).passthrough(),hg=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(),Hl=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:ot.nullish()}).passthrough(),$l=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:ig.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Jl=zod.z.object({Grant:H.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),mg=zod.z.object({Availability:Q.nullish(),Policy:Q.nullish(),Reward:Q.nullish(),Steps:Q.nullish()}).passthrough(),fg=zod.z.object({FlowID:zod.z.string().nullish(),Identity:hg.nullish(),Availability:Hl.nullish(),Policy:$l.nullish(),Steps:zod.z.record(zod.z.string(),yo).nullish(),Reward:Jl.nullish(),Presets:mg.nullish()}).passthrough(),gg=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(),yg=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:gg.nullish()}).passthrough(),Rg=zod.z.object({Availability:zod.z.record(zod.z.string(),Hl).nullish(),Policy:zod.z.record(zod.z.string(),$l).nullish(),Reward:zod.z.record(zod.z.string(),Jl).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),yo)).nullish()}).passthrough(),Zl=zod.z.object({Flows:zod.z.record(zod.z.string(),fg).nullish(),Settings:yg.nullish(),Presets:Rg.nullish()}).passthrough(),Cg=zod.z.object({}).passthrough().transform(s=>s),Yl=zod.z.object({FlowID:zod.z.string(),Status:rg,CurrentStepID:zod.z.string().nullish(),CurrentStep:yo.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(),nn=zod.z.object({State:Cg.nullish(),Flows:zod.z.array(Yl).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),qt=zod.z.object({Flow:Yl.nullish()}).passthrough(),Xl=zod.z.object({FlowID:zod.z.string().nullish(),Granted:M.nullish()}).passthrough(),eu=zod.z.array(we(qt)),tu=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),at={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function rn(s){return Array.isArray(s)?s.filter(e=>e!==null).map(rn):s!==null&&typeof s=="object"?Object.fromEntries(Object.entries(s).filter(([,e])=>e!==null).map(([e,t])=>[e,rn(t)])):s}var sn=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var on=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function iu(s){return s===429||s>=500&&s<=599}function an(s,e=Math.random){let t=Math.min(500*Math.pow(2,s-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Lt(s){return new Promise(e=>setTimeout(e,s))}var nu=15e3;async function ru(s){try{let t=JSON.parse(await s.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(s.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function su(s,e=Math.random){return s+10+Math.min(250,s*.2)*e()}function ou(s,e=Math.random){let t=s<=1?1500:s===2?4e3:6e3;return t+t*.1*e()}var Ro=15,au=1e3,ln=class{constructor(e=Ro,t=()=>Date.now(),i=Lt){this.perSecond=e;this.now=t;this.wait=i;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=au;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(au-(e-this.starts[0])+5);}}};var Sg=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function gi(s){if(!s)return null;let e=Sg.exec(s);if(!e)return null;let[,t,i,n]=e;if(!t||i===void 0||n===void 0)return null;let r=new Jt__default.default(i),o=new Jt__default.default(n),c=o.minus(Jt__default.default.max(r,0));return c.lte(0)?null:{currencyID:t,required:o.toNumber(),available:r.toNumber(),missing:c.toNumber(),missingAmount:c.toFixed()}}var xg=12e3,bg=new Set(["RelatedEntityID"]);function Dg(s,e){if(e===null||typeof e!="object"||Array.isArray(e))return s;let t={};for(let[i,n]of Object.entries(e))bg.has(i)||(t[i]=n);try{return `${s}|${JSON.stringify(t)}`}catch{return s}}var Pg=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(ho).nullish(),TutorialProgress:zod.z.array(tu).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),un=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new on;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 sn(e.throttleMs),this.pacer=new ln(e.maxRequestsPerSecond??Ro),this.clientPlatform=e.clientPlatform??yt.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,n={}){let r=n.throttleKey??Dg(e,t);if(!this.throttler.tryAcquire(r))return u("throttled","Throttled");if(!this.inflight.add(r))return u("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,c=JSON.stringify(t),h=n.ticket??null,y=n.silent??!1,F=n.timeoutMs??xg,oe=n.autoRetry??!0,be=!1,le=!1,ge=0;for(;;){let Pt;n.keepalive||await this.pacer.take();try{Pt=await this.doFetch(o,c,h,F,n.keepalive??!1);}catch{if(oe&&ge<3){ge++,await Lt(an(ge));continue}return this.connectionFailure("Internet Connection Error",y)}let Xe=Pt.status;if(Xe>=200&&Xe<300){let se=!le&&this.cryptoTopUpHandler!==null,Ae=await this.parseSuccess(Pt,i,y,e,se);if(!Ae.ok&&se){let de=gi(Ae.error);if(de){if(le=!0,await this.runTopUp(de))continue;y||this.emitter.emit("error:global",Ae.error);}}return Ae}if(Xe===401){if(!be&&this.sessionRefreshHandler){be=!0;let se=null;try{se=await this.sessionRefreshHandler();}catch{se=null;}if(se){h=se;continue}}return this.emitter.emit("auth:unauthorized",void 0),u("unauthorized","Unauthorized")}if(iu(Xe)){let se=Xe===429?await ru(Pt):null;if(se!==null&&se>nu)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(se/1e3)} s`,y);if(oe&&ge<3){ge++,await Lt(se!==null?su(se):Xe===429?ou(ge):an(ge));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Xe})`,y)}let Ti="";try{Ti=await Pt.text();}catch{}if(Xe===409&&/operation in progress/i.test(Ti)&&oe&&ge<3){ge++,await Lt(an(ge));continue}return this.handleWebError(Ti,Xe,y)}}finally{this.inflight.remove(r),this.lowerBusy();}}async doFetch(e,t,i,n,r=false){let o=new AbortController,c=setTimeout(()=>{o.abort();},n);try{let h={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(h.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:h,signal:o.signal,...r?{keepalive:!0}:{}})}finally{clearTimeout(c);}}async parseSuccess(e,t,i,n,r=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",i)}let c;try{c=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",i)}let h=Pg.safeParse(c);if(!h.success)return this.globalError("Malformed response envelope",i);if(!h.data.Success){let le=h.data.Error??"Server returned Success=false",ge=r&&gi(le);return !i&&!ge&&this.emitter.emit("error:global",le),u("server",le)}let y=h.data.StateVersions;y&&Object.keys(y).length>0&&this.emitter.emit("user:stateVersions",{epoch:h.data.StateEpoch??null,versions:y});let F=h.data.QuestProgress;F&&F.length>0&&this.emitter.emit("quest:systemProgress",F);let oe=h.data.TutorialProgress;oe&&oe.length>0&&this.emitter.emit("tutorial:systemProgress",oe);let be=t.safeParse(h.data.Data);if(!be.success){let le=t.safeParse(rn(h.data.Data));le.success&&(be=le);}if(!be.success){let le=`Validation error (${n}): ${be.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",le),i||this.emitter.emit("error:global",le),u("validation",le)}return V(be.data)}handleWebError(e,t,i){let n=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),u("server","PLAY_ACCESS_REQUIRED");n=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{n=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",n),u("server",n)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),u("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),u("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function yi(s){return (typeof s=="string"?s:s.toISOString()).slice(0,10)}function Mi(s){return `${yi(s)}T00:00:00.000Z`}function lu(s){let e=new Date(s);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function uu(s,e){return new Date(s.getTime()+e*6e4).toISOString()}function xo(s,e,t,i){let n={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return n;s.InventoryV2??={};let r=s.InventoryV2,o=i.toISOString(),c=new Map,h=new Map,y=new Map,F=new Map,oe=new Map,be=new Map,le=new Map,ge=new Map,Pt=e.Grant?.PremiumTiers??[],Xe=Pt.length;for(let se=0;;se++){let Ae,de;if(se===0)Ae=e.Grant?.Standard?.Entries,de=false;else if(se-1<Xe)Ae=Pt[se-1]?.Resources?.Entries,de=false;else if(se===1+Xe)Ae=e.Consume?.Standard?.Entries,de=true;else break;if(Ae)for(let ue of Ae){if(ue.Type==null)continue;let he=Math.max(0,ue.Amount??0);if(!(he<=0))switch(ue.Type){case "VirtualCurrency":{if(!ue.CurrencyID)continue;let me=de?h:c;me.set(ue.CurrencyID,(me.get(ue.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!ue.CurrencyID)continue;let me=de?F:y;me.set(ue.CurrencyID,(me.get(ue.CurrencyID)??new Jt__default.default(0)).plus(he));break}case "Item":{if(!ue.ItemID)continue;let me=vg(t,ue.CatalogID,ue.ItemID),Pe=(me?me.IsStackable??true:true)?de?be:oe:de?ge:le;Pe.set(ue.ItemID,(Pe.get(ue.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(n.vcChanged=c.size>0||h.size>0,n.vcChanged){r.VirtualCurrencies??={};for(let se of new Set([...c.keys(),...h.keys()])){let Ae=c.get(se)??0,de=h.get(se)??0,ue=Ae-de,he=r.VirtualCurrencies[se];he?(he.Amount+=ue,he.UpdatedAt=o,he.Daily&&yi(he.Daily.PeriodStartUtc)===yi(i)?(he.Daily.Earned+=Ae,he.Daily.Spent+=de):he.Daily={PeriodStartUtc:Mi(i),Earned:Ae,Spent:de}):r.VirtualCurrencies[se]={Amount:ue,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:Mi(i),Earned:Ae,Spent:de}};}}if(n.ccChanged=y.size>0||F.size>0,n.ccChanged){r.CryptoCurrencies??={};for(let se of new Set([...y.keys(),...F.keys()])){let Ae=y.get(se)??new Jt__default.default(0),de=F.get(se)??new Jt__default.default(0),ue=Ae.minus(de),he=r.CryptoCurrencies[se];he?(he.Amount=new Jt__default.default(he.Amount).plus(ue).toString(),he.UpdatedAt=o):r.CryptoCurrencies[se]={Amount:ue.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(n.itemsChanged=oe.size>0||be.size>0||le.size>0||ge.size>0,n.itemsChanged){r.Items??={},r.UnstackableItems??={};let se=r.UnstackableItems,Ae=new Set([...oe.keys(),...be.keys(),...le.keys(),...ge.keys()]);for(let de of Ae){let ue=(oe.get(de)??0)-(be.get(de)??0),he=(le.get(de)??0)-(ge.get(de)??0),me=ue+he,st=r.Items[de];st?(ue!==0&&(st.StackableAmount+=ue),he!==0&&(st.UnstackableAmount+=he),me!==0&&(st.TotalAmount+=me)):r.Items[de]={StackableAmount:Math.max(0,ue),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,me)};}for(let[de,ue]of ge){if(ue<=0)continue;let he=Object.values(se).filter(me=>me.ItemID===de&&me.EquippedSlot==null&&(me.ExpiresAt==null||new Date(me.ExpiresAt)>i)).sort(Ig).slice(0,ue).map(me=>me.ItemInstanceID);for(let me of he)delete se[me];}for(let[de,ue]of le){let he=Tg(t,de);for(let me=0;me<ue;me++){let st=B();se[st]={ItemInstanceID:st,ItemID:de,CatalogID:he,RemainingUses:1,AcquiredAt:o};}}}s.EventToken??={};let Ti=s.EventToken;for(let se=0;;se++){let Ae,de;if(se===0)Ae=e.Grant?.Standard?.EventTokens,de=false;else if(se-1<Xe)Ae=Pt[se-1]?.Resources?.EventTokens,de=false;else if(se===1+Xe)Ae=e.Consume?.Standard?.EventTokens,de=true;else break;if(!(!Ae||Ae.length===0))for(let ue of Ae){let he=ue.Address;if(!he||he.Type==null)continue;let me=ue.Amount??0;if(me<=0)continue;let st=Ag(Ti,he.Type);if(!st)continue;let Pe=st[he.EntityID];Pe||(Pe={},st[he.EntityID]=Pe),Pe.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Pe.Daily??={Date:Mi(i),TotalEarned:0},Pe.Meta??={};let Ai=ue.Source&&ue.Source.length>0?ue.Source:"CustomAction";de?(Pe.Balance.Current-=me,Pe.Balance.TotalSpent+=me):(Pe.Balance.Current+=me,Pe.Balance.TotalEarned+=me,yi(Pe.Daily.Date)!==yi(i)&&(Pe.Daily={Date:Mi(i),TotalEarned:0}),Pe.Daily.TotalEarned+=me,Pe.Daily.EarnedBySource??={},Pe.Daily.EarnedBySource[Ai]=(Pe.Daily.EarnedBySource[Ai]??0)+me,Pe.Daily.TriggersBySource??={},Pe.Daily.TriggersBySource[Ai]=(Pe.Daily.TriggersBySource[Ai]??0)+1,Pe.Daily.LastTriggerBySource??={},Pe.Daily.LastTriggerBySource[Ai]=o,Pe.Meta.JoinedAtUtc||(Pe.Meta.JoinedAtUtc=o),Pe.Meta.LastEarnedAtUtc=o),n.tokensChanged=true;}}return n}function Ig(s,e){return s.AcquiredAt!==e.AcquiredAt?s.AcquiredAt<e.AcquiredAt?-1:1:s.ItemInstanceID===e.ItemInstanceID?0:s.ItemInstanceID<e.ItemInstanceID?-1:1}function vg(s,e,t){let i=s?.Catalogs;if(i){if(e){let n=i[e]?.Items?.[t];if(n)return n}for(let n of Object.values(i)){let r=n.Items?.[t];if(r)return r}}}function Tg(s,e){let t=s?.Catalogs;if(t){for(let[i,n]of Object.entries(t))if(n.Items&&e in n.Items)return i}}function Ag(s,e){switch(e){case "TimedEvent":return s.TimedEvent??={};case "Quest":return s.Quest??={};case "Leaderboard":return s.Leaderboard??={};case "CoopEvent":return s.CoopEvent??={};case "Season":return s.Season??={};default:return null}}function cu(s,e,t){let i={drop:[],restore:{}};if(!t)return i;let n=t.ChangedInstances??{},r=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let h of Object.values(n))h?.ItemID&&o.add(h.ItemID);for(let h of r){let y=s[h]?.ItemID;y&&o.add(y);}if(o.size===0)return i;let c=h=>r.has(h)||h in n;if(e){for(let[h,y]of Object.entries(e))h in s||c(h)||y&&o.has(y.ItemID)&&i.drop.push(h);for(let[h,y]of Object.entries(s))h in e||c(h)||y&&o.has(y.ItemID)&&(i.restore[h]=y);}return i}function bo(s,e){return s===e||s.startsWith(`${e}:`)}var pn=class s{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){s.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];s.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){s.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let n=xo(this.currentState,e,t,i);this.emitResourceChanges(n,false);}applyResourcesWithDelta(e,t,i,n=new Date){if(!this.currentState)return;let r=this.currentState,o={...r.InventoryV2?.UnstackableItems??{}},c=xo(r,e,i,n),h=cu(o,r.InventoryV2?.UnstackableItems,t),y=Object.entries(t?.ChangedInstances??{}),F=t?.RemovedInstanceIDs??[],oe=h.drop.length>0||Object.keys(h.restore).length>0||y.length>0||F.length>0;if(oe){r.InventoryV2??={},r.InventoryV2.UnstackableItems??={};let be=r.InventoryV2.UnstackableItems;for(let le of h.drop)delete be[le];for(let[le,ge]of Object.entries(h.restore))be[le]=ge;for(let[le,ge]of y)be[le]=ge;for(let le of F)delete be[le];}this.emitResourceChanges(c,oe);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,n){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let r=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof Jt__default.default?t:new Jt__default.default(t),c=n===void 0?new Jt__default.default(0):n instanceof Jt__default.default?n:new Jt__default.default(n),h=i??new Date().toISOString(),y=r[e];y?(y.Amount=new Jt__default.default(y.Amount).plus(o).toString(),c.isZero()||(y.Frozen=new Jt__default.default(y.Frozen??0).plus(c).toString()),y.UpdatedAt=h):r[e]={Amount:o.toString(),Frozen:c.toString(),CreatedAt:h,UpdatedAt:h},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let n=this.currentState.Store.Purchases,r=n[e];r||(r={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},n[e]=r),r.TotalPurchases+=t,r.LastPurchasedAt=i,i>=r.DailyResetUtc?(r.DailyPurchases=t,r.DailyResetUtc=lu(i)):r.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let n=this.currentState.Lootbox??={};if(n.Pity??={},t){let r=new Date().toISOString();for(let o of t)o.RuleID&&(n.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:r});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchRewardWindowState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Windows??={},this.currentState.Reward.Windows[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let n=this.currentState.Quest;if(t){n.Cycles??={};let r=n.Cycles[t];if(!r)return;r.Quests??={};let o=r.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {n.PermanentQuests??={};let r=n.PermanentQuests[e]??={QuestID:e,Status:i};r.Status=i,i==="Claimed"&&(r.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let n=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,r=t[n]??={};r.Balance??={Current:0,TotalEarned:0,TotalSpent:0},r.Balance.Current=i.PointsCurrent??0,r.Balance.TotalEarned=i.PointsTotalEarned??0,r.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(r.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let n=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};n.Steps??={};let r=n.Steps[i.StepID]??={StepID:i.StepID};r.Progress=i.Progress,i.Completed&&(r.CompletedAtUtc??=new Date().toISOString(),n.CurrentStepID===i.StepID&&(n.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let n;if(!i.CycleID)t.PermanentQuests??={},n=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let r=t.Cycles[i.CycleID];if(!r)continue;r.Quests??={},n=r.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(n.Status=i.Status,i.ObjectiveID){n.Objectives??={};let r=n.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};r.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(r.Completed=true,r.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(n.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,n]of Object.entries(t))if(bo(i,e)&&n)return n;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,n){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[r,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((n?r!==n:!bo(r,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,n),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,n){let r=this.activeEventsCache?.ActiveEvents;if(r)for(let o of r)o.Type!==e||o.TimedEventID!==t||n&&o.TokenEntityID&&o.TokenEntityID!==n||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,n){if(!e)return;let r=this.ensureLeaderboardProgress(e);(r.ScoreCycleVersion??0)<n&&(r.ScoreEarnedThisCycle=0,r.ClaimedMilestoneIDs=[],r.BracketID=null),r.CurrentScore=t,r.ScoreEarnedThisCycle=(r.ScoreEarnedThisCycle??0)+i,r.ScoreCycleVersion=n,r.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let n=false;for(let r of Object.values(i))for(let o of Object.values(r.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,n=true);n&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,n=i[e];n||(n={CharacterID:e},i[e]=n),t(n),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let n=this.currentState?.Character?.Characters?.[e];n&&(n.Equipment??={},i===null?delete n.Equipment[t]:n.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[n,r]of Object.entries(e.ChangedInstances??{}))t[n]=r,i=true;for(let n of e.RemovedInstanceIDs??[])n in t&&(delete t[n],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let n=this.currentState.CoopEvent??={MyObjectIndex:-1};n.ActiveGroupID=e,n.ActiveCoopEventID=t,n.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let n of Object.keys(i)){let r=i[n];r&&r.BoostID===e.BoostID&&n!==e.InstanceID&&delete i[n];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,n,r){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,c={Value:i,UpdatedAt:new Date().toISOString(),Version:n,LastWriter:"Client",ExpiresAt:r??null};if(e==="Private")o.Private??={},o.Private[t]=c;else if(e==="Public")o.Public??={},o.Public[t]=c;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let n=i.BuildingStates.find(r=>r.SlotIndex===e);n||(n={SlotIndex:e},i.BuildingStates.push(n)),t(n),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let n=this.ensureBoard().Pending;n&&(e&&(n.RaidLayout=e),t>=0&&(n.OpenedIndices??=[],n.OpenedIndices.includes(t)||n.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let n of Object.values(e.CryptoBalances??{}))n?.CurrencyID&&this.patchCryptoCurrencyDelta(n.CurrencyID,n.AmountDelta,n.UpdatedAt,n.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let n=this.currentState.Blockchain??={},r=n.PendingWithdrawals??[];t.size>0&&(r=r.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!r.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(r=[...r,i]),n.PendingWithdrawals=r;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var dn=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,i]of Object.entries(e))this.sections.has(t)||this.sections.set(t,i);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let i=this.config?.[e];return i??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var hn=class{user;config;constructor(e){this.user=new pn(e),this.config=new dn;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function wg(s){return s}var kg=0,zg=1500,Mg=3,fn=class{constructor(e,t,i=null,n="",r="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=n;this.loginMode=r;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return V(void 0);let i=Date.now(),n=[],r=[];for(let h of new Set(e)){let y=this.rules.get(h);if(y&&(t?.force||y.needsServer(i))){n.push(this.runRule(h,y));continue}(t?.force||!this.state.isStateFresh(h,t?.maxAgeMs))&&r.push(h);}let c=(await Promise.all([...n,r.length>0?this.queueSlice(r):Promise.resolve(V(void 0))])).find(h=>!h.ok);return c&&!c.ok?c:V(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let n=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,n),n}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},kg),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(n=>i=n);try{let n=this.state?await this.state.readStateSlice(e):V(void 0),r=n.ok?V(void 0):n;for(let o of t)o(r);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let n=mn(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let y=this.fresh(n,i?.maxAgeMs);if(y)return V(y.data);let F=this.loginFailures.get(n);if(F)return this.loginFailures.delete(n),F;let oe=this.inflight.get(n);if(oe)return oe}let r=this.generation.get(n)??0,o=Date.now(),h=t().then(y=>{if(!y.ok)return y;let F=Date.now();if((this.generation.get(n)??0)===r)return this.entries.set(n,{data:y.data,storedAt:F,expiresAt:Do(e,y.data,F)}),y;let oe=this.entries.get(n);if(oe&&oe.storedAt>=o)return y;let be=Do(e,y.data,F);return this.entries.set(n,{data:y.data,storedAt:F,expiresAt:Math.min(be??1/0,F+zg)}),y}).finally(()=>{this.inflight.get(n)===h&&this.inflight.delete(n);});return this.inflight.set(n,h),h}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let n=t.Key?t.Key:void 0,r=mn(i.view,n);if(!t.Success){this.loginFailures.set(r,u("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(r),i.apply(o.data,n),this.put(i.view,o.data,n));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let n=e.login;this.loadUsed().then(()=>{let r=pu({Name:n,Key:t});this.used.get(r)?.n!==this.session&&(this.used.set(r,{Name:n,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>Mg||this.used.set(pu(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(n=>n&&typeof n.Name=="string"&&typeof n.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(mn(e,t))?.data}put(e,t,i){this.register(e);let n=mn(e,i);this.bump(n);let r=Date.now();this.entries.set(n,{data:t,storedAt:r,expiresAt:Do(e,t,r)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let n of [...this.entries.keys(),...this.inflight.keys()])(n===i||n.startsWith(`${i}|`))&&this.drop(n);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let n=Date.now();if(!(i.expiresAt!==null&&n>=i.expiresAt)&&!(t!==void 0&&n-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(n=>t.has(n))&&this.invalidate(i);}};function mn(s,e){return e===void 0?s.key:`${s.key}|${e}`}function pu(s){return s.Key?`${s.Name}|${s.Key}`:s.Name}function Do(s,e,t){let i=s.expiresAt?.(e)??null,n=s.ttlMs!==void 0?t+s.ttlMs:null;return i!==null&&n!==null?Math.min(i,n):i??n}var gn=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 Og(e)?e:ze.None}saveAuthType(e){this.storage.setString(this.authTypeKey,e);}get savedEmail(){return this.storage.getString(this.emailKey)??""}get savedPassword(){return this.storage.getString(this.passwordKey)??""}saveEmailAndPassword(e,t){this.storage.setString(this.emailKey,e),this.storage.setString(this.passwordKey,t);}get savedRefreshToken(){return this.storage.getString(this.refreshTokenKey)??""}saveRefreshToken(e){e?this.storage.setString(this.refreshTokenKey,e):this.storage.remove(this.refreshTokenKey);}clear(){this.storage.remove(this.authTypeKey),this.storage.remove(this.emailKey),this.storage.remove(this.passwordKey),this.storage.remove(this.refreshTokenKey);}};function Og(s){return s!==null&&Object.values(ze).includes(s)}var Tt=["https://idosgames.com","https://www.idosgames.com"],yn="https://platform.idosgames.com",du=/^[a-z0-9]{8}-preview\.idos\.games$/;function Po(s){return s==="localhost"||s==="127.0.0.1"||s==="[::1]"||s.endsWith(".localhost")}function Io(){if(typeof window>"u")return false;let s=window.location.hostname.toLowerCase();return du.test(s)?true:Po(s)&&globalThis.__IDOS_PREVIEW__!=null}function Oi(s){if(typeof window<"u"&&du.test(window.location.hostname.toLowerCase()))return s===yn;if(Tt.includes(s))return true;if(typeof window>"u"||!Po(window.location.hostname))return false;try{return Po(new URL(s).hostname)}catch{return false}}var hu="IDOS_PLATFORM_WALLET_ACK",mu="PLATFORM_WALLET_UNAVAILABLE",Eg=5e3,Ug=18e4;function qg(){if(Oi(yn))return [yn];let s=[...Tt],e=window.location.ancestorOrigins?.[0];return e&&!s.includes(e)&&Oi(e)&&s.push(e),s}function Lg(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function At(s,e,t,i={}){let n={ok:false,error:mu,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(n);let r=window.parent;if(!r)return Promise.resolve(n);let o=Lg(),c=i.answerTimeoutMs??Ug;return new Promise(h=>{let y=false,F,oe=le=>{y||(y=true,window.removeEventListener("message",be),clearTimeout(F),h(le));},be=le=>{if(!Oi(le.origin))return;let ge=le.data;if(!(!ge||ge.requestId!==o)){if(ge.type===hu){clearTimeout(F),F=setTimeout(()=>oe({ok:false,error:"TIMEOUT",data:{}}),c);return}ge.type===e&&oe({ok:ge.ok===true,error:typeof ge.error=="string"?ge.error:void 0,data:ge});}};F=setTimeout(()=>oe(n),Eg),window.addEventListener("message",be);for(let le of qg())try{r.postMessage({type:s,requestId:o,...t},le);}catch{}})}var vo={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},Bg=30*6e4,To="idos:platformSignIn:declined:";function Gg(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(Io())return false;let s=window.location.ancestorOrigins?.[0];if(s&&!Tt.includes(s))try{let e=new URL(s).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}function _g(){if(typeof window>"u"||!Io())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function Ao(s){let e=await At(vo.request,vo.response,{titleID:s,supports:["pgs"]},{answerTimeoutMs:Bg}),t=e.data.ticket;if(e.ok&&typeof t=="string"&&t.length>0)return {ticket:t};let i=e.data.code;return e.ok&&typeof i=="string"&&i.length>0?{code:i}:{error:e.error??"no_code"}}function Fg(s){try{window.localStorage.setItem(To+s,"1");}catch{}}function Vg(s){try{window.localStorage.removeItem(To+s);}catch{}}function Ng(s){try{return window.localStorage.getItem(To+s)==="1"}catch{return false}}var jg=8,Wg=100,Kg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,fu=["GameLoop"];function Qg(s){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(s)}var Rn=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=ze.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let n=this.authContext;if(!n)return a;let r=this.baseRequest();r.UserID=n.userID,r.ClientSessionTicket=n.clientSessionTicket,r.WalletAddress=e,r.NetworkID=t,i&&(r.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(r);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return a;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let n=await this.ctx.api.authentication.unlinkWallet(i);return n.ok&&n.data.PlayAccess&&this.setPlayAccess(n.data.PlayAccess),n}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.platform.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.platform.getDeviceID(),e.Device=this.ctx.platform.getDeviceModel(),e.Platform=this.ctx.platform.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(ze.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return u("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let n=await this.ctx.api.authentication.loginWithEmail(i);if(!n.ok)return n;this.applyAuthContext(n.data);let r=await this.fetchAndApplyClientState(ze.Email);return r.ok&&this.keepEmailCredentials(e,t),r}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.platform.getDeviceID(),i.Device=this.ctx.platform.getDeviceModel(),i.Platform=this.ctx.platform.getPlatform();let n=await this.ctx.api.authentication.registerWithEmail(i);return n.ok?(this.pendingRegistration={email:e,password:t},V({codeTtlMinutes:n.data.CodeTtlMinutes??0,resendCooldownSeconds:n.data.ResendCooldownSeconds??0})):n}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let n=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!n.ok)return n;this.applyAuthContext(n.data);let r=await this.fetchAndApplyClientState(ze.Email);return r.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,r}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?V(void 0):i}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let i=await this.ctx.api.authentication.loginWithGoogle(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Google)):i}async loginWithApple(e,t){if(!e?.trim())return u("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let n=await this.ctx.api.authentication.loginWithApple(i);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(ze.Apple)):n}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.WalletAddress=e,n.NetworkID=t,n.WalletSignature=i,n.Platform=this.ctx.platform.getPlatform(),n.Device=this.ctx.platform.getDeviceModel(),n.DeviceID=this.ctx.platform.getDeviceID();let r=await this.ctx.api.authentication.loginWithWallet(n);return r.ok?(this.applyAuthContext(r.data),this.fetchAndApplyClientState(ze.Wallet)):r}async loginWithSsoCode(e){if(!e)return u("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.platform.getDeviceID(),t.Device=this.ctx.platform.getDeviceModel(),t.Platform=this.ctx.platform.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.iDosGames)):i}async loginWithPlatformGameTicket(e){if(!e)return u("client","Platform game ticket is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.PlatformGameTicket=e;let i=await this.ctx.api.authentication.resolvePlatformGameSession(t);return i.ok?(this.applyAuthContext(i.data),this.platformGameSession=true,this.fetchAndApplyClientState(ze.iDosGames)):i}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.Email=e,n.ResetToken=t,n.Password=i,this.ctx.api.authentication.resetPassword(n)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==ze.None?e:ze.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let n=await this.ctx.api.authentication.refreshSession(i);return n.ok?(this.applyRefresh(n.data),"ok"):(Qg(n.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case ze.Email:return this.loginWithEmail(t,i);case ze.Device:case ze.None:return this.loginWithDeviceID();case ze.Telegram:return this.loginWithTelegram();default:return Promise.resolve(u("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;if(this.platformGameSession){this.refreshing=true;try{let t=await Ao(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let n=await this.ctx.api.authentication.resolvePlatformGameSession(i);return n.ok?(this.applyAuthContext(n.data),this.platformGameSession=!0,n.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==ze.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===ze.None)return null;this.refreshing=true;try{return (await this.replay(e,this.sessionEmail||this.ctx.authStore.savedEmail,this.sessionPassword||this.ctx.authStore.savedPassword)).ok&&this.authContext?this.authContext.clientSessionTicket:null}catch{return null}finally{this.refreshing=false;}}logout(){this.authContext=null,this.playAccessStatus=null,this.forgetSession(),this.ctx.authStore.clear(),this.ctx.data.reset(),this.ctx.emitter.emit("auth:loggedOut",void 0);}static isValidEmail(e){return e.length>0&&Kg.test(e)}static isValidPasswordLength(e){return e.length>=jg&&e.length<=Wg}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=ze.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e){let t=await this.ctx.userService.getClientStateExcept(fu,fu);return t.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)),t}};var Hg="idos:cfg",Ri=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${gu(t)}`:e&&e.length>0?`f:${gu(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${Hg}:${this.titleId}:${e}`}};function gu(s){return [...s].map(e=>e.toLowerCase()).sort().join(",")}var yu="idos:loc",Ci=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(n)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[n,r]of Object.entries(t))typeof r=="number"&&r>0&&(i[n]=r);return i}catch{return {}}}async noteVersion(e,t){let i=await this.readVersions();i[e]!==t&&(i[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(i)));}keyOf(e){return `${yu}:${this.titleId}:${e}`}versionsKey(){return `${yu}:${this.titleId}:versions`}};var $g="idos:sec",Cn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let i=JSON.parse(t);return !i||typeof i!="object"||i.v!==e||!i.s||typeof i.s!="object"?{}:i.s}catch{return {}}}async write(e,t){try{let i={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(i));}catch{}}keyOf(){return `${$g}:${this.titleId}`}};var Jg="idos:state",Sn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,n){if(!(!e||!t))try{let r={e:t,v:i,s:n};await this.storage.set(this.keyOf(e),JSON.stringify(r));}catch{}}keyOf(e){return `${Jg}:${this.titleId}:${e}`}};function Zg(s,e){if(!s)return;let t=new Set((e??[]).map(n=>n.trim().toLowerCase()));if(t.size===0)return s;let i={};for(let[n,r]of Object.entries(s))t.has(n.toLowerCase())||(i[n]=r);return i}function wo(s,e,t,i){let n={...s??{}};if(!e||!t||!i)return n;for(let[r,o]of Object.entries(t))i[r]===o&&r in e&&(n[r]=e[r]);return n}function Yg(s){return {...s??{}}}function ko(s){return typeof s.StateEpoch=="string"&&s.StateEpoch.length>0?s.StateEpoch:null}var xn=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let n=this.confirmedAt[e];return n===void 0?false:t===void 0||i-n<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=Zg(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let r=Object.keys(this.versions);this.reset(e),this.notify(r);}return}let i=Date.now(),n=[];for(let[r,o]of Object.entries(t)){let c=this.versions[r];c!==o&&(c!==void 0&&o===c+1?(this.versions[r]=o,this.confirmedAt[r]=i):(delete this.versions[r],delete this.confirmedAt[r]),n.push(r),this.dirty=true);}this.notify(n);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=Yg(t);let n=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=n;this.dirty=true;let r=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&r.add(o);this.notify([...r]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),n=[];for(let[r,o]of Object.entries(t??{}))this.versions[r]!==o&&n.push(r),this.versions[r]=o,this.confirmedAt[r]=i;this.dirty=true,this.notify(n);}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 Ru=u("server","Title configuration is unavailable (CDN and API both failed)."),bn=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.platform.getFullURL(),RelatedEntityID:B()}:null}get configCache(){return this.cache??=new Ri(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new Ci(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new Cn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new xn(new Sn(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return a;let t=Ri.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let n=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let r=await this.ctx.api.user.getClientState(e);if(!r.ok)return r;let o=await this.resolveTitleConfig(r.data,t,i,{Fields:e.TitleFields});return o==null?Ru:(this.finishStateHandshake(r.data,n),await this.restoreSections(r.data.TitleConfigVersion,o),await this.applyClientState(r.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(r.data.Views),await this.applyLocalization(r.data.Localization),await this.flushState(n),r)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let n=this.stateStore.versionsFor(t);if(n){e.KnownStateVersions=n;let r=this.stateStore.currentEpoch;r&&(e.KnownStateEpoch=r);}return {userId:i,cached:this.stateStore.cachedState,sent:n}}finishStateHandshake(e,t){let i=wo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let n=ko(e);!n||!t.userId||this.stateStore.afterFullRead(n,e.StateVersions);}async resolveTitleConfig(e,t,i,n){let r=e.TitleConfigVersion;if(i&&r&&i.v===r)return i.c;if(e.TitleConfigUrl){let c=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(c!=null)return r&&await this.configCache.write(t,r,c),c}let o=await this.fetchConfigFromApi(n);return o!=null?(r&&await this.configCache.write(t,r,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},n=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return n.ok?n.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return a;i.ExcludeFields=e,i.ExcludeTitleFields=t;let n=Ri.scopeOf(null,t??[]),r=await this.configCache.read(n);r&&(i.KnownTitleConfigVersion=r.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let c=await this.ctx.api.user.getClientStateExcept(i);if(!c.ok)return c;let h=await this.resolveTitleConfig(c.data,n,r,{ExcludeFields:t??[]});return h==null?Ru:(this.finishStateHandshake(c.data,o),await this.restoreSections(c.data.TitleConfigVersion,h),await this.applyClientState(c.data,h,e,t),this.ctx.cache.acceptLoginViews(c.data.Views),await this.applyLocalization(c.data.Localization),await this.flushState(o),c)}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let i=t,n={};for(let[r,o]of Object.entries(await this.sectionCache.read(e)))i[r]==null&&(n[r]=o);this.ctx.data.config.restoreSections(n),this.ctx.data.config.setSectionSink((r,o)=>{i[r]!=null||o==null||(n[r]=o,this.sectionCache.write(e,n));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let n=await this.localizationCache.read(t);if(i<=0)return n?.t??null;if(n&&n.v===i)return n.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let r=await this.fetchLocalizationFromApi(t,n?.v??0);return r??n?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let n=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!n.ok)return null;let r=n.data;if(r.NotModified)return null;let o=r.Entries??{},c=r.Version??0,h=r.Locale??e;return c>0&&await this.localizationCache.write(h,c,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):a}async getUserState(e){let t=this.baseRequest();if(!t)return a;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),n=await this.ctx.api.user.getUserState(t);if(!n.ok)return n;let r=wo(n.data.User,i.cached,i.sent,n.data.StateVersions);n.data.User=r;let o=i.sent??{},c=Object.entries(n.data.StateVersions??{}).filter(([y,F])=>o[y]!==F||this.ctx.data.user.state?.[y]===void 0).map(([y])=>y);this.ctx.data.user.applyUserStateContainers(r,c);let h=ko(n.data);return h&&(this.stateStore.afterSliceRead(h,n.data.StateVersions),await this.flushState(i)),n}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let n=this.baseRequest();if(!n)return a;n.UsageTime=e,n.IsNewSession=t,n.SessionDurationSeconds=i;let r=await this.ctx.api.user.addUsageTime(n);return r.ok&&this.ctx.emitter.emit("user:usageTimeAdded",r.data),r}async deleteUserAccount(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return a;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,n){let r=i?.includes("GameLoop")===true,o=n?.includes("GameLoop")===true,c=r?this.ctx.data.user.state?.GameLoop:void 0,h=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let y=this.ctx.data.user.state;r&&y&&y.GameLoop==null&&(y.GameLoop=c);let F=this.ctx.data.config.titlePublicConfiguration;o&&F&&F.GameLoop==null&&(F.GameLoop=h),this.ctx.emitter.emit("user:clientStateReceived",e);}};var Pn=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return u("client","SpendID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${B()}`},n=await this.ctx.api.currency.spend(i);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",n.data)),n}async convert(e,t,i,n,r,o){if(!t)return u("client","SourceID is required.");if(!n)return u("client","TargetID is required.");if(r<=0)return u("client","Amount must be positive.");if(e===i&&t===n)return u("client","Source and target must differ.");if(e===dt.Crypto||i===dt.Crypto)return u("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return a;let c={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:String(Math.trunc(r)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${n}_${B()}`},h=await this.ctx.api.currency.convert(c);if(h.ok){let y=h.data,F={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:y.SourceID,Amount:y.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:y.TargetID,Amount:y.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(F,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",y);}return h}async cryptoConvert(e,t,i,n,r,o){let c=r instanceof Jt__default.default?r:new Jt__default.default(r);if(!t)return u("client","SourceID is required.");if(!n)return u("client","TargetID is required.");if(c.lte(0))return u("client","SourceAmount must be a positive decimal.");if(e===i&&t===n)return u("client","Source and target must differ.");if(e===dt.Virtual&&i===dt.Virtual)return u("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===dt.Virtual&&!c.isInteger())return u("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:c.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${n}_${B()}`},y=await this.ctx.api.currency.cryptoConvert(h);if(y.ok){let F=y.data,oe=[],be=[];if(F.SourceType===dt.Virtual&&oe.push({Type:"VirtualCurrency",CurrencyID:F.SourceID,Amount:Math.trunc(Number(F.SourceSpent))}),F.TargetType===dt.Virtual&&be.push({Type:"VirtualCurrency",CurrencyID:F.TargetID,Amount:Math.trunc(Number(F.TargetCredited))}),oe.length>0||be.length>0){let le={Consume:oe.length>0?{Standard:{Entries:oe}}:null,Grant:be.length>0?{Standard:{Entries:be}}:null};this.ctx.data.user.applyResourceOperation(le,this.ctx.data.config.itemDefinitions);}F.SourceType===dt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(F.SourceID,new Jt__default.default(F.SourceSpent).negated(),F.ServerTimeUtc),F.TargetType===dt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(F.TargetID,new Jt__default.default(F.TargetCredited),F.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",F);}return y}};var In=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i,n){let r=e.trim();if(!r)return u("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:r,SelectedOptionID:i,CreditsConfirmationID:n,RelatedEntityID:`upgrade_item_${r}_${B()}`};t&&t.length>0&&(o.FodderInstanceIDs=[...t]);let c=await this.ctx.api.item.upgradeLevel(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(c.data.ItemInstanceID??r,c.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",c.data)),c}async upgradeLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let n of i.data)n.Success&&n.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(n.Data.ItemInstanceID,n.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var vn=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:It.nullish(),AllowedPlatforms:zod.z.array(Ji).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ce=zod.z.record(zod.z.string(),vn),Xg=zod.z.object({Store:Zi,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var Ei={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},fe=zod.z.object({ConfirmationID:zod.z.string(),Url:zod.z.string(),Status:zod.z.string(),PriceCredits:zod.z.number(),ExpiresAt:p}).passthrough(),Cu=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),ey={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"},zo=zod.z.object({ServerTimeUtc:p,OfferID:zod.z.string(),Count:zod.z.number(),Resources:M.nullish(),Inventory:K.nullish(),CreditsConfirmation:fe.nullish()}),Su=zod.z.array(we(zo)),ty=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:p,LastPurchasedAt:p}),iy=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:p}),xu=zod.z.object({Purchases:zod.z.record(zod.z.string(),ty).nullish(),Rotations:zod.z.record(zod.z.string(),iy).nullish()}).passthrough().transform(s=>s),wt=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(),Tn=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),ny={Fixed:"Fixed",Title:"Title",Player:"Player"},ry=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:Z.nullish()}).passthrough(),bu=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(ry).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),sy=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Rotation:Q.nullish()}).passthrough(),oy=zod.z.object({SlotID:zod.z.string().nullish(),Identity:wt.nullish(),Availability:Tn.nullish(),Rotation:bu.nullish(),Presets:sy.nullish()}).passthrough(),ay=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish()}).passthrough(),ly=zod.z.object({SectionID:zod.z.string().nullish(),Identity:wt.nullish(),Availability:Tn.nullish(),Slots:zod.z.record(zod.z.string(),oy).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:ay.nullish()}).passthrough(),Du=zod.z.object({Sections:zod.z.record(zod.z.string(),ly).nullish()}).passthrough(),uy=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Layout:Q.nullish()}).passthrough(),cy=zod.z.object({StoreID:zod.z.string().nullish(),Identity:wt.nullish(),Availability:Tn.nullish(),Layout:Du.nullish(),Presets:uy.nullish()}).passthrough(),Pu=zod.z.object({Options:ce.nullish(),CompareAt:zod.z.record(zod.z.string(),It).nullish()}).passthrough(),Iu=zod.z.object({Grant:H.nullish()}).passthrough(),vu=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),py=zod.z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish(),Availability:Q.nullish()}).passthrough(),dy=zod.z.object({OfferID:zod.z.string().nullish(),Identity:wt.nullish(),Pricing:Pu.nullish(),Reward:Iu.nullish(),Availability:vu.nullish(),Presets:py.nullish()}).passthrough(),hy=zod.z.object({Identity:zod.z.record(zod.z.string(),wt).nullish(),Availability:zod.z.record(zod.z.string(),Tn).nullish(),Layout:zod.z.record(zod.z.string(),Du).nullish(),Rotation:zod.z.record(zod.z.string(),bu).nullish(),Pricing:zod.z.record(zod.z.string(),Pu).nullish(),Reward:zod.z.record(zod.z.string(),Iu).nullish(),OfferAvailability:zod.z.record(zod.z.string(),vu).nullish()}).passthrough(),An=zod.z.object({Stores:zod.z.record(zod.z.string(),cy).nullish(),StoreOffers:zod.z.record(zod.z.string(),dy).nullish(),Presets:hy.nullish()}).passthrough(),my=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:p.nullish()}).passthrough(),fy=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:It.nullish(),CompareAtCost:It.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(),gy=zod.z.object({OfferID:zod.z.string(),Identity:wt.nullish(),PriceOptions:zod.z.array(fy).nullish(),Rewards:H.nullish(),State:my.nullish()}).passthrough(),yy=zod.z.object({SlotID:zod.z.string(),Identity:wt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:p.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:gy.nullish()}).passthrough(),Ry=zod.z.object({SectionID:zod.z.string(),Identity:wt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(yy).nullish()}).passthrough(),Cy=zod.z.object({StoreID:zod.z.string(),Identity:wt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:p.nullish(),Sections:zod.z.array(Ry).nullish()}).passthrough(),wn=zod.z.object({ServerTimeUtc:p,Stores:zod.z.array(Cy).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),kt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},Sy="OFFER_NOT_IN_ROTATION";var Tu="Store",Au={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:s=>{let e=null;for(let t of s.Stores??[])for(let i of t.Sections??[])for(let n of i.Slots??[]){let r=Date.parse(n.RefreshesAtUtc??"");!Number.isNaN(r)&&(e===null||r<e)&&(e=r);}return e}},kn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Au,{schema:wn,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return u("client","OfferID is required.");if(t<1)return u("client","Count must be at least 1.");let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${n.userID}_${B()}`},o=await this.ctx.api.store.purchase(r);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;this.ctx.data.user.patchStorePurchase(e,t,c.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",c);}return o}async purchaseWithCredits(e,t=1,i={}){return await this.ctx.credits.pay(n=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:n}),{onConfirmation:i.onConfirmation,signal:i.signal,pollMs:i.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):a}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):a}async purchaseBatch(e){if(!e||e.length===0)return u("client","purchases is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||!r.Data.OfferID||(this.ctx.data.user.patchStorePurchase(r.Data.OfferID,r.Data.Count,r.Data.ServerTimeUtc),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(Tu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.store.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Tu,n.data),this.ctx.emitter.emit("store:definitionsLoaded",n.data)),n}getStorefront(e){return this.ctx.cache.read(Au,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let n of i.Slots??[]){let r=n.RefreshesAtUtc;r&&(e===null||Date.parse(r)<Date.parse(e))&&(e=r);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var Mo={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},xy=15*6e4,by=/^[a-z0-9]{8}-preview\.idos\.games$/;function Zt(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !by.test(window.location.hostname.toLowerCase())}async function Oo(s){let e=await At(Mo.request,Mo.response,{titleID:s.titleID,userID:s.userID,currencyID:s.currencyID,amount:s.amount},{answerTimeoutMs:xy});return e.ok?{ok:true}:{ok:false,error:e.error}}var Eo={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},Dy=10*6e4;function Uo(){return Zt()}async function qo(s){let e=await At(Eo.request,Eo.response,{titleID:s.titleID,confirmationID:s.confirmationID},{answerTimeoutMs:Dy});return e.ok?{ok:true}:{ok:false,error:e.error}}var zn=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let i=await e(void 0);if(!i.ok||!i.data.CreditsConfirmation)return i;let n=i.data.CreditsConfirmation,r=()=>e(n.ConfirmationID);if(Uo()){let h=await qo({titleID:this.ctx.settings.titleID,confirmationID:n.ConfirmationID});if(h.ok)return await r();if(h.error==="DECLINED")return u("server","CREDITS_CONFIRMATION_DECLINED");if(h.error==="NOT_ENOUGH_CREDITS")return u("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(n);let o=Math.max(1e3,t.pollMs??2500),c=Date.parse(n.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return u("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>c)return u("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(F=>setTimeout(F,o));let h=await this.ctx.store.getCreditsConfirmation(n.ConfirmationID);if(!h.ok)continue;let y=h.data.Status;if(y!==Ei.Pending)return y===Ei.Declined?u("server","CREDITS_CONFIRMATION_DECLINED"):y===Ei.Expired?u("server","CREDITS_CONFIRMATION_EXPIRED"):await r()}}};var Mn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?V(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return u("client","Receipt is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},r=await this.ctx.api.purchase.validatePurchase(n);return r.ok&&this.applyValidation(r.data),r}async buyWithTelegramStars(e,t){if(!e)return u("client","productID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},n=await this.ctx.api.purchase.createTelegramInvoice(i);return n.ok&&t?.open!==false&&this.ctx.platform.openInvoice(n.data.InvoiceLink),n}async validatePurchasesBatch(e){if(!e||e.length===0)return u("client","receipts is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let n of i.data.Items)n.Success&&n.Data&&this.applyValidation(n.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var wu=3,Py=700,On=class{constructor(e){this.ctx=e;Zt()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return gi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await Oo({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return i.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:i.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=wu;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===wu)break;await Lt(Py);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t)if(i?.Type===$i.Purchase&&i.ProductID)return i.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t){if(i?.Type!==$i.CryptoCurrency||!i.CurrencyID)continue;let n=Number(i.Amount??0);if(!(n>0))continue;let r=this.cryptoBalance(i.CurrencyID);return r>=n?null:{currencyID:i.CurrencyID,required:n,available:r,missing:n-r}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var ku="Lootbox",En=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ku,e);if(t){let r={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),V(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.lootbox.getDefinitions(i);if(n.ok){let r=n.data.LootboxDefinitions;r&&(this.ctx.data.config.patchSection(ku,r),this.ctx.emitter.emit("lootbox:definitionsLoaded",r));}return n}async open(e,t,i,n,r){if(!e)return u("client","LootboxID is required.");if(t<1)return u("client","Count must be at least 1.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:n,CreditsConfirmationID:r,RelatedEntityID:`lootbox_${e}_${i??"default"}_${B()}`},c=await this.ctx.api.lootbox.open(o);if(c.ok&&!c.data.CreditsConfirmation){let h=c.data;h.TriggeredPity&&h.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,h.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(h.Resources,h.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",h);}return c}};var Lo="Reward";function Un(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var qn=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(Lo)?.Comebacks??{}).some(i=>i?.TrackPresenceOnRead===true),refresh:async()=>{let i=await this.getUserRewardsState();return i.ok&&(t=true),i}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(Lo,e);if(t){let r={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),V(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.reward.getRewardDefinitions(i);if(n.ok){let r=n.data.RewardDefinitions;r&&(this.ctx.data.config.patchSection(Lo,r),this.ctx.emitter.emit("reward:definitionsLoaded",r));}return n}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${B()}`},n=await this.ctx.api.reward.claimDailyReward(i);if(n.ok){let r=n.data;this.ctx.data.user.patchDailyCalendarState(r.CalendarID,r.DailyState),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",r);}return n}async collectIdleAccrual(e){if(!Un(e))return u("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${B()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let n=i.data;this.ctx.data.user.patchIdleAccrualState(n.AccrualID,n.IdleState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",n);}return i}async claimComebackReward(e){if(!Un(e))return u("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${B()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchComebackState(n.ComebackID,n.ComebackState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",n);}return i}async claimReward(e){if(!Un(e))return u("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${B()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchClaimRewardState(n.ClaimID,n.ClaimState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",n);}return i}async claimRewardWindow(e,t,i={}){if(!Un(e))return u("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return u("client","Amount must be a positive number.");let n=i.boost??"None";if(n==="Ad"&&!i.adRequestID)return u("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:n,...i.adRequestID?{AdRequestID:i.adRequestID}:{},RelatedEntityID:i.roundID??`reward_window_${e}_${B()}`},o=await this.ctx.api.reward.claimRewardWindow(r);if(o.ok){let c=o.data;this.ctx.data.user.patchRewardWindowState(c.WindowID,c.WindowState),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:windowClaimed",c);}return o}};var Ln="Tutorial",zu={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"]},Bn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(zu,{schema:nn,apply:i=>this.applyUserTutorialState(i)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(Ln)?.Flows??{}).length>0,refresh:async()=>{let i=await this.getUserTutorialState();return i.ok&&(t=true),i}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(Ln,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.tutorial.getTutorialDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Ln,n.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",n.data)),n}getUserTutorialState(e=true,t){return this.ctx.cache.read(zu,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${B()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return u("client","FlowID is required.");if(!t||t.length===0)return u("client","stepIDs is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${B()}`},r=await this.ctx.api.tutorial.completeStepsBatch(n);return r.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",r.data)),r}async skipStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.skipStep(i))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${B()}`},n=await this.ctx.api.tutorial.claimFlowReward(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",n.data)),n}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let n=e?.trim();if(!n)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),FlowID:n},o=await t(r);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,n){let r=e?.trim(),o=t?.trim();if(!r)return u("client","FlowID is required.");if(!o)return u("client","StepID is required.");if(!this.ctx.auth.context)return a;let c={...this.ctx.buildAuthedBaseRequest(),FlowID:r,StepID:o};n?.relatedEntityID&&(c.RelatedEntityID=n.relatedEntityID);let h=this.ctx.data.user.state?.Tutorial?.Flows?.[r]?.RewardClaimed===true,y=await i(c);return y.ok&&(this.applyFlowView(y.data),this.mayHavePaid(r,o,h,y.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",y.data)),y}mayHavePaid(e,t,i,n){return !i&&n.Flow?.RewardClaimed===true?true:n.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Ln)?.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 Gn=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return a;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return u("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return u("client","campaignID is required.");if(!t)return u("client","walletAddress is required.");let n=this.ctx.authedRequest();if(!n)return a;n.CampaignID=e,n.WalletAddress=t,i&&(n.Amount=i);let r=await this.ctx.api.communityMarketing.withdrawCryptoReward(n);return r.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",r.data),r}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var qe=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 Iy={Global:"Global",Announcement:"Announcement",Group:"Group"},Ou=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),vy={None:"None",Language:"Language",Region:"Region"},Ty=zod.z.enum(["None","Language","Region"]).catch("None"),Ay={Anyone:"Anyone",Friends:"Friends"},wy=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),ky={Reject:"Reject",Mask:"Mask"},zy=zod.z.enum(["Reject","Mask"]).catch("Reject"),My={Player:"Player",Publisher:"Publisher",System:"System"},Oy=zod.z.enum(["Player","Publisher","System"]).catch("Player"),Ey={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Uy=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),Eu=zod.z.object({Gate:Z.nullish(),Schedule:Re.nullish()}).passthrough(),Uu=zod.z.object({Gate:Z.nullish(),Limits:Se.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),qu=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),qy=zod.z.object({Availability:Q.nullish(),Write:Q.nullish(),Retention:Q.nullish()}).passthrough(),Ly=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:Uy.nullish(),Type:Ou.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:Ty.nullish(),Capacity:zod.z.number().nullish(),Availability:Eu.nullish(),Write:Uu.nullish(),Retention:qu.nullish(),Presets:qy.nullish()}).passthrough(),By=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:wy.nullish(),Limits:Se.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),Gy=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:zy.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Se.nullish()}).passthrough(),_y=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),Fy=zod.z.object({Availability:zod.z.record(zod.z.string(),Eu).nullish(),Write:zod.z.record(zod.z.string(),Uu).nullish(),Retention:zod.z.record(zod.z.string(),qu).nullish()}).passthrough(),Lu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),Ly).nullish(),Direct:By.nullish(),Moderation:Gy.nullish(),Polling:_y.nullish(),Presets:Fy.nullish()}).passthrough(),Vy=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),Mu=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(),Vy).nullish(),Limits:zod.z.record(zod.z.string(),Mu).nullish(),ReportLimits:Mu.nullish()}).passthrough();var Bo=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),_n=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:qe.nullish(),AuthorType:Oy.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),Ny=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:Ou.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(),Fn=zod.z.object({Channels:zod.z.array(Ny).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),jy=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(_n).nullish(),NextCursor:Bo.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Bu=zod.z.object({Rooms:zod.z.array(jy).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Gu=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(_n).nullish(),NextBefore:Bo.nullish()}).passthrough(),_u=zod.z.object({Message:_n.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),Fu=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:qe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Wy=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:qe.nullish(),LastMessage:_n.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Vu=zod.z.object({Conversations:zod.z.array(Wy).nullish()}).passthrough(),Si=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:Bo.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),Nu=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),$e={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 ju="Chat",Wu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Vn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Wu,{schema:Fn,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(ju,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.chat.getChatDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ju,n.data),this.ctx.emitter.emit("chat:definitionsLoaded",n.data)),n}getChannels(e,t){return this.ctx.cache.read(Wu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let n of i.data.Rooms??[])n.NextCursor&&n.RoomID&&this.cursors.set(n.RoomID,n.NextCursor),n.Messages&&n.Messages.length>0&&this.ctx.emitter.emit("chat:messages",n);return i}async getHistory(e,t,i){let n=this.ctx.authedRequest();return n?(n.RoomID=e,t&&(n.Before=t),i&&(n.Limit=i),this.ctx.api.chat.getHistory(n)):a}async sendMessage(e,t,i){let n=this.ctx.authedRequest();if(!n)return a;n.ChannelID=e,n.Text=t,i&&(n.Locale=i);let r=await this.ctx.api.chat.sendMessage(n);return r.ok&&this.ctx.emitter.emit("chat:sent",r.data),r}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Text=t;let n=await this.ctx.api.chat.sendMessage(i);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):a}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):a}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let n=await this.ctx.api.chat.markRead(i);return n.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),n}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):a}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):a}async reportMessage(e,t,i,n){let r=this.ctx.authedRequest();return r?(r.RoomID=e,r.MessageID=t,r.Reason=i,n&&(r.Comment=n),this.ctx.api.chat.reportMessage(r)):a}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):a}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):a}resetCursors(){this.cursors.clear();}};var Ky={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},Qy=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),Hy={Player:"player",Title:"title",Creator:"creator"},xi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Ku=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),$y=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),Go=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:Qy.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array($y).nullish()}).passthrough(),Qu=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(Go).nullish()}).passthrough(),zt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var Jy="IDOS_PLATFORM_PUSH_REQUEST",Zy="IDOS_PLATFORM_PUSH_RESPONSE",Yy=12e4;function Hu(s){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let n=false,r=h=>{n||(n=true,window.removeEventListener("message",o),clearTimeout(c),i(h));},o=h=>{let y=h?.data;!y||y.type!==Zy||y.requestId!==t||Tt.includes(h.origin)&&r(y.ok===true);},c=setTimeout(()=>r(false),Yy);window.addEventListener("message",o);for(let h of Tt)try{e.postMessage({type:Jy,requestId:t,titleID:s},h);}catch{}})}var Nn=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),n=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=n,i.ok&&this.ctx.emitter.emit("push:configLoaded",n),n}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return zt.Unsupported;if(this.isEmbedded())return zt.Embedded;if(!this.isSupported())return zt.Unsupported;let t=Notification.permission;return t==="denied"?zt.Blocked:t!=="granted"?zt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?zt.Subscribed:zt.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return u("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Hu(this.ctx.settings.titleID)?V({Where:"portal",Subscription:null}):u("client","The portal did not complete the subscription.");if(!this.isSupported())return u("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return u("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let n=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await n.pushManager.getSubscription()??await n.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:Xy(t.PublicKey)}),c=this.ctx.authedRequest();if(!c)return a;let h=o.toJSON();c.PushEndpoint=h.endpoint,c.PushP256dh=h.keys?.p256dh,c.PushAuth=h.keys?.auth,c.PushTransport="WebPush",c.PushLocale=e.locale??navigator.language,c.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let y=await this.ctx.api.push.subscribePush(c);return y.ok?(this.ctx.emitter.emit("push:subscribed",y.data),V({Where:"game",Subscription:y.data})):y}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return a;if(this.isSupported()){let n=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();n&&(e.PushEndpoint=n.endpoint,await n.unsubscribe());}if(!e.PushEndpoint)return u("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):a}async unsubscribeByHash(e){if(!e)return u("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return a;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function Xy(s){let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),n=new Uint8Array(i);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return i}var jn=Object.freeze({}),Wn=class{constructor(e){this.ctx=e;}ctx;table={...jn};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new Ci(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),n=this.lookup(i)??this.lookup(e);return n===void 0?this.onMissing(e):t?eR(n,t):n}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...jn},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return a;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:n,table:r,fallbackLocale:o}=i.data,c=null;if(o){let h=await this.loadTableFromApi(o);h.ok&&(c=h.data.table);}return this.table=r,this.fallbackTable=c,this.currentFallbackLocale=o,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:o,entryCount:Object.keys(r).length}),{ok:true,data:n}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):a}reset(){this.table={...jn},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:B()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return a;t.Locale=e;let i=await this.cache.read($u(e));i&&(t.KnownVersion=i.v);let n=await this.ctx.api.localization.getLocalizationTable(t);if(!n.ok)return n;let r=n.data,o=r.Locale??$u(e),c=r.Version??0;if(r.NotModified){let y=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:y?.t??{...jn},fallbackLocale:r.FallbackLocale??null}}}let h=r.Entries??{};return c>0&&await this.cache.write(o,c,h),{ok:true,data:{locale:o,table:h,fallbackLocale:r.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let n=this.pluralCategory(i),r=`${e}.${n}`;if(this.lookup(r)!==void 0)return r;let o=`${e}.other`;return this.lookup(o)!==void 0?o:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function eR(s,e){return s.replace(/\{(\w+)\}/g,(t,i)=>{let n=e[i];return n===void 0?t:String(n)})}function $u(s){return s.trim().replace(/_/g,"-").toLowerCase()}var _o="Quest",tR={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:s=>{let e=Date.now(),t=null,i=[...Object.values(s.PointsTracks??{}).map(n=>n?.CycleEndUtc),...Object.values(s.State?.Cycles??{}).map(n=>n?.CycleEndUtc)];for(let n of i){let r=Date.parse(n??"");!Number.isNaN(r)&&r>e&&(t===null||r<t)&&(t=r);}return t}},Kn=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let n=e.cache.configSection(_o)?.Cycles;if(!n)return false;let r=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(n)){let c=Date.parse(r[o]?.CycleEndUtc??"");if(Number.isNaN(c)){if(t===0)return true}else if(c<=i&&t<c)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true,{forceRefresh:true});return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(_o,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.quest.getQuestDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(_o,n.data),this.ctx.emitter.emit("quest:definitionsLoaded",n.data)),n}getUserQuestState(e=true,t){return this.ctx.cache.read(tR,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let n=i.data.State??{};this.ctx.data.user.applyQuest(n),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",n);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let i=e.trim();if(!i)return u("client","QuestID is required.");if(!this.ctx.auth.context)return a;let n=t&&t.trim().length>0?t.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:n,RelatedEntityID:`quest_claim_${n??""}_${i}_${B()}`},o=await this.ctx.api.quest.claimQuestReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchQuestStatus(c.QuestID,c.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",c);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return u("client","quests is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||(this.ctx.data.user.patchQuestStatus(r.Data.QuestID,r.Data.CycleID,"Claimed"),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return u("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:n,RelatedEntityID:`milestone_claim_${i}_${n}_${B()}`},o=await this.ctx.api.quest.claimMilestoneReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchMilestoneClaimed(c.CycleID,c.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",c);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||(this.ctx.data.user.patchMilestoneClaimed(r.Data.CycleID,r.Data.MilestoneID),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return u("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:n,RelatedEntityID:`group_completion_${i}_${n}_${B()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchGroupCompletionClaimed(c.CycleID,c.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",c);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return u("client","MetricID is required.");if(t<0)return u("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},r=await this.ctx.api.quest.addQuestProgress(n);return r.ok&&(this.ctx.data.user.patchQuestProgressUpdates(r.data.Updates),this.ctx.emitter.emit("quest:progressAdded",r.data)),r}};var Ju=zod.z.object({}).passthrough().transform(s=>s);var iR=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),nR=zod.z.object({Schedule:zod.z.array(iR).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),rR=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:p.nullish(),NextBonusStartUtc:p.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),sR=zod.z.object({Milestones:Q.nullish()}).passthrough(),Fo=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:$t.nullish(),TokenSources:zod.z.array(ot).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:sR.nullish(),BonusWindow:nR.nullish()}).passthrough(),oR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:Fo.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),aR=zod.z.object({TimedEventID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:Re.nullish(),Content:Fo.nullish(),Events:zod.z.array(oR).nullish(),Gate:Z.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),lR=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),uR=zod.z.object({Milestones:zod.z.record(zod.z.string(),mi).nullish()}).passthrough(),Qn=zod.z.object({Definitions:zod.z.record(zod.z.string(),aR).nullish(),Settings:lR.nullish(),Presets:uR.nullish()}).passthrough(),cR=zod.z.object({Type:zi,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:Fo.nullish(),Progress:Ju.nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:_e.nullish(),BonusWindow:rR.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),Hn=zod.z.object({ActiveEvents:zod.z.array(cR).nullish()}).passthrough(),Zu=zod.z.object({Tokens:zod.z.record(zod.z.string(),Ju).nullish()}),Vo=zod.z.object({Type:zi.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),No=zod.z.object({Type:zi.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:M.nullish(),Inventory:K.nullish()}),pR=zod.z.object({Type:zi.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),jo=zod.z.array(we(No)),Yu=zod.z.array(we(Vo)),Xu=zod.z.array(we(pR)),ut={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var ec="TimedEvent",tc={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:s=>{let e=null;for(let t of s.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},$n=class{constructor(e){this.ctx=e;e.cache.bindLoginView(tc,{schema:Hn,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(tc,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(ec,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.timedEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ec,n.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",n.data)),n}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,n,r,o,c=1){if(!t)return u("client","LteID is required.");if(!i)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:n,AmountOverride:r,SourceParams:o,RollMultiplier:c},y=await this.ctx.api.timedEvent.grantTokens(h);return y.ok&&(this.ctx.data.user.applyResourceOperation(y.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",y.data)),y}async spendTokens(e,t,i){if(!t)return u("client","LteID is required.");if(i<=0)return u("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},r=await this.ctx.api.timedEvent.spendTokens(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",r.data)),r}async claimMilestone(e,t,i){if(!t||!i)return u("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},r=await this.ctx.api.timedEvent.claimMilestone(n);if(r.ok){let o=r.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return r}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return a;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return u("client","spends is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(r.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return u("client","grants is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(r.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let n=i.Data;n.Type&&n.LteID&&n.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(n.Type,n.LteID,n.MilestoneID,n.TokenEntityID),!t&&n.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(n.Rewards,n.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var dR=zod.z.object({UserID:zod.z.string(),Score:j.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:p.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:qe.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),Ui=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:j.nullish(),CycleEndUtc:p.nullish(),TopUsers:zod.z.array(dR).nullish(),BracketID:zod.z.string().nullish()}),hR=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:p.nullish(),ClaimDeadlineUtc:p.nullish(),MilestoneTokensEarned:j.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Jn=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:j.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:j.nullish(),MilestoneTokensEarned:j.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(hR).nullish()}),Zn=zod.z.object({LeaderboardID:zod.z.string(),NewScore:j,CycleVersion:zod.z.number()}),Yn=zod.z.object({ServerTimeUtc:p,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Xn=zod.z.object({ServerTimeUtc:p,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:M.nullish(),Inventory:K.nullish()}),ic=zod.z.array(we(Ui)),er=zod.z.array(we(Jn)),nc=zod.z.array(we(Yn)),rc=zod.z.array(we(Xn)),sc=zod.z.array(we(Zn)),mR=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:we(Yn).nullish(),Milestones:zod.z.array(we(Xn)).nullish()}),oc=zod.z.array(mR),fR=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:we(Ui).nullish(),Progress:we(Jn).nullish()}),ac=zod.z.array(fR),gR=zod.z.string(),lc=zod.z.object({Rank:zod.z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:po.nullish()}).passthrough(),yR=zod.z.object({RankRewards:zod.z.array(lc).nullish()}).passthrough(),RR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),CR=zod.z.object({Milestones:Q.nullish(),RankRewards:Q.nullish()}).passthrough(),SR=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:gR.nullish(),Schedule:Re.nullish(),ChainEvents:zod.z.array(RR).nullish(),Gate:Z.nullish(),TopUsersLimit:zod.z.number().nullish(),MinScoreToEnterTop:zod.z.number().nullish(),BracketSize:zod.z.number().nullish(),LinkedSeasonChainID:zod.z.string().nullish(),RankRewards:zod.z.array(lc).nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:CR.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(ot).nullish()}).passthrough(),xR=zod.z.object({Milestones:zod.z.record(zod.z.string(),mi).nullish(),RankRewards:zod.z.record(zod.z.string(),yR).nullish()}).passthrough(),tr=zod.z.object({Definitions:zod.z.record(zod.z.string(),SR).nullish(),Presets:xR.nullish()}).passthrough(),je={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 uc="Leaderboard",cc={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"]},ir=class{constructor(e){this.ctx=e;e.cache.bindLoginView(cc,{schema:er,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(uc,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.leaderboard.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(uc,n.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",n.data)),n}async getLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return u("client","LeaderboardID is required.");if(t<=0)return u("client","Score must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},n=await this.ctx.api.leaderboard.submitScore(i);if(n.ok){let r=n.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),r.NewScore,t,r.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",r);}return n}async submitScoreFromSource(e,t,i,n,r=1){if(!e)return u("client","LeaderboardID is required.");if(!t)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:n,RollMultiplier:r},c=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(c.ok){let h=c.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),h.NewScore,h.NewScore,h.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",h);}return c}async claimCycleReward(e){if(!e)return u("client","LeaderboardID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",n);}return i}async claimMilestone(e,t,i){if(!e||!t)return u("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},r=await this.ctx.api.leaderboard.claimMilestone(n);if(r.ok){let o=r.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",o);}return r}async getFriendsLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(u("client","leaderboardIDs is required.")):this.ctx.cache.read(cc,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(n.Data.LeaderboardID)),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(n.Data.LeaderboardID),n.Data.MilestoneID),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return u("client","scores is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(n.Data.LeaderboardID),n.Data.NewScore,n.Data.NewScore,n.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let n of i.data){let r=this.cycleDocID(n.LeaderboardID);n.CycleReward?.Success&&n.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(r),n.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.CycleReward.Data.Resources,n.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of n.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(r,o.Data.MilestoneID),o.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(o.Data.Resources,o.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let n of i.data)n.Progress?.Success&&n.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(n.LeaderboardID),n.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var Wo=zod.z.object({}).passthrough().transform(s=>s),nr=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>mc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:j.nullish(),UserState:Wo.nullish(),NextTier:zod.z.lazy(()=>hc).nullish()}).passthrough(),pc=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:j.nullish(),NewStatusTokens:j.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),Ko=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:M.nullish(),Inventory:K.nullish()}),dc=Rt(Ko);var hc=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:j.nullish(),TierReachedReward:H.nullish()}).passthrough(),mc=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:j.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(hc).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var bR=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Seasons:zod.z.array(mc).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:Z.nullish()}).passthrough(),rr=zod.z.object({Chains:zod.z.record(zod.z.string(),bR).nullish()}).passthrough(),Gt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var fc="Season",gc={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:s=>{let e=Date.parse(s.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},sr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(gc,{schema:nr,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(fc,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.season.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(fc,n.data),this.ctx.emitter.emit("season:definitionsLoaded",n.data)),n}getActiveSeason(e,t){return e?this.ctx.cache.read(gc,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(u("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return u("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","Amount must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${B()}`},n=await this.ctx.api.season.grantStatusTokens(i);return n.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,n.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",n.data)),n}async claimTierReward(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","TierNumber must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${B()}`},n=await this.ctx.api.season.claimTierReward(i);if(n.ok){let r=n.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",r);}return n}async claimTierRewardsBatch(e,t){if(!e)return u("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return u("client","TierNumbers is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${B()}`},r=await this.ctx.api.season.claimTierRewardsBatch(n);if(r.ok){let o=r.data;for(let c of o.Items??[]){let h=c.Data?.TierNumber;c.Success&&typeof h=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,h);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return r}};var yc="Premium",or=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(yc,e);if(t){let r={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",r),V(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.premium.getDefinitions(i);return n.ok&&n.data.Premium&&(this.ctx.data.config.patchSection(yc,n.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},n=await this.ctx.api.premium.activateTrial(i);return n.ok&&(n.data.Premium&&this.ctx.data.user.applyPremium(n.data.Premium),this.ctx.emitter.emit("premium:trialActivated",n.data)),n}async purchaseItemOrCurrency(e,t,i="Default",n=1,r){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:n,CreditsConfirmationID:r,RelatedEntityID:`premium_purchase_${e}_${t}`},c=await this.ctx.api.premium.purchaseItemOrCurrency(o);if(c.ok&&!c.data.CreditsConfirmation){let h=c.data;h.Premium&&this.ctx.data.user.applyPremium(h.Premium),this.ctx.data.user.applyResourceOperation(h.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",h);}return c}async purchaseRealMoney(e,t,i,n,r,o,c,h){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!n||!r)return u("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return a;let y={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:n,ReceiptData:r,PurchaseToken:o,PackageName:c,AppStoreEnvironment:h,RelatedEntityID:`premium_iap_${e}_${t}`},F=await this.ctx.api.premium.purchaseRealMoney(y);if(F.ok){let oe=F.data;oe.Premium&&this.ctx.data.user.applyPremium(oe.Premium),this.ctx.data.user.applyResourceOperation(oe.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",oe);}return F}};var ar=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:p.nullish()}),Qo=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:j.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),ar).nullish(),UpdatedAt:p.nullish()}).passthrough(),Rc=zod.z.object({Characters:zod.z.record(zod.z.string(),Qo).nullish()}),Ho=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),$o=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),Cc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),ar).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Sc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),DR=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),xc=zod.z.object({ServerTimeUtc:p,Characters:zod.z.record(zod.z.string(),DR).nullish(),Inventory:K.nullish()}),Jo=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:M.nullish()}),bc=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:M.nullish(),Inventory:K.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:ar.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Dc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:ar.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Pc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),PR=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:p.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:ce.nullish()}),IR=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(PR).nullish()}),Ic=zod.z.object({ServerTimeUtc:p,Characters:zod.z.record(zod.z.string(),IR).nullish()}),vc=Rt(Jo),Tc=Rt($o),Ac=Rt(Ho),Zo=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),wc=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:ce.nullish(),CostCurve:Ne.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Ne.nullish(),RankCurve:Ne.nullish(),Requirements:zod.z.array(Zo).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),vR=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Zo).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(),kc=zod.z.object({Slots:zod.z.record(zod.z.string(),vR).nullish()}).passthrough(),zc=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(),TR=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),AR=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:ce.nullish()}).passthrough(),wR=zod.z.object({Stats:Q.nullish(),Levels:Q.nullish(),Equipment:Q.nullish()}).passthrough(),Mc=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:Ne.nullish()}).passthrough(),Yo="@skin";function kR(s){return !!s&&s.startsWith("@")}var zR=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),MR=zod.z.object({PriceOptions:ce.nullish(),Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),OR=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Zo).nullish()}).passthrough(),ER=zod.z.object({SkinID:zod.z.string().nullish(),Identity:zc.nullish(),Item:zR.nullish(),Sale:MR.nullish(),Requirements:OR.nullish()}).passthrough(),UR=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),ER).nullish()}).passthrough(),qR=zod.z.object({CharacterID:zod.z.string(),Identity:zc.nullish(),Classification:TR.nullish(),Unlock:AR.nullish(),Presets:wR.nullish(),Equipment:kc.nullish(),Stats:zod.z.record(zod.z.string(),wc).nullish(),RankLadder:Mc.nullish(),RankStatCurve:Ne.nullish(),StatMaxLevelCurve:Ne.nullish(),Skins:UR.nullish()}).passthrough(),LR=zod.z.object({Stats:zod.z.record(zod.z.string(),wc).nullish()}).passthrough(),BR=zod.z.object({RankLadder:Mc.nullish()}).passthrough(),GR=zod.z.object({Equipment:kc.nullish()}).passthrough(),_R=zod.z.object({Stats:zod.z.record(zod.z.string(),LR).nullish(),Levels:zod.z.record(zod.z.string(),BR).nullish(),Equipment:zod.z.record(zod.z.string(),GR).nullish()}).passthrough(),lr=zod.z.object({Definitions:zod.z.record(zod.z.string(),qR).nullish(),Presets:_R.nullish()}).passthrough(),We={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"},FR="SKIN_ALREADY_OWNED";var Xo="Character",ur=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Xo)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([n,r])=>r?.Unlock?.UnlockedByDefault===true&&!i[r.CharacterID??n])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(Xo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.character.getCharacterDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Xo,n.data),this.ctx.emitter.emit("character:definitionsLoaded",n.data)),n}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${B()}`},n=await this.ctx.api.character.unlockCharacter(i);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},r.Power!=null&&(o.Power=r.Power),o.UpdatedAt=r.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",r);}return n}async upgradeStatLevel(e,t,i){if(!e||!t)return u("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${B()}`,SelectedOptionID:i?.selectedOptionID,CreditsConfirmationID:i?.creditsConfirmationID,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},r=await this.ctx.api.character.upgradeStatLevel(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;this.ctx.data.user.patchCharacter(o.CharacterID,c=>{c.StatLevels??={},c.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(c.Power=o.Power),c.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return r}async upgradeCharacterLevel(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${B()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},n=await this.ctx.api.character.upgradeCharacterLevel(i);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,o=>{o.Level=r.NewLevel,r.Power!=null&&(o.Power=r.Power),o.UpdatedAt=r.ServerTimeUtc,r.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",r);}return n}async equipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},n=await this.ctx.api.character.equipItems(i);return n.ok&&(this.applyEquipChangesLocally(e,n.data),this.ctx.emitter.emit("character:itemsEquipped",n.data)),n}async unequipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},n=await this.ctx.api.character.unequipItems(i);if(n.ok){let r=n.data;this.applyUnequipChangesLocally(e,r),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:r.ClearedSlotIDs??[],power:r.Power??null});}return n}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${B()}`},r=await this.ctx.api.character.unlockSkin(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),o.Equipped&&o.Equipment&&this.applySkinLocally(o.CharacterID,o.Equipment,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",o);}return r}async equipSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},r=await this.ctx.api.character.equipSkin(n);if(r.ok){let o=r.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return r}async unequipSkin(e){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let n=i.data;n.Cleared&&(this.applyInventoryDelta(n.Inventory),this.applySkinLocally(n.CharacterID,null,n.Power,n.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",n);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):a}applySkinLocally(e,t,i,n){let r=this.ctx.data.user;r.patchCharacterEquipment(e,Yo,t??null),r.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=n;});}async unlockCharactersBatch(e){if(!e||e.length===0)return u("client","characterIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level??=1,r.StatLevels??={},r.Equipment??={},n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level=n.NewLevel,n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(r.StatLevels??={},r.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.StatLevels??={},r.StatLevels[n.StatID]=n.StatLevel,n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[n,r]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,n,r);i.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let r of i)n.patchCharacterEquipment(e,r,null);n.patchCharacter(e,r=>{t.Power!=null&&(r.Power=t.Power),r.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,n]of Object.entries(e.Characters??{})){for(let r of n.ClearedSlotIDs??[])t.patchCharacterEquipment(i,r,null);t.patchCharacter(i,r=>{n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=e.ServerTimeUtc;});}}};var Oc="Match",cr=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,n,r,o){let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:n,TargetUserID:r,SelectedOptionID:o,RelatedEntityID:`pvp_create_${c.userID}_${B()}`},y=await this.ctx.api.match.createMatch(h);return y.ok&&(this.ctx.data.user.applyResourceOperation(y.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",y.data)),y}async updateMatch(e,t={}){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},n=await this.ctx.api.match.updateMatch(i);return n.ok&&this.ctx.emitter.emit("match:updated",n.data),n}async cancelMatch(e){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,n){let r=this.ctx.auth.context;if(!r)return a;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:n,RelatedEntityID:`pvp_battle_${e}_${B()}`},c=await this.ctx.api.match.instantBattle(o);if(c.ok){let h=c.data,y=this.ctx.data.config.itemDefinitions;if(h.Resources)this.ctx.data.user.applyResourceOperation(h.Resources,y);else if(h.ResourcesDual){let F=h.ResourcesDual;F.FromUserID===r.userID&&F.FromResult?this.ctx.data.user.applyResourceOperation(F.FromResult,y):F.ToUserID===r.userID&&F.ToResult&&this.ctx.data.user.applyResourceOperation(F.ToResult,y);}this.ctx.emitter.emit("match:instantBattleCompleted",h);}return c}async saveStrategy(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let n=this.ctx.authedRequest();if(!n)return a;n.Page=e,n.PageSize=t,n.Statuses=i;let r=await this.ctx.api.match.getMyMatches(n);return r.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",r.data),r}async getAvailableMatches(e=0,t=20,i=false){let n=this.ctx.authedRequest();if(!n)return a;n.Page=e,n.PageSize=t,n.OnlyPublic=i;let r=await this.ctx.api.match.getAvailableMatches(n);return r.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",r.data),r}async getDefinitions(e){let t=this.ctx.cache.configSection(Oc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.match.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Oc,n.data),this.ctx.emitter.emit("match:definitionsLoaded",n.data)),n}};var Ec="Craft",pr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ec,e);if(t){let r={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),V(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.craft.getDefinitions(i);return n.ok&&n.data.CraftDefinitions&&(this.ctx.data.config.patchSection(Ec,n.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",n.data.CraftDefinitions)),n}async craft(e,t,i=1,n,r,o){if(!e)return u("client","CraftID is required.");let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:n,InputInstanceIDs:r,CreditsConfirmationID:o,RelatedEntityID:`craft_${e}_${c.userID}_${B()}`},y=await this.ctx.api.craft.craft(h);return y.ok&&!y.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(y.data.Resources,y.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",y.data)),y}};var _t=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(_t),zod.z.record(zod.z.string(),_t)]));var Ft={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Uc=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Yt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function qi(s){return s!==Yt.Pending&&s!==Yt.Running}var VR={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 NR(s){return s?/\b(AI_[A-Z_]+)\s*:/.exec(s)?.[1]??null:null}var jR=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),WR=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),dr=zod.z.object({CreditsConfirmation:fe.nullish(),GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Uc.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),_t).nullish(),Assets:zod.z.array(jR).nullish(),Error:WR.nullish(),Charge:M.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:M.nullish(),Context:zod.z.record(zod.z.string(),_t).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish()}),qc=zod.z.object({Data:zod.z.array(dr).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),KR=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(),QR=zod.z.object({Modality:Uc.nullish(),Async:zod.z.boolean().nullish(),Limits:Se.nullish(),PriceOptions:ce.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:H.nullish(),PromptVariables:zod.z.array(KR).nullish(),AllowFreePrompt:zod.z.boolean().nullish()}).passthrough(),Lc=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),QR).nullish()}).passthrough(),Ve={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"};var Bc="AI",HR=/^[A-Za-z0-9_-]{1,128}$/,$R=2e3,JR=5e3,ZR=30*6e4;function YR(s,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(n),e?.removeEventListener("abort",i),t();},n=setTimeout(i,s);e?.addEventListener("abort",i,{once:true});})}var hr=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(Bc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.ai.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Bc,n.data),this.ctx.emitter.emit("ai:definitionsLoaded",n.data)),n}generateText(e,t,i){return this.generate(e,{Text:t},i,n=>this.ctx.api.ai.generateText(n))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,n=>this.ctx.api.ai.generateImage(n))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,n=>this.ctx.api.ai.editImage(n))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,n=>this.ctx.api.ai.generateVideo(n))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,n=>this.ctx.api.ai.generateAudio(n))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,n=>this.ctx.api.ai.generateMusic(n))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,n=>this.ctx.api.ai.generateThreeD(n))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):a}async getGeneration(e){if(!e)return u("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):a}isTerminal(e){return qi(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let c=await this.getGeneration(e);if(!c.ok)return c;i=c.data;}else {if(!e?.GenerationID)return u("client","GenerationID is required.");i=e;}let n=Date.now()+(t.timeoutMs??ZR),r=Math.max(1,t.intervalMs??$R),o=Math.max(r,t.maxIntervalMs??JR);for(;!qi(i.Status);){if(t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");if(Date.now()+r>n)return u("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await YR(r,t.signal),t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");let c=await this.pollFor(i);if(r=Math.min(o,Math.round(r*1.5)),!c.ok){if(c.reason==="connection")continue;return c}i=c.data,qi(i.Status)||t.onUpdate?.(i);}return V(i)}pollFor(e){switch(e.Modality){case Ft.Text:return this.getText(e.GenerationID);case Ft.Image:return this.getImage(e.GenerationID);case Ft.Audio:return this.getAudio(e.GenerationID);case Ft.Music:return this.getMusic(e.GenerationID);case Ft.Video:return this.getVideo(e.GenerationID);case Ft.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,n){if(!e)return u("client","FeatureKey is required.");let r=i?.relatedEntityID;if(r!==void 0&&!HR.test(r))return u("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,Variables:i?.variables,Context:i?.context,RelatedEntityID:r??B()},c=await n(o);return c.ok&&!c.data.CreditsConfirmation&&(await this.reconcileCharge(c.data,true),this.emitView(c.data)),c}async poll(e,t){if(!e)return u("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.GenerationID=e;let n=await t(i);return n.ok&&(await this.reconcileCharge(n.data,false),this.emitView(n.data)),n}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Yt.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===Yt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Yt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var ea="Collection",mr=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let i=e.cache.configSection(ea),n=Object.keys(i?.Collections??{});if(n.length===0||t)return false;let r=e.cache.configSection("Season");return Object.values(r?.Chains??{}).some(c=>(c?.Seasons??[]).some(h=>!!h?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==n[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ea,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.collection.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ea,n.data),this.ctx.emitter.emit("collection:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,n){let r=this.ctx.auth.context;if(!r)return a;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${r.userID}_${B()}`},c=await this.ctx.api.collection.openPack(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",c.data)),c}async openCollectionChest(e,t,i=1){let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${n.userID}_${B()}`},o=await this.ctx.api.collection.openCollectionChest(r);return o.ok&&(this.ctx.data.user.applyResourcesWithDelta(o.data.Resources,o.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",o.data)),o}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${B()}`},r=await this.ctx.api.collection.useCollectibleJoker(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",r.data)),r}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${B()}`},r=await this.ctx.api.collection.claimSetReward(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",r.data)),r}async claimSetRewardsBatch(e){if(!e||e.length===0)return u("client","sets is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${B()}`},n=await this.ctx.api.collection.claimGrandPrize(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",n.data)),n}async sendTradeOffer(e,t,i,n,r,o=false){let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:n,RequestedCollectibleID:r,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${c.userID}_${n}_${B()}`},y=await this.ctx.api.collection.sendTradeOffer(h);return y.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",y.data)),y}async cancelTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${B()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${B()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${B()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var XR=zod.z.object({}).passthrough().transform(s=>s),eC={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},tC={Active:"Active",Left:"Left",Replaced:"Replaced"},iC=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),nC=zod.z.object({UserID:zod.z.string().nullish(),PublicData:qe.nullish(),BuildObjectsProgress:iC.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),rC=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(),sC=zod.z.object({Objects:zod.z.array(rC).nullish()}).passthrough(),Gc=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(nC).nullish(),BuildObjectsState:sC.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:zod.z.number().nullish()}).passthrough(),_c=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>Fc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),oC=zod.z.string(),ta=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(),aC=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:H.nullish()}).passthrough(),lC=zod.z.object({Objects:zod.z.array(aC).nullish(),PriceOptions:ce.nullish(),SpinnerTable:zod.z.array(ta).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),Fc=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:oC.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:lC.nullish(),GrandPrize:H.nullish()}).passthrough(),uC=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Events:zod.z.array(Fc).nullish(),Gate:Z.nullish()}).passthrough(),fr=zod.z.object({ServerTimeUtc:p.nullish(),UserState:XR.nullish(),ActiveGroup:Gc.nullish()}),ia=zod.z.object({ServerTimeUtc:p.nullish(),Group:Gc.nullish(),SecondsRemaining:j.nullish()}),Vc=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Resources:M.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:ta.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(ta).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),na=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Nc=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),gr=zod.z.object({Chains:zod.z.record(zod.z.string(),uC).nullish()}).passthrough(),ft={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var jc="CoopEvent",Wc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},yr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Wc,{schema:fr,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(jc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.coopEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(jc,n.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",n.data)),n}async getActiveEvent(e){if(!e)return u("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(Wc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return u("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return u("client","CoopChainID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let n=i.data.Group;n&&this.ctx.data.user.patchCoopEventActiveGroup(n.GroupID??null,n.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,n,r){if(!e||!t)return u("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:n,CreditsConfirmationID:r,RelatedEntityID:B()},c=await this.ctx.api.coopEvent.spin(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(c.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",c.data)),c}async claimObjectReward(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var cC={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},pC={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},dC=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:p.nullish(),CompletedAtUtc:p.nullish(),LastExecutedAtUtc:p.nullish(),NextAvailableAtUtc:p.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),hC=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),Kc=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:p.nullish(),ExhaustedAtUtc:p.nullish(),ExpiredAtUtc:p.nullish(),DismissedAtUtc:p.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:p.nullish(),Nodes:zod.z.record(zod.z.string(),dC).nullish(),Tracks:zod.z.record(zod.z.string(),hC).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),mC=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:p.nullish(),ActiveOfferExpiresAtUtc:p.nullish(),ActiveOffer:Kc.nullish(),NextCycleStartsAtUtc:p.nullish(),LastUpdatedUtc:p.nullish(),DismissSkipAvailableAtUtc:p.nullish(),LastDismissedAtUtc:p.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),fC=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),gC=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:p.nullish(),LastActivatedAtUtc:p.nullish(),LastExhaustedAtUtc:p.nullish(),NodeCounts:zod.z.record(zod.z.string(),fC).nullish()}).passthrough(),yC=zod.z.object({Slots:zod.z.record(zod.z.string(),mC).nullish(),OfferHistory:zod.z.record(zod.z.string(),gC).nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),RC={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},CC={Eq:"Eq",Gte:"Gte",Lte:"Lte"},SC=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),Rr=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(),Qc=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),Hc=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),xC=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Behaviour:Q.nullish()}).passthrough(),bC=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:Rr.nullish(),Availability:Qc.nullish(),Behaviour:Hc.nullish(),Queue:zod.z.array(SC).nullish(),Presets:xC.nullish()}).passthrough(),DC=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),PC=zod.z.object({RewardedVideo:DC.nullish()}).passthrough(),IC=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),vC=zod.z.object({Identity:Q.nullish(),Graph:Q.nullish(),Milestones:Q.nullish()}).passthrough(),TC=zod.z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish()}).passthrough(),AC=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),wC=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(),kC=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(IC).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),$c=zod.z.object({Options:ce.nullish()}).passthrough(),Jc=zod.z.object({Grants:H.nullish(),TrackChanges:zod.z.array(AC).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),zC=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:Rr.nullish(),Pricing:$c.nullish(),Reward:Jc.nullish(),Action:PC.nullish(),UnlockRules:kC.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:Se.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:TC.nullish()}).passthrough(),Zc=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(zC).nullish(),Tracks:zod.z.array(wC).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),Yc=zod.z.object({Milestones:zod.z.record(zod.z.string(),_e).nullish(),ClaimMode:zod.z.string().nullish(),Token:$t.nullish()}).passthrough(),Xc=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:Rr.nullish(),Graph:Zc.nullish(),Milestones:Yc.nullish(),Presets:vC.nullish()}).passthrough(),MC=zod.z.object({Identity:zod.z.record(zod.z.string(),Rr).nullish(),Availability:zod.z.record(zod.z.string(),Qc).nullish(),Behaviour:zod.z.record(zod.z.string(),Hc).nullish(),Graph:zod.z.record(zod.z.string(),Zc).nullish(),Milestones:zod.z.record(zod.z.string(),Yc).nullish(),Pricing:zod.z.record(zod.z.string(),$c).nullish(),Reward:zod.z.record(zod.z.string(),Jc).nullish()}).passthrough(),ra=zod.z.object({Slots:zod.z.record(zod.z.string(),bC).nullish(),Offers:zod.z.record(zod.z.string(),Xc).nullish(),Presets:MC.nullish()}).passthrough(),ep=zod.z.object({DealOfferDefinitions:ra.nullish()}),tp=zod.z.object({DealOffers:yC.nullish()}),OC=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(),EC=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:Xc.nullish(),ActivationState:Kc.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:p.nullish(),Cost:It.nullish(),Milestone:OC.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),Cr=zod.z.object({Slots:zod.z.array(EC).nullish()}),ip=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),np=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),rp=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),sp=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),op=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:M.nullish(),Inventory:K.nullish()}),St={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var UC="DealOffer",ap={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},Sr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ap,{schema:Cr,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(UC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(ap,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${B()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,n){if(!e||!t)return u("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return a;let r=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:r??`deal_exec_${e}_${t}_${B()}`},c=await this.ctx.api.dealOffer.executeNode(o);return c.ok&&!c.data.CreditsConfirmation&&(c.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",c.data)),c}async recordShow(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${B()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return u("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${B()}`},n=await this.ctx.api.dealOffer.claimMilestone(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",n.data)),n}async claimMilestonesBatch(e,t){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${B()}`},r=await this.ctx.api.dealOffer.claimMilestonesBatch(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",r.data)),r}};var lp="Referral",xr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(lp,e);if(t){let r={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",r),V(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.referral.getDefinitions(i);return n.ok&&n.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(lp,n.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=Ht.parseReferralCode(e)?.toUpperCase();if(!t)return u("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},r=await this.ctx.api.referral.activateReferralCode(n);if(r.ok){let o=r.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID,o.QualificationPending),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return r}async claimInviteReward(e){let t=e.trim();if(!t)return u("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},r=await this.ctx.api.referral.claimInviteReward(n);if(r.ok){let o=r.data;o.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(o.RewardID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",o);}return r}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return u("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},r=await this.ctx.api.referral.claimInviteRewardsBatch(n);if(r.ok){let o=r.data;for(let c of o.Items??[])c.Success&&c.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(c.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return r}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.checkQualification(e);return t.ok&&t.data.Qualification&&!t.data.QualificationPending&&await this.getUserState(),t}async checkQualificationIfPending(){this.ctx.data.user.state?.Referral?.QualificationPending===true&&await this.checkQualification();}};var qC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},up=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),LC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},BC=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),GC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},_C=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),nt={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},FC={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"},VC=100,NC=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),cp=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(),jC=zod.z.object({Texts:zod.z.record(zod.z.string(),NC).nullish(),Category:up.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:cp.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),WC=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:pe.nullish(),Cost:pe.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:p.nullish(),SenderGate:Z.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),KC=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(),QC=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(KC).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:p.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:pe.nullish(),SenderGate:Z.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),pp=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(),jC).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),WC).nullish(),Transfer:QC.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(),HC=zod.z.object({MessageID:zod.z.string(),Source:BC,Category:up,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:cp.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:H.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:p,ExpiresAt:p.nullish(),ReadAt:p.nullish(),ClaimedAt:p.nullish()}).passthrough(),$C=zod.z.object({MessageID:zod.z.string(),Module:_C,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:H.nullish()}).passthrough(),sa=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),dp=zod.z.object({ServerTimeUtc:p.nullish(),Messages:zod.z.array(HC).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array($C).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),br=zod.z.object({ServerTimeUtc:p.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),oa=zod.z.object({ServerTimeUtc:p.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(sa).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),JC=zod.z.object({MessageID:zod.z.string(),Rewards:pe.nullish()}).passthrough(),Dr=zod.z.object({ServerTimeUtc:p.nullish(),Claimed:zod.z.array(JC).default([]),Failed:zod.z.array(sa).default([]),Resources:M.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),hp=zod.z.object({ServerTimeUtc:p.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(sa).default([]),Resources:M.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish()}).passthrough(),mp=zod.z.object({ServerTimeUtc:p.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish(),RecipientReceives:pe.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),fp=zod.z.object({ServerTimeUtc:p.nullish(),ResetsAt:p.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:p.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish()}).passthrough().nullish()}).passthrough();var aa="Mailbox",la={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},Pr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(la,{schema:br,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(la,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(aa)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(aa,e);if(t)return V(t);let i=this.request();if(!i)return a;let n=await this.ctx.api.mailbox.getDefinitions(i);return n.ok&&this.ctx.data.config.patchSection(aa,n.data),n}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return a;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(la,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return a;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return a;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return u("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):a}async claimRewards(e){let t=(e??[]).map(n=>n?.trim()).filter(Boolean);if(t.length===0)return u("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):a}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):a}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return a;let n=await this.ctx.api.mailbox.deleteMessages(i);return n.ok&&this.emitCounters(n.data),n}async sendGift(e,t){if(!e?.trim())return u("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return u("client","Recipients are required.");let n=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!n)return a;let r=await this.ctx.api.mailbox.sendGift(n);return r.ok&&(r.data.Resources&&this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",r.data)),r}async sendTransfer(e,t,i){if(!e?.trim())return u("client","RecipientUserID is required.");if(!i?.requestID?.trim())return u("client","requestID is required.");let n=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!n)return a;let r=await this.ctx.api.mailbox.sendTransfer(n);return r.ok&&(r.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(r.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",r.data)),r}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):a}};var Ir={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},ua="idos-app",gp=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()}),yp=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:M.nullish()});var ca={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},ZC=5*6e4;function vr(){return Zt()}async function pa(s){let e=await At(ca.request,ca.response,{titleID:s.titleID,userID:s.userID,requestID:s.requestID,placementID:s.placementID,adUnitID:s.adUnitID??null},{answerTimeoutMs:ZC});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var YC=new Set(["CANCELLED","DECLINED","CLOSED"]),XC=45e3,eS=s=>new Promise(e=>setTimeout(e,s)),Tr=class{constructor(e){this.ctx=e;}ctx;get available(){return vr()}async showRewarded(e){if(!vr())return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let i=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!i.ok)return {status:"unavailable",reason:i.error};let n=i.data;if(!n.Allowed)return {status:"denied",reason:n.DenyReason??void 0,retryAfterSeconds:n.RetryAfterSeconds??void 0};if(n.ProviderID!==ua||!n.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let r=await pa({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:n.RequestID,placementID:e,adUnitID:n.AdUnitID});return r.ok?{...await this.awaitReward(n.RequestID,r.via),requestID:n.RequestID}:{status:YC.has(r.error??"")?"cancelled":"unavailable",reason:r.error}}async awaitReward(e,t){let i=Date.now()+XC;for(;;){let n=this.ctx.authedRequest();if(!n)return {status:"pending",via:t};let r=await this.ctx.api.advertising.completeView({...n,RequestID:e});if(r.ok&&r.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:r.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((r.ok?r.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>i)return {status:"pending",via:t,reason:r.ok?void 0:r.error};await eS(o);}}};var tS={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},iS={Title:"Title",Platform:"Platform"},Rp=zod.z.object({UserID:zod.z.string(),PublicData:qe.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),Li=zod.z.object({Friends:zod.z.array(Rp).nullish()}),nS=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),Bi=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:Rp.nullish(),Counters:nS.nullish()}),rS={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},sS={Like:"Like",Favorite:"Favorite"},oS={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},aS={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},lS={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},uS=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),cS=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(uS).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),OccurredAt:p.nullish(),OwnerImpact:M.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),Cp=zod.z.object({Items:zod.z.array(cS).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:p.nullish()}).passthrough(),Gi=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:p.nullish()}).passthrough(),pS=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(),Vt=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:pS.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),Sp=zod.z.object({Items:zod.z.array(Vt).nullish()}).passthrough(),da={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},dS=zod.z.object({UserID:zod.z.string(),PublicData:qe.nullish(),Mutual:zod.z.boolean().nullish(),Since:p.nullish()}).passthrough(),Ar=zod.z.object({Items:zod.z.array(dS).nullish(),...da}).passthrough(),hS=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:p.nullish()}).passthrough(),xp=zod.z.object({Items:zod.z.array(hS).nullish(),...da}).passthrough(),wr=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:qe.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:p.nullish(),EditedAt:p.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),bp=zod.z.object({Items:zod.z.array(wr).nullish(),...da,TotalCount:zod.z.number().nullish()}).passthrough(),Dp=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),Pp=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),Ip=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(),mS="FRIENDS_FROM_PLATFORM",fS={Off:"Off",Default:"Default",Always:"Always"},gS={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},vp=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:zod.z.boolean().nullish()}).passthrough(),xe={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report"};var ha={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},kr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ha,{schema:Gi,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return a;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return u("client","TargetUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return u("client","FriendUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return a;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(ha,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(ha,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):a}async getEntityStates(e,t){if(!t?.length)return u("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):a}async addComment(e,t,i,n){let r=this.targetRequest(e,t);if("ok"in r)return r;if(!i?.trim())return u("client","Text is required.");r.Text=i,r.ParentCommentID=n;let o=await this.ctx.api.social.addComment(r);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return u("client","CommentID is required.");if(!t?.trim())return u("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return a;i.CommentID=e,i.Text=t;let n=await this.ctx.api.social.editComment(i);return n.ok&&this.ctx.emitter.emit("social:commentEdited",n.data),n}async deleteComment(e){if(!e)return u("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let n=this.targetRequest(e,t);return "ok"in n?n:(n.ParentCommentID=i.parentCommentID,this.applyPage(n,i.cursor,i.limit),this.ctx.api.social.getComments(n))}async report(e,t,i,n){let r=this.targetRequest(e,t);if("ok"in r)return r;if(!i)return u("client","ReportReason is required.");r.ReportReason=i,r.ReportComment=n;let o=await this.ctx.api.social.report(r);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,n){let r=this.targetRequest(t,i);if("ok"in r)return r;r.ReactionKind=n;let o=await this.ctx.api.social[e](r);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let n=this.ctx.authedRequest();return n?(this.applyPage(n,t,i),this.ctx.api.social[e](n)):a}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return u("client","EntityType is required.");if(!t)return u("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):a}};var Tp="TimedBoost";function yS(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var zr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Tp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),V(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.timedBoost.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Tp,n.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",n.data)),n}async getActive(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let i=e.trim();if(!yS(i))return u("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${i}_${B()}`},r=await this.ctx.api.timedBoost.activate(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;if(o.ActivatedBoost){let c=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,c);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return r}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var Ot={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},RS={Client:"Client",Server:"Server",System:"System"},CS=zod.z.enum(["Client","Server","System"]).catch("Client"),SS=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:p.nullish(),Version:zod.z.number().nullish(),LastWriter:CS.nullish(),ExpiresAt:p.nullish()}).passthrough(),Mr=zod.z.record(zod.z.string(),SS),Ap=zod.z.object({Version:zod.z.number().nullish(),Private:Mr.nullish(),Public:Mr.nullish(),ReadOnly:Mr.nullish()}),ma=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Mr.nullish()}),fa=zod.z.object({ServerTimeUtc:p.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:p.nullish()}),xS=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:p.nullish()}),wp=zod.z.object({ServerTimeUtc:p.nullish(),Results:zod.z.array(xS).nullish()}),kp=zod.z.object({ServerTimeUtc:p.nullish(),DeletedCount:zod.z.number().nullish()}),zp=zod.z.object({Results:zod.z.array(ma).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),bS={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},DS=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),PS=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:DS.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Or=zod.z.object({Keys:zod.z.record(zod.z.string(),PS).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(),gt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var IS="UserCustomData";function Mp(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var Er=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(IS,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TargetUserID=t;let n=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return n.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",n.data),n}async setPrivateData(e,t){return this.setData(e,t,Ot.Private)}async setPublicData(e,t){return this.setData(e,t,Ot.Public)}async setData(e,t,i){let n=e.trim();if(!Mp(n))return u("client",'KeyID is required and must not contain "." or "$".');if(t==null)return u("client","Value is required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Value:t},c=await(i===Ot.Private?this.ctx.api.userCustomData.setPrivateData(r):this.ctx.api.userCustomData.setPublicData(r));if(c.ok){let h=c.data;this.ctx.data.user.patchUserCustomDataKey(i,h.KeyID,t,h.Version??0,h.ExpiresAt),this.ctx.emitter.emit(i===Ot.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",h);}return c}async deleteKey(e,t){let i=e.trim();if(!Mp(i))return u("client",'KeyID is required and must not contain "." or "$".');if(t!==Ot.Private&&t!==Ot.Public)return u("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},r=await this.ctx.api.userCustomData.deleteKey(n);return r.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),r}async batchSet(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let n of i.data.Results??[]){let r=n.Bucket??Ot.Private,o=e.find(c=>c.Bucket===r&&c.KeyID===n.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(r,n.KeyID,o.Value,n.Version??0,n.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let n of e)this.ctx.data.user.removeUserCustomDataKey(n.Bucket,n.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return u("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var vS="TitleCustomDataDefinitions",Op=50;function TS(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}function ga(s){if(s.ExpiresAt==null)return false;let e=Date.parse(s.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function AS(s){let e={};for(let[t,i]of Object.entries(s))ga(i)||(e[t]=i);return e}var Ur=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(vS,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return a;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(r=>r.trim()).filter(r=>r.length>0);if(!t.length)return u("client","At least one KeyID is required.");if(t.some(r=>!TS(r)))return u("client",'KeyID must not contain "." or "$".');if(t.length>Op)return u("client",`At most ${Op} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return a;i.KeyIDs=t;let n=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return n.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",n.data),n}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!ga(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!ga(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=AS(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 qr=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var wS=15,kS="GameLoop",Ep="BoardDefinition",Lr=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(kS,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(Ep,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),V(i);let n=this.ctx.authedRequest();if(!n)return a;let r=await this.ctx.api.gameLoop.getBoardDefinition(n,e);return r.ok&&(this.ctx.data.config.patchSection(Ep,r.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",r.data)),r}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return u("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return a;i.StageLevel=e;let n=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return n.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",n.data),n}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return u("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${B()}`},n=await this.ctx.api.gameLoop.boardLoopRoll(i);if(n.ok){let r=n.data,o=uu(new Date,wS);this.ctx.data.user.patchBoardState(c=>{c.Position=r.NewPosition,c.CyclesCompleted=(c.CyclesCompleted??0)+(r.CyclesCompletedDelta??0),c.LastRollAtUtc=new Date().toISOString(),r.ActionRequired&&r.ActionData?c.Pending={Type:r.ActionRequired,TargetUserID:r.ActionData.TargetUserID,TargetPublicData:r.ActionData.PublicData,TargetBuildingStates:r.ActionData.TargetBuildingStates??void 0,TargetHasShield:r.ActionData.TargetHasShield??void 0,RollMultiplier:r.UsedMultiplier??1,ExpiresAtUtc:o}:r.SpecialModeOffer&&(c.Pending={Type:"SPECIAL",RollMultiplier:r.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:r.SpecialModeOffer.ModeID??void 0,Choices:r.SpecialModeOffer.Choices??void 0}});}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),r.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",r);}return n}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${B()}`},n=await this.ctx.api.gameLoop.boardLoopAttack(i);if(n.ok){let r=n.data;this.ctx.data.user.clearBoardPending(),r.IsBotTarget&&r.Operation?this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs):!r.IsBotTarget&&r.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(r.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",r);}else await this.getUserBoardState();return n}async boardLoopRaid(e,t){if(e<0||e>11)return u("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${B()}`},r=await this.ctx.api.gameLoop.boardLoopRaid(n);if(r.ok){let o=r.data;o.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(o.RaidLayout,o.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(o)),this.ctx.emitter.emit("gameLoop:boardRaided",o);}else await this.getUserBoardState();return r}async boardLoopRaidFast(e){if(!e.length)return u("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${B()}`},n=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(n.ok){let r=n.data;r.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(r)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",r);}else await this.getUserBoardState();return n}async boardLoopBuild(e){if(e<0)return u("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${B()}`},n=await this.ctx.api.gameLoop.boardLoopBuild(i);if(n.ok){let r=n.data;r.StageComplete?this.ctx.data.user.patchBoardState(o=>{o.StageLevel=(o.StageLevel??1)+1,o.Position=0,o.Pending=null,o.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(r.BuiltIndex,o=>{r.NewLevel!=null&&(o.Level=r.NewLevel),o.IsDamaged=false,r.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",r);}return n}async boardSpecialChoose(e,t,i){if(!e)return u("client","choiceID must not be empty.");let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:i,RelatedEntityID:`special_choose_${n.userID}_${B()}`},o=await this.ctx.api.gameLoop.boardSpecialChoose(r);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;c.Mode==="Instant"||c.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(y=>{y.ChoiceID=e,y.ChosenMode=c.Mode??"Timed",y.StartedAtUtc=c.StartedAtUtc??null,y.DurationSeconds=c.DurationSeconds??null,y.AdViewsUsed=0;}),c.Operation&&this.ctx.data.user.applyResourcesWithDelta(c.Operation,c.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",c);}return o}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${B()}`},n=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(n.ok){let r=n.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=r.AdViewsUsed??0,o.AccumulatedMultiplier=r.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",r);}return n}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${B()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},n=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(n.ok){let r=n.data;this.ctx.data.user.clearBoardPending(),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",r);}return n}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return u("client","milestoneID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},n=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",n.data)),n}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var Br=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,n){let r=e.trim();if(!r)return u("client","FunctionName is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:r,FunctionParameter:t,RevisionSelection:i,SpecificRevision:n},c=await this.ctx.api.cloudCode.execute(o);return c.ok&&this.ctx.emitter.emit("cloudCode:executed",c.data),c}};var Up=zod.z.object({ServerTimeUtc:p,SourceType:di,SourceID:zod.z.string(),TargetType:di,TargetID:zod.z.string(),SourceSpent:j,FeeAmount:j,RateApplied:Y,TargetCredited:j}),qp=zod.z.object({ServerTimeUtc:p,SourceType:di,SourceID:zod.z.string(),TargetType:di,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),Lp=zod.z.object({ServerTimeUtc:p,SpendID:zod.z.string(),Resources:M.nullish()}),_i={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},zS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},Bp=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),MS={Automatic:"Automatic",Manual:"Manual"},OS=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),ES=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),US=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),qS=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),LS=zod.z.object({TargetCurrencyType:di.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),Gp=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:OS.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(LS).nullish()}).passthrough(),_p=zod.z.object({CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough(),BS=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:ES.nullish(),Recharge:US.nullish(),Conversion:Gp.nullish(),Permissions:qS.nullish(),Audit:_p.nullish(),Status:Bp.nullish()}).passthrough(),GS=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),_S=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),FS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),VS=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:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:zod.z.array(GS).nullish(),Limits:_S.nullish(),Permissions:FS.nullish(),Conversion:Gp.nullish(),Audit:_p.nullish(),Status:Bp.nullish(),ServerGrantPolicy:VS.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),NS=zod.z.object({SpendID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),PriceOptions:zod.z.record(zod.z.string(),vn).nullish()}).passthrough(),Gr=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),BS).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),ya).nullish(),Spends:zod.z.record(zod.z.string(),NS).nullish()}).passthrough();var jS={EVM:"EVM",Solana:"Solana"},WS=zod.z.enum(["EVM","Solana"]).catch("EVM"),KS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},QS=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),HS={Token:"Token",Nft:"Nft"},Fp=zod.z.enum(["Token","Nft"]).catch("Token"),$S={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},JS=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),ZS={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},YS=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),XS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Ra=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),Vp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function _r(s){let e=s?.trim();return e||Vp.GameTopUp}var ex={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},Np=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),tx=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(),jp=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),ix=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:WS.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:jp.nullish(),NftCollections:zod.z.array(tx).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(),nx=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:jp.nullish()}).passthrough(),rx=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),sx={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},ox=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Wp=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:ox.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),ax=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),lx={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Fi=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),ux=zod.z.object({Mode:Fi.nullish(),TokenGates:zod.z.array(Wp).nullish()}).passthrough(),Ca=zod.z.object({SystemState:nx.nullish(),Networks:zod.z.record(zod.z.string(),ix).nullish(),AccountSafety:rx.nullish(),WalletLogin:ax.nullish(),PlayAccess:ux.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),cx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:p.nullish(),LastUsedAt:p.nullish(),LinkType:QS.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),Kp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:Fp.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),px=zod.z.object({Status:JS.nullish(),Tier:YS.nullish(),VerifiedAt:p.nullish(),ExpiresAt:p.nullish(),RejectedAt:p.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),dx=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),hx=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:zod.z.record(zod.z.string(),dx).nullish()}).passthrough(),mx=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),fx=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(),mx).nullish()}).passthrough(),gx=zod.z.object({Tokens:hx.nullish(),Nfts:fx.nullish()}).passthrough(),Sa=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Nt=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:p.nullish(),Balances:zod.z.array(Sa).nullish()}).passthrough(),yx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:p.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:p.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(Sa).nullish()}).passthrough(),Rx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),Qp=zod.z.object({Mode:Fi.nullish(),TokenGates:zod.z.array(Wp).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(Rx).nullish(),Status:Nt.nullish()}).passthrough(),Cx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:p.nullish(),LoggedInAt:p.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(Sa).nullish()}).passthrough(),Sx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:p.nullish()}).passthrough(),xx=zod.z.object({Version:zod.z.number().nullish(),Stats:gx.nullish(),LinkedWallets:zod.z.record(zod.z.string(),cx).nullish(),LastWalletLogin:Cx.nullish(),PlayAccess:yx.nullish(),PendingWithdrawals:zod.z.array(Kp).nullish(),Kyc:px.nullish(),FirstActivityAt:p.nullish(),LastActivityAt:p.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(Sx).nullish()}).passthrough(),bx=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:p}).passthrough(),bi=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),bx).nullish(),PendingAdded:Kp.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Dx=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough().transform(s=>s),Px=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Np.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Ra.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:p.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:p.nullish(),RefundCheckedAt:p.nullish()}).passthrough(),Ix=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Np.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Ra.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:p.nullish()}).passthrough(),Hp=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),xa=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(Hp).nullish(),Signature:zod.z.string().nullish()}).passthrough(),ba=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(Hp).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(),$p=zod.z.object({Blockchain:Ca.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),ya).nullish()}).passthrough(),Jp=zod.z.object({State:xx.nullish(),CryptoBalances:zod.z.record(zod.z.string(),Dx).nullish()}).passthrough(),Zp=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:bi.nullish()}).passthrough(),Yp=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}).passthrough(),Xp=zod.z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:p.nullish(),EvmSignature:xa.nullish(),SolanaSignature:ba.nullish(),StateDelta:bi.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),ed=zod.z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish(),EvmSignature:xa.nullish(),SolanaSignature:ba.nullish(),StateDelta:bi.nullish(),Inventory:K.nullish()}).passthrough(),td=zod.z.object({TokenTransactions:zod.z.array(Px).nullish(),NFTTransactions:zod.z.array(Ix).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Da=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:zod.z.string().nullish()}).passthrough(),id=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:Fp.nullish(),EvmSignature:xa.nullish(),SolanaSignature:ba.nullish()}).passthrough(),nd=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:Ra.nullish(),StateDelta:bi.nullish()}).passthrough(),Je={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 vx="Blockchain",rd="Blockchain:Definitions",Fr=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(rd,e);if(t)return V(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return a;let n=this.ctx.api.blockchain.getDefinitions(i).then(r=>(r.ok&&(this.ctx.data.config.patchSection(vx,r.data.Blockchain),this.ctx.data.config.patchSection(rd,r.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",r.data)),r)).finally(()=>{this.definitionsInflight===n&&(this.definitionsInflight=null);});return this.definitionsInflight=n,n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositToken(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",n.data)),n}async depositNFT(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositNFT(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",n.data)),n}async requestTokenWithdrawal(e,t,i,n,r){if(!e)return u("client","CurrencyID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!n)return u("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return a;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=n,o.Category=_r(r);let c=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return c.ok&&(this.ctx.data.user.applyBlockchainStateDelta(c.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",c.data)),c}async requestNFTWithdrawal(e,t,i,n,r,o,c){if(!e)return u("client","ItemID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!n)return u("client","Amount is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.NetworkID=t,h.WalletAddress=i,h.Amount=n,h.Category=_r(r),o!==void 0&&(h.Level=o),c&&(h.ItemInstanceID=c);let y=await this.ctx.api.blockchain.requestNFTWithdrawal(h);return y.ok&&(this.ctx.data.user.applyBlockchainStateDelta(y.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(y.data.Resources,y.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",y.data)),y}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return a;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return u("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return u("client","TitleTransactionID is required.");if(!t)return u("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TitleTransactionID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.confirmWithdrawal(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",n.data)),n}async donateToDeveloper(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToDeveloper(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",n.data),n}async donateToUsersPool(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToUsersPool(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",n.data),n}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var Tx={Head:"Head",Torso:"Torso",Legs:"Legs"},Vr=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),Ax={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},Pa=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),od=zod.z.object({AttackTarget:Vr,DefenseTarget:Vr});var wx=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),kx=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:Vr.nullish(),DefenseZone:Vr.nullish(),HitType:wx.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),zx=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(),Mx=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),sd=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:Qo.nullish(),BattleStrategy:zod.z.array(od).nullish(),UnstackableItems:zod.z.record(zod.z.string(),Mx).nullish(),Stats:zx.nullish()}).passthrough(),Ox=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:pe.nullish(),NetReward:pe.nullish(),BattleLog:zod.z.array(kx).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:sd.nullish(),P2BattleProfile:sd.nullish()}).passthrough(),ad=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:p.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(od).nullish(),TargetUserID:zod.z.string().nullish(),Entry:pe.nullish(),CreationCostPaid:pe.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:p.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:p.nullish(),Status:Pa.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:p.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:p.nullish()}).passthrough(),ld=zod.z.object({Status:Pa,MatchID:zod.z.string(),Entry:pe.nullish(),Resources:M.nullish()}),ud=zod.z.object({Match:ad.nullish()}),cd=zod.z.object({MatchID:zod.z.string(),Status:Pa,Resources:M.nullish()}),pd=zod.z.object({Battle:Ox.nullish(),Resources:M.nullish(),ResourcesDual:vt.nullish()}),Ia=zod.z.object({Matches:zod.z.array(ad).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),xt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var Ex=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var Ux=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),qx=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(),Lx=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),Bx=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:Lx.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),Gx=zod.z.object({Kind:Ux.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Ne.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),_x=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(Gx).nullish()}).passthrough(),Xt=zod.z.object({Terms:zod.z.array(_x).nullish()}).passthrough(),Fx=zod.z.object({Health:Xt.nullish(),Damage:Xt.nullish(),Armor:Xt.nullish(),AttackSpeed:Xt.nullish(),CritChance:Xt.nullish(),CritDamage:Xt.nullish(),Dodge:Xt.nullish()}).passthrough(),dd=zod.z.object({StatMapping:qx.nullish(),Combat:Bx.nullish(),Formula:Fx.nullish()}).passthrough(),Vx=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),Vi=zod.z.object({Kind:Ex.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:Yi.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),hd=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(Vi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),md=zod.z.object({PriceOptions:ce.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:Se.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),Nx=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:Vx.nullish(),Entry:hd.nullish(),Creation:md.nullish(),Settings:dd.nullish()}).passthrough(),jx=zod.z.object({Rules:zod.z.record(zod.z.string(),Nx).nullish(),Defaults:dd.nullish(),EntryDefaults:hd.nullish(),CreationDefaults:md.nullish()}).passthrough(),va=zod.z.object({InstantBattle:jx.nullish()}).passthrough(),fd=va;var Wx={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Ta=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),Kx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Aa=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),Qx={Burn:"Burn",Ledger:"Ledger"},Hx=zod.z.enum(["Burn","Ledger"]).catch("Burn"),jr={Item:"Item",VirtualCurrency:"VirtualCurrency"},wa=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),$x=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish()}).passthrough(),Wr=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(Vi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),ka=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish(),Sink:Hx.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),$x).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),Jx=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(),Zx=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:Se.nullish(),BuyLimits:Se.nullish(),ListingFeeOptions:ce.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),Yx=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:j.nullish(),BidLimits:Se.nullish()}).passthrough(),Xx=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:Se.nullish(),FillLimits:Se.nullish()}).passthrough(),eb=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:Se.nullish()}).passthrough(),tb=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),za=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:Re.nullish(),PricePolicy:Wr.nullish(),Commission:ka.nullish(),Tradability:Jx.nullish(),Listings:Zx.nullish(),Auctions:Yx.nullish(),BuyOrders:Xx.nullish(),DirectTrades:eb.nullish(),Matching:tb.nullish()}).passthrough(),gd=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:j.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:p.nullish()}).passthrough(),ib=zod.z.object({BidAxisType:hi.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:j.nullish(),CurrentBid:j.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(gd).nullish()}).passthrough(),Nr=zod.z.object({LastAt:p.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),nb=zod.z.object({Create:Nr.nullish(),Buy:Nr.nullish(),Sell:Nr.nullish(),Bid:Nr.nullish()}).passthrough(),rb=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),sb=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:rb.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),Et=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Ta.nullish(),Status:Aa.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:qe.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:wa.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),GoodsInstances:zod.z.array(sb).nullish(),Price:pe.nullish(),Auction:ib.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),ob=zod.z.object({GoodsType:wa.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(Ta,j).nullish()}).passthrough(),yd=zod.z.object({Definitions:za.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),Ma=zod.z.object({Offers:zod.z.array(Et).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Rd=zod.z.object({Groups:zod.z.array(ob).nullish()}).passthrough(),Cd=zod.z.object({Offer:Et.nullish()}).passthrough(),ct=zod.z.object({OfferID:zod.z.string().nullish(),Status:Aa.nullish(),Settlement:vt.nullish(),Resources:M.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Ni=zod.z.object({OfferID:zod.z.string().nullish(),Offer:Et.nullish(),Resources:M.nullish(),Matched:zod.z.boolean().nullish(),Settlement:ct.nullish()}).passthrough(),Sd=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:j.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish()}).passthrough(),Kr=zod.z.object({MyOffers:zod.z.array(Et).nullish(),MyBids:zod.z.array(Et).nullish(),MyBuyOrders:zod.z.array(Et).nullish(),IncomingTrades:zod.z.array(Et).nullish(),OutgoingTrades:zod.z.array(Et).nullish(),Claimables:zod.z.array(Et).nullish(),DrainedRefunds:zod.z.array(gd).nullish(),Limits:nb.nullish()}).passthrough(),ab=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Ta.nullish(),FinalStatus:Aa.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:wa.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),PricePaid:pe.nullish(),CommissionTaken:pe.nullish(),CompletedAt:p.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),xd=zod.z.object({Entries:zod.z.array(ab).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Oe={GetDefinitions:"GetDefinitions",GetGroupedOffers:"GetGroupedOffers",GetOffersByItem:"GetOffersByItem",GetOffer:"GetOffer",GetBuyOrders:"GetBuyOrders",GetMyState:"GetMyState",GetHistory:"GetHistory",CreateListing:"CreateListing",CancelListing:"CancelListing",Buy:"Buy",MarketBuy:"MarketBuy",MarketSell:"MarketSell",CreateAuction:"CreateAuction",PlaceBid:"PlaceBid",ClaimAuction:"ClaimAuction",CreateBuyOrder:"CreateBuyOrder",CancelBuyOrder:"CancelBuyOrder",FillBuyOrder:"FillBuyOrder",CreateDirectTrade:"CreateDirectTrade",RespondDirectTrade:"RespondDirectTrade",CancelDirectTrade:"CancelDirectTrade",ClaimBack:"ClaimBack"};var lb="Marketplace",bd={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"]},Qr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(bd,{schema:Kr,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(lb,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,n=20){if(!e)return u("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return a;r.ItemID=e,r.OfferTypeFilter=t,r.ContinuationToken=i,r.PageSize=n;let o=await this.ctx.api.marketplace.getOffersByItem(r);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let n=this.ctx.authedRequest();if(!n)return a;n.ItemID=e,n.ContinuationToken=t,n.PageSize=i;let r=await this.ctx.api.marketplace.getBuyOrders(n);return r.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",r.data),r}getMyState(e,t){return this.ctx.cache.read(bd,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let n=this.ctx.authedRequest();if(!n)return a;i&&(n.HistoryFilter=i),n.ContinuationToken=e,n.PageSize=t;let r=await this.ctx.api.marketplace.getHistory(n);return r.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",r.data),r}async createListing(e,t,i,n,r,o,c){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!n)return u("client","PriceBundle is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.PriceBundle=n,h.DurationHours=r,h.ItemInstanceIDs=o,h.SelectedOptionID=c;let y=await this.ctx.api.marketplace.createListing(h);return this.applyCreateOfferResult(y,"marketplace:listingCreated"),y}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let n=this.ctx.authedRequest();if(!n)return a;let r=this.applyGoodsSelector(n,i);if(r)return r;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let n=this.ctx.authedRequest();if(!n)return a;let r=this.applyGoodsSelector(n,i);if(r)return r;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,n,r,o,c={}){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.BidAxisType=n,h.BidCurrencyID=c.bidCurrencyID,h.BidCatalogID=c.bidCatalogID,h.BidItemID=c.bidItemID,h.StartingBid=r,h.DurationHours=o,h.ItemInstanceIDs=c.itemInstanceIDs,h.SelectedOptionID=c.selectedOptionID;let y=await this.ctx.api.marketplace.createAuction(h);return this.applyCreateOfferResult(y,"marketplace:auctionCreated"),y}async placeBid(e,t){if(!e)return u("client","OfferID is required.");if(!t||t<=0)return u("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.BidAmount=t;let n=await this.ctx.api.marketplace.placeBid(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",n.data)),n}async claimAuction(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,n,r){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!n)return u("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return a;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=n,o.DurationHours=r;let c=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(c,"marketplace:buyOrderCreated"),c}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,n,r){if(!e)return u("client","TargetUserID is required.");if(!t)return u("client","CatalogID is required.");if(!i)return u("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return a;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=n,o.RequestedBundle=r;let c=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(c,"marketplace:directTradeCreated"),c}async respondDirectTrade(e,t){if(!e)return u("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.Accept=t;let n=await this.ctx.api.marketplace.respondDirectTrade(i);return n.ok&&(t&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",n.data)),n}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return u("client","OfferID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.OfferID=e;let r=await t(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,r.data)),r}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=jr.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=jr.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):u("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var Hr=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return u("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let n=await this.ctx.api.multiplayer.createRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",n.data),n}async joinRoom(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.JoinCode=t;let n=await this.ctx.api.multiplayer.joinRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",n.data),n}async leaveRoom(e,t={}){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let n=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",n.data),n}async claimHost(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.TargetUserID=t,n.Ban=i;let r=await this.ctx.api.multiplayer.kickMember(n);return r.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",r.data),r}async unbanMember(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.TargetUserID=t;let n=await this.ctx.api.multiplayer.unbanMember(i);return n.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",n.data),n}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return a;i.Page=e,i.PageSize=t;let n=await this.ctx.api.multiplayer.listRooms(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",n.data),n}async getRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.LastSeq=t;let n=await this.ctx.api.multiplayer.poll(i);return n.ok&&this.ctx.emitter.emit("multiplayer:polled",n.data),n}async sendSignal(e,t,i,n){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");if(!i)return u("client","SignalKind is required.");let r=this.ctx.authedRequest();if(!r)return a;r.RoomID=e,r.TargetUserID=t,r.SignalKind=i,r.Payload=n;let o=await this.ctx.api.multiplayer.sendSignal(r);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.ChatText=t;let n=await this.ctx.api.multiplayer.sendChat(i);return n.ok&&this.ctx.emitter.emit("multiplayer:chatSent",n.data),n}async setMemberState(e,t,i){if(!e)return u("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.Ready=t,n.MemberState=i;let r=await this.ctx.api.multiplayer.setMemberState(n);return r.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",r.data),r}};var Dd=" (if the network is fine, the storage bucket has no CORS rule for this origin)",$r=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.ParentContentID=e.parentContentID,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):a}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return u("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):a}async getCreatorProfile(e,t,i){if(!e)return u("client","CreatorUserID is required.");let n=this.ctx.authedRequest();return n?(n.CreatorUserID=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getCreatorProfile(n)):a}async publish(e){if(!e.files||e.files.length===0)return u("client","At least one file is required.");let t=new Map,i=e.files.map((h,y)=>{if("sourceAssetUrl"in h)return {Role:h.role,ContentType:h.contentType,SourceAssetUrl:h.sourceAssetUrl};let F=Pd(h.data,h.contentType);return t.set(y,F),{Role:h.role,ContentType:h.contentType,Size:F.size}}),n=e.thumbnail?Pd(e.thumbnail.data,e.thumbnail.contentType):null,r=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&n?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:n.size}:void 0});if(!r.ok)return r;let o=r.data.Uploads??[];for(let h=0;h<o.length;h++){let y=o[h];if(!y||y.ServerCopy||!y.Url)continue;let F=t.get(h);if(!F)return u("client",`No bytes for file #${h+1}.`);let oe=await this.putBytes(y.Url,F,y.ContentType??F.type);if(!oe.ok)return oe}let c=r.data.ThumbnailUpload;if(c?.Url&&n){let h=await this.putBytes(c.Url,n,c.ContentType??n.type);if(!h.ok)return h}return this.ctx.credits.pay(h=>this.publishUploaded({CreditsConfirmationID:h,ContentID:r.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID}),e.credits)}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):a}async publishUploaded(e){if(!e.ContentID)return u("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return a;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&!i.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let n=await this.ctx.api.workshop.updateContent(i);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let n=this.ctx.authedRequest();return n?(n.ContentType=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getMyContent(n)):a}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let n=await this.ctx.api.workshop.acquire(i);return n.ok&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",n.data)),n}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let n of t.data.Files??[])if(n.Url)try{let r=await this.ctx.fetchImpl(n.Url);if(!r.ok)return u("connection",`Download failed (HTTP ${r.status}).`);i.push({role:n.Role??"main",contentType:n.ContentType??"application/octet-stream",data:await r.arrayBuffer()});}catch(r){return u("connection",`Download failed: ${r instanceof Error?r.message:String(r)}${Dd}`)}return V({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):a}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):a}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?V(!0):u("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return u("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}${Dd}`)}}contentRequest(e){if(!e)return u("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):a}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function Pd(s,e){return s instanceof Blob?s:typeof s=="string"?new Blob([new TextEncoder().encode(s)],{type:e}):s instanceof Uint8Array?new Blob([s.slice().buffer],{type:e}):new Blob([s],{type:e})}var ub={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},cb=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),pb={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Id=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),db={Everyone:"Everyone",Owner:"Owner",Server:"Server"},vd=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),hb={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},mb=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),fb={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},gb=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),yb={Count:"Count",Sum:"Sum"},Rb=zod.z.enum(["Count","Sum"]).catch("Count"),Cb={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},Sb=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),xb={Strict:"Strict",Loose:"Loose"},bb=zod.z.enum(["Strict","Loose"]).catch("Strict"),Db=zod.z.object({Kind:gb,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),Pb=zod.z.object({Type:Id,ItemType:Id.nullish(),Ref:Db.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:vd.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()}),Ib=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Jr=zod.z.object({Mode:mb,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),vb=zod.z.object({Read:zod.z.array(Jr).nullish(),Create:zod.z.array(Jr).nullish(),Update:zod.z.array(Jr).nullish(),Delete:zod.z.array(Jr).nullish()}),Oa=zod.z.object({Cost:pe.nullish(),Grant:pe.nullish()}),Tb=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()}),Ab=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:cb,Mode:bb.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),Pb).nullish(),SortKeys:zod.z.array(Ib).nullish(),Access:vb.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:Sb.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:Rb,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:vd.optional()})).nullish(),Economy:zod.z.object({OnCreate:Oa.nullish(),OnUpdate:Oa.nullish(),OnDelete:Oa.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:zod.z.array(Tb).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()}),Td=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),Ab).default({})}),wb=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),Ad=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),Di=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(),wb).nullish()}),Ea=zod.z.object({Item:Di}),wd=zod.z.object({Items:zod.z.array(Di).default([]),Missing:zod.z.array(zod.z.string()).default([])}),Ua=zod.z.object({Items:zod.z.array(Di).default([]),NextCursor:zod.z.string().nullish()}),kd=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),qa=zod.z.object({Item:Di,AlreadyExists:zod.z.boolean().optional(),Economy:M.nullish()}),zd=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:M.nullish()}),Md=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),Od=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:Di.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),Ed=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),Ud=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),qd=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({})}),Ld=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(Di).default([])}),kb={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 zb=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,_d=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Ba=100,Bd=25,Gd=100;function Mb(s,e,t){return {Field:s,Op:e,Value:t}}var Zr=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(a)}get(e,t,i={}){let n=rt(e)??ji(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.get({...r,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let n=rt(e);if(n)return Promise.resolve(n);let r=[...new Set(t.filter(o=>_d.test(o)))];return r.length?r.length>Gd?Promise.resolve(u("client",`At most ${Gd} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:r,Expand:i.expand})):Promise.resolve(u("client","At least one valid item id is required."))}query(e,t={},i={}){let n=rt(e)??La(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.query({...r,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let n=Math.max(1,i.maxItems??500),r=[],o=t.Cursor;for(;;){let c=await this.query(e,{...t,Cursor:o,Limit:t.Limit??Ba},i);if(!c.ok)return c;if(r.push(...c.data.Items),o=c.data.NextCursor??void 0,!o||r.length>=n)return V(r.slice(0,n))}}count(e,t={}){let i=rt(e)??La(t);return i?Promise.resolve(i):this.call(n=>this.ctx.api.dataCollections.count({...n,Collection:e,Query:t}))}create(e,t,i={}){let n=rt(e)??(i.itemID?ji(i.itemID):null);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.create({...r,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,n={}){let r=rt(e)??ji(t);return r?Promise.resolve(r):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:n.expectedVersion}))}set(e,t,i,n={}){return this.update(e,t,{Set:i},n)}increment(e,t,i,n=1){return this.update(e,t,{Inc:{[i]:n}})}delete(e,t,i={}){let n=rt(e)??ji(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.delete({...r,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(u("client","Operations are empty."));if(e.length>Bd)return Promise.resolve(u("client",`At most ${Bd} operations per batch.`));let t=e.map(i=>rt(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let n=rt(e);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.getCounter({...r,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,n){let r=rt(e);return r?Promise.resolve(r):t?n>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:n})):Promise.resolve(u("client","File size must be positive.")):Promise.resolve(u("client","Field is required."))}async uploadFile(e,t,i,n={}){let r=n.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,r,i.size);if(!o.ok)return o;let c=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||r);return c.ok?o:c}async getPublicViews(e){let t=rt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return V(i);let n=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return n.ok&&this.publicViews.set(e,n.data),n}async readPublicView(e,t,i={}){let n=await this.getPublicViews(e);if(!n.ok)return n;let r=n.data.Views[t];if(!r)return u("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(r,qd);if(!o.ok)return o;let c=o.data.Partitions[i.partition??""],h=Math.max(1,i.page??1);if(!c||h>c.Pages)return V({pointer:o.data,page:{Page:h,HasMore:false,Items:[]}});let y=await this.fetchJson(`${o.data.BaseUrl}${c.Segment}/page-${h}.json`,Ld);return y.ok?V({pointer:o.data,page:y.data}):y}getPublic(e,t){let i=rt(e)??ji(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=rt(e)??La(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(a)}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?V(!0):u("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return u("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return u("connection","Internet Connection Error")}if(!i.ok)return u("server",`CDN answered ${i.status}.`);let n;try{n=await i.json();}catch{return u("server","CDN answer is not JSON.")}let r=t.safeParse(n);return r.success?V(r.data):u("server","CDN answer has an unexpected shape.")}};function rt(s){return zb.test(s??"")?null:u("client",`Collection id '${s}' is invalid (letters, digits, '_', '-', ':').`)}function ji(s){return _d.test(s??"")?null:u("client",`Item id '${s}' is invalid.`)}function La(s){return s.Limit!=null&&(s.Limit<1||s.Limit>Ba)?u("client",`Limit must be 1..${Ba}.`):(s.Where?.length??0)>8?u("client","At most 8 filters per query."):null}var Ga={Open:"Open",Declared:"Declared"},Ob=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),Eb=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),Fd=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Ob).nullish(),Dimensions:zod.z.array(Eb).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),jt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},bt={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Yr=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Ub={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},qb=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),Vd=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(qb).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),_a={LogEvents:"LogEvents"};function Nd(s,e=0){let t=s??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let c=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:c==="iPad"?"tablet":"phone",deviceModel:c}}let n=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(n){let c=(n[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:n[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:c&&c!=="K"&&c!=="wv"?c:void 0}}let r=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(r)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(r[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let o=/\bWindows NT (\d+\.\d+)/.exec(t);return o?{osName:"Windows",osVersion:o[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function jd(s){let e=typeof navigator>"u"?void 0:navigator,t=Nd(e?.userAgent??"",e?.maxTouchPoints??0),i={};s.appVersion&&(i.AppVersion=s.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let n=s.locale||e?.language;return n&&(i.Language=n),i}var Lb=25,Bb=3e4,Wd=1800*1e3,Kd=500,Gb=5,_b=1e3,Fb=3600*1e3,Qd="idos_analytics_queue",Fa="idos_analytics_pending",Va="idos_analytics_opt_out",Hd="idos_analytics_first_open",$d="idos_analytics_last_activity",Jd="idos_analytics_last_context",Zd="idos_analytics_owner",Xr=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!Yr.test(e)?u("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Vb(e)?u("client",`Event name "${e}" uses a reserved prefix (${bt.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return u("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(jt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return V(null);if(this.config()?.Enabled===false)return this.clear(),V(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return V(null);this.pending={BatchID:B(),Events:this.queue.splice(0,bt.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=Gb)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Va);return}this.write(Va,"1"),this.clear();}get isEnabled(){return this.read(Va)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(Zd);e&&t&&t!==e&&this.clear(),e&&this.write(Zd,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Bb),typeof window<"u"&&(window.addEventListener("visibilitychange",this.onVisibilityChange),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,typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),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($d)??"0");this.read(Hd)||(this.write(Hd,new Date().toISOString()),this.enqueue(jt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Jd);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(jt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(jt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Jd,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Wd)&&this.enqueue(jt.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=Wd&&this.enqueue(jt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,n){if(!this.isEnabled||this.disabledByServer)return V(null);let r=this.config();if(r?.Enabled===false)return V(null);if(n&&r?.AutomaticEvents===false)return V(null);if(r?.Events?.[e]?.Blocked)return u("client",`Event "${e}" is blocked by the title.`);if(!n&&r?.EventNaming?.toLowerCase()===Ga.Declared.toLowerCase()&&!r.Events?.[e])return u("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return u("client","value must be a finite number.");let o=Nb(t);if(o.error)return u("client",o.error);this.restore();let c={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(c.Params=o.params),i!==void 0&&(c.Value=i),this.queue.push(c),this.queue.length>Kd&&this.queue.splice(0,this.queue.length-Kd),this.touch(),this.persist(),this.started&&this.queue.length>=Lb&&this.flush(),V(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},_b));}dropStale(){let e=Date.now()-(bt.maxEventAgeMs-Fb);this.queue=this.queue.filter(t=>{let i=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(i)||i>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=jd({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(Qd);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(Fa);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(Qd,this.queue),this.pending?this.writeJson(Fa,this.pending):this.remove(Fa);}touch(){this.write($d,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.platform.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.platform.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.platform.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 Vb(s){let e=s.toLowerCase();return bt.reservedPrefixes.some(t=>e.startsWith(t))}function Nb(s){if(!s)return {};let e=Object.keys(s);if(e.length===0)return {};if(e.length>bt.maxParams)return {error:`Too many parameters: ${e.length}, max ${bt.maxParams}.`};let t={};for(let i of e){if(!Yr.test(i))return {error:`Invalid parameter name "${i}".`};let n=s[i];typeof n=="string"?t[i]=n.length>bt.maxStringValueLength?n.slice(0,bt.maxStringValueLength):n:typeof n=="number"?Number.isFinite(n)&&(t[i]=n):typeof n=="boolean"&&(t[i]=n);}return {params:t}}var jb="idos_experiments",es=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let n=this.getParams(e)[t];if(n===void 0)return i;if(typeof i=="number"){let r=Number(n);return n.trim()!==""&&Number.isFinite(r)?r:i}if(typeof i=="boolean"){let r=n.trim().toLowerCase();return r==="true"||r==="1"?true:r==="false"||r==="0"?false:i}return n}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 n of e.Experiments??[])n?.ExperimentID&&t.set(n.ExperimentID,n);let i=[];for(let[n,r]of t){let o=this.views.get(n);(!o||o.VariantID!==r.VariantID||o.Status!==r.Status)&&i.push(r);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.platform.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.platform.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${jb}:${this.ctx.settings.titleID}`}};function Wt(s,e,t,i){let r=`api/v2/${s&&s.length>0?s:"0"}/Client/${e}/${t}`;return i==null?r:`${r}/${i}`}var L=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Wt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,n){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...n,ticket:t.ClientSessionTicket})}};var ts=class extends L{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(_a.LogEvents,e,Vd,{silent:true})}};var Wb=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(),Kb={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Qb=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),Hb=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:Re.nullish(),Gate:Z.nullish(),Variants:zod.z.array(Wb).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(Qb).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),Yd=zod.z.object({Experiments:zod.z.record(zod.z.string(),Hb).nullish()}).passthrough(),$b={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Jb=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(),Xd=zod.z.object({Experiments:zod.z.array(Jb).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),Na={GetExperiments:"GetExperiments"};var is=class extends L{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Na.GetExperiments,e,Xd)}};var eh=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:p.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:p,PlayAccess:Nt.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:p.nullish()}),th=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:p,RefreshToken:zod.z.string(),RefreshTokenExpiration:p.nullish(),PlayAccess:Nt.nullish()}),Zb=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),ih=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:Zb.nullish()}).passthrough(),nh=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:p.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:Nt.nullish()}).passthrough(),rh=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:p.nullish(),PlayAccess:Nt.nullish()}).passthrough(),sh=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Be=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:p.nullish()}),oh=zod.z.object({Message:zod.z.string(),ExpiresAt:p}),Le={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 ns=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Wt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,eh,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Le.RefreshSession),e,th,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Le.GetAuthOptions),e,ih,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Wt(this.ctx.settings.titleID,"Authentication",Le.LinkWallet,e.UserID??""),e,nh,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Wt(this.ctx.settings.titleID,"Authentication",Le.UnlinkWallet,e.UserID??""),e,rh,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Le.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Le.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Le.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Le.LoginWithGoogle,e)}loginWithApple(e){return this.login(Le.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Le.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(Le.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Le.RegisterWithEmail),e,sh,{ticket:null})}confirmEmailRegistration(e){return this.login(Le.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Le.ResendVerificationCode),e,Be,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Le.RequestWalletChallenge),e,oh,{ticket:null})}loginWithWallet(e){return this.login(Le.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Le.ForgotPassword),e,Be,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Le.ResetPassword),e,Be,{ticket:null})}};var Yb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},ah=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Xb=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),lh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),Xb).nullish(),MissingKeyMode:ah.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),eD=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),uh=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:eD.nullish()}).passthrough(),rs={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},tD=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),ch=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:ah.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(tD).nullish()}).passthrough(),ph=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 ja=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:uh.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(s=>s),dh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(s=>s),hh=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(s=>s),mh=zod.z.object({}).passthrough().transform(s=>s),fh=zod.z.object({}).passthrough().transform(s=>s),gh=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:p.nullish(),LastActiveAt:p.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),yh=zod.z.object({Username:zod.z.string()}),pt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var ss=class extends L{constructor(e){super(e,"User");}getClientState(e){return this.send(pt.GetClientState,e,ja)}getClientStateExcept(e){return this.send(pt.GetClientStateExcept,e,ja)}getStateVersions(e){return this.send(pt.GetStateVersions,e,dh)}getUserState(e){return this.send(pt.GetUserState,e,hh)}getInventory(e){return this.send(pt.GetInventory,e,mh)}getEventTokens(e){return this.send(pt.GetEventTokens,e,fh)}getUsageTime(e){return this.send(pt.GetUsageTime,e,gh)}addUsageTime(e){return this.send(pt.AddUsageTime,e,Be,{silent:true})}deleteUserAccount(e){return this.send(pt.DeleteUserAccount,e,Be)}changeUsername(e){return this.send(pt.ChangeUsername,e,yh)}};var os=class extends L{constructor(e){super(e,"Currency");}convert(e){return this.send(_i.Convert,e,Up)}spend(e){return this.send(_i.Spend,e,Lp)}cryptoConvert(e){return this.send(_i.CryptoConvert,e,qp)}};var iD=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),Wa=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:M.nullish(),FodderConsumed:zod.z.array(iD).nullish()}),Rh=zod.z.array(we(Wa)),as={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},nD={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},rD=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),sD={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},oD=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),aD=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),lD=zod.z.object({Networks:zod.z.record(zod.z.string(),aD).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),uD=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(),cD=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(),pD=zod.z.object({ValuationMode:rD.nullish(),WeightCurve:Ne.nullish(),Selection:oD.nullish()}).passthrough(),dD=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:Ne.nullish(),FlatBonusCurve:Ne.nullish(),PercentBonusCurve:Ne.nullish(),PowerCurve:Ne.nullish(),Fodder:pD.nullish()}).passthrough(),hD=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),mD=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:lD.nullish(),Stats:uD.nullish(),Equipment:cD.nullish(),Upgrade:dD.nullish(),Metadata:hD.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),fD=zod.z.object({Items:zod.z.record(zod.z.string(),mD).nullish()}).passthrough(),ls=zod.z.object({Catalogs:zod.z.record(zod.z.string(),fD).nullish()}).passthrough();function Ie(s){return zod.z.unknown().transform((e,t)=>{let i=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(i!=null){let r=fe.safeParse(i);return r.success?{...e,CreditsConfirmation:r.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${r.error.message}`}),zod.z.NEVER)}let n=s.safeParse(e);return n.success?n.data:(t.addIssue({code:"custom",message:n.error.message}),zod.z.NEVER)})}var us=class extends L{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(as.UpgradeLevel,e,Ie(Wa))}upgradeLevelsBatch(e){return this.send(as.UpgradeLevelsBatch,e,Rh)}};var cs=class extends L{constructor(e){super(e,"Store");}purchase(e){return this.send(kt.Purchase,e,zo)}purchaseBatch(e){return this.send(kt.PurchaseBatch,e,Su)}getDefinitions(e){return this.send(kt.GetDefinitions,e,An)}getUserState(e){return this.send(kt.GetUserState,e,xu)}getStorefront(e){return this.send(kt.GetStorefront,e,wn)}getCreditsConfirmation(e){return this.send(kt.GetCreditsConfirmation,e,fe)}getCreditsBalance(e){return this.send(kt.GetCreditsBalance,e,Cu)}};var gD={Apple:"Apple",Google:"Google"},ps=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(),ds=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),ps).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(s=>s),yD=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:ce.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Qa=zod.z.object({Definitions:zod.z.record(zod.z.string(),yD).nullish()}).passthrough(),Ch=zod.z.object({Premium:Qa.nullish()}),Sh=zod.z.object({ServerTimeUtc:p.nullish(),Premium:ds.nullish()}),hs=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),Premium:ds.nullish(),Subscription:ps.nullish(),Resources:M.nullish()}),ei={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var RD={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},CD=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),xh=zod.z.object({StartUtc:p.nullish(),EndUtc:p.nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Ha=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),SD=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),xD=zod.z.object({Rewards:Q.nullish(),Rules:Q.nullish(),Refund:Q.nullish()}).passthrough(),bD=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:CD.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:xh.nullish(),Refund:Ha.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:SD.nullish(),Presets:xD.nullish()}).passthrough(),DD=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(),PD=zod.z.object({Rewards:H.nullish()}).passthrough(),ID=zod.z.object({Rules:xh.nullish()}).passthrough(),vD=zod.z.object({Refund:Ha.nullish()}).passthrough(),TD=zod.z.object({Rewards:zod.z.record(zod.z.string(),PD).nullish(),Rules:zod.z.record(zod.z.string(),ID).nullish(),Refund:zod.z.record(zod.z.string(),vD).nullish()}).passthrough(),AD=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(),wD=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),bD).nullish(),Stores:zod.z.record(zod.z.string(),DD).nullish(),Presets:TD.nullish(),Validation:AD.nullish(),Refund:Ha.nullish()}).passthrough(),bh=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:p.nullish(),LastPurchasedAt:p.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Dh=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:p.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:p.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:p.nullish()}).passthrough(),kD=zod.z.object({Products:zod.z.record(zod.z.string(),bh).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Dh).nullish(),LastRefundCheckAt:p.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:p.nullish(),LastPurchaseAt:p.nullish()}).passthrough(),zD=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(),Ph=zod.z.object({ServerTimeUtc:p,Purchase:wD.nullish(),Availability:zod.z.array(zD).nullish()}),Ih=zod.z.object({ServerTimeUtc:p,Purchase:kD.nullish()}),MD={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},OD=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),$a=zod.z.object({ServerTimeUtc:p,Store:Zi.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:OD.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish(),ProductState:bh.nullish(),Premium:ds.nullish(),Subscription:ps.nullish(),SubscriptionMirror:Dh.nullish()}).passthrough(),vh=zod.z.object({ServerTimeUtc:p,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:p.nullish()}).passthrough(),Th=Rt($a),ti={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var ms=class extends L{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(ti.GetDefinitions,e,Ph)}getUserState(e){return this.send(ti.GetUserState,e,Ih)}validatePurchase(e){return this.send(ti.ValidatePurchase,e,$a)}validatePurchasesBatch(e){return this.send(ti.ValidatePurchasesBatch,e,Th)}createTelegramInvoice(e){return this.send(ti.CreateTelegramInvoice,e,vh)}};var ED=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Ah=zod.z.object({Reward:H.nullish(),Weight:zod.z.number().nullish(),AmountRange:ED.nullish()}).passthrough(),Pi=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(Ah).nullish()}).passthrough(),Ii=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(Ah).nullish()}).passthrough(),UD=zod.z.object({RewardSlots:zod.z.array(Pi).nullish()}).passthrough(),qD=zod.z.object({PityRules:zod.z.array(Ii).nullish()}).passthrough(),fs=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),UD).nullish(),PityPresets:zod.z.record(zod.z.string(),qD).nullish()}).passthrough();var LD=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),wh=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish(),Results:zod.z.array(M).nullish(),TriggeredPity:zod.z.array(LD).nullish()}),BD=zod.z.object({RewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),GD=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:j.nullish()}).passthrough(),_D=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ce.nullish(),RewardSlots:zod.z.array(Pi).nullish(),PityRules:zod.z.array(Ii).nullish(),Presets:BD.nullish(),RewardMultiplier:Xi.nullish(),SupplyLimits:zod.z.array(GD).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),FD=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Ja=zod.z.object({Definitions:zod.z.record(zod.z.string(),_D).nullish(),RewardPools:fs.nullish(),Settings:FD.nullish()}).passthrough(),kh=zod.z.object({LootboxDefinitions:Ja.nullish()}),gs={GetDefinitions:"GetDefinitions",Open:"Open"};var ys=class extends L{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(gs.GetDefinitions,e,kh)}open(e){return this.send(gs.Open,e,Ie(wh))}};var VD=zod.z.object({}).passthrough().transform(s=>s),ND=zod.z.object({}).passthrough().transform(s=>s),jD=zod.z.object({}).passthrough().transform(s=>s),WD=zod.z.object({}).passthrough().transform(s=>s),KD=zod.z.object({}).passthrough().transform(s=>s),QD=zod.z.object({}).passthrough().transform(s=>s),zh=zod.z.object({ServerTimeUtc:p,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:VD,Resources:M.nullish(),Inventory:K.nullish()}),Mh=zod.z.object({ServerTimeUtc:p,AccrualID:zod.z.string(),AccruedSeconds:j.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:ND,Resources:M.nullish(),Inventory:K.nullish()}),Oh=zod.z.object({ServerTimeUtc:p,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:jD,Resources:M.nullish(),Inventory:K.nullish()}),Eh=zod.z.object({ServerTimeUtc:p,ClaimID:zod.z.string(),ClaimState:WD,Resources:M.nullish(),Inventory:K.nullish()}),HD={None:"None",Ad:"Ad",Vip:"Vip"},Uh=zod.z.object({ServerTimeUtc:p,WindowID:zod.z.string(),Boost:zod.z.string().nullish(),BaseAmount:j.nullish(),Multiplier:zod.z.number().nullish(),Granted:j.nullish(),WindowState:KD,Resources:M.nullish(),Inventory:K.nullish()}),qh=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:j.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),$D=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),JD=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:H.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Wi=zod.z.object({Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Za=zod.z.object({Availability:Q.nullish()}).passthrough(),ZD=zod.z.object({Availability:zod.z.record(zod.z.string(),Wi).nullish()}).passthrough(),YD=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(JD).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:Wi.nullish(),Presets:Za.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),XD=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),eP=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(XD).nullish()}).passthrough(),tP=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Wi.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),iP=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:eP.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:tP.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),nP=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:H.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rP=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(nP).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Wi.nullish(),Presets:Za.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),sP=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(),oP=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:H.nullish(),PremiumLimitOverrides:zod.z.array(sP).nullish(),Availability:Wi.nullish(),Presets:Za.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),aP=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(),Ya=zod.z.object({TierRewards:$D.nullish(),MilestoneRewardMultiplier:Xi.nullish(),DailyCalendars:zod.z.record(zod.z.string(),YD).nullish(),IdleAccruals:zod.z.record(zod.z.string(),iP).nullish(),Comebacks:zod.z.record(zod.z.string(),rP).nullish(),Claims:zod.z.record(zod.z.string(),oP).nullish(),Windows:zod.z.record(zod.z.string(),aP).nullish(),Presets:ZD.nullish()}).passthrough(),Lh=zod.z.object({RewardDefinitions:Ya.nullish()}),Bh=zod.z.object({Rewards:QD.nullish()}),Dt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var Rs=class extends L{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Dt.GetRewardDefinitions,e,Lh)}getUserRewardsState(e){return this.send(Dt.GetUserRewardsState,e,Bh)}getMilestoneRewardMultiplier(e){return this.send(Dt.GetMilestoneRewardMultiplier,e,qh)}claimDailyReward(e){return this.send(Dt.ClaimDailyReward,e,zh)}collectIdleAccrual(e){return this.send(Dt.CollectIdleAccrual,e,Mh)}claimComebackReward(e){return this.send(Dt.ClaimComebackReward,e,Oh)}claimReward(e){return this.send(Dt.ClaimReward,e,Eh)}claimRewardWindow(e){return this.send(Dt.ClaimRewardWindow,e,Uh)}};var Cs=class extends L{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(at.GetTutorialDefinitions,e,Zl)}getUserTutorialState(e){return this.send(at.GetUserTutorialState,e,nn)}startFlow(e){return this.send(at.StartFlow,e,qt)}reportStepShown(e){return this.send(at.ReportStepShown,e,qt)}completeStep(e){return this.send(at.CompleteStep,e,qt)}completeStepsBatch(e){return this.send(at.CompleteStepsBatch,e,eu)}skipStep(e){return this.send(at.SkipStep,e,qt)}skipFlow(e){return this.send(at.SkipFlow,e,qt)}claimFlowReward(e){return this.send(at.ClaimFlowReward,e,Xl)}resetFlow(e){return this.send(at.ResetFlow,e,qt)}};var lP={Open:"Open",Application:"Application"},uP=zod.z.enum(["Open","Application"]).catch("Open"),cP={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Gh=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),pP={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Xa=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),dP={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var ii={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},hP=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(),_h=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:uP.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:Gh.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(hP).nullish()}).passthrough(),mP=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(),fP=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:Xa.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(),mP).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),gP=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:Xa.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),Fh=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(fP).nullish(),Payouts:zod.z.array(gP).nullish()}).passthrough(),Vh=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:Xa.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),yP=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),RP=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(yP).nullish()}).passthrough(),CP=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(),Nh=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:Gh.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(CP).nullish()}).passthrough(),SP=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),xP=zod.z.object({ProgramID:zod.z.string().nullish(),Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(SP).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(),jh=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:RP.nullish(),SolanaSignature:xP.nullish(),StateDelta:bi.nullish()}).passthrough();var Ss=class extends L{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(ii.GetCommunityMarketingState,e,_h)}getEarnings(e){return this.send(ii.GetEarnings,e,Fh)}claim(e){return this.send(ii.Claim,e,Vh)}checkJoinEligibility(e){return this.send(ii.CheckJoinEligibility,e,Nh)}withdrawCryptoReward(e){return this.send(ii.WithdrawCryptoReward,e,jh)}};var xs=class extends L{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send($e.GetChatDefinitions,e,Lu)}getChannels(e){return this.send($e.GetChannels,e,Fn)}poll(e){return this.send($e.Poll,e,Bu)}getHistory(e){return this.send($e.GetHistory,e,Gu)}getConversations(e){return this.send($e.GetConversations,e,Vu)}sendMessage(e){return this.send($e.SendMessage,e,_u)}openDirectChannel(e){return this.send($e.OpenDirectChannel,e,Fu)}markRead(e){return this.send($e.MarkRead,e,Si)}joinChannel(e){return this.send($e.JoinChannel,e,Si)}leaveChannel(e){return this.send($e.LeaveChannel,e,Si)}reportMessage(e){return this.send($e.ReportMessage,e,Nu)}ignoreUser(e){return this.send($e.IgnoreUser,e,Si)}unignoreUser(e){return this.send($e.UnignoreUser,e,Si)}};var bs=class extends L{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(xi.GetPushConfig,e,Ku)}subscribePush(e){return this.send(xi.SubscribePush,e,Go)}unsubscribePush(e){return this.send(xi.UnsubscribePush,e,Be)}getPushSubscriptions(e){return this.send(xi.GetPushSubscriptions,e,Qu)}};var Ds=class extends L{constructor(e){super(e,"Localization");}send(e,t,i,n){let r=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${r}:${t.Locale}`:r,...n})}getLocalizationManifest(e){return this.send(rs.GetLocalizationManifest,e,ch)}getLocalizationTable(e){return this.send(rs.GetLocalizationTable,e,ph)}};var Ps=class extends L{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(mt.GetQuestDefinitions,e,tn)}getUserQuestState(e){return this.send(mt.GetUserQuestState,e,Gl)}refreshQuestCycles(e){return this.send(mt.RefreshQuestCycles,e,Be)}claimQuestReward(e){return this.send(mt.ClaimQuestReward,e,mo)}claimQuestRewardsBatch(e){return this.send(mt.ClaimQuestRewardsBatch,e,Vl)}claimMilestoneReward(e){return this.send(mt.ClaimMilestoneReward,e,fo)}claimMilestoneRewardsBatch(e){return this.send(mt.ClaimMilestoneRewardsBatch,e,Nl)}claimGroupCompletionReward(e){return this.send(mt.ClaimGroupCompletionReward,e,_l)}addQuestProgress(e){return this.send(mt.AddQuestProgress,e,Fl)}};var Is=class extends L{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ut.GetActiveEvents,e,Hn)}getDefinitions(e){return this.send(ut.GetDefinitions,e,Qn)}getUserLteState(e){return this.send(ut.GetUserLteState,e,Zu)}grantTokens(e){return this.send(ut.GrantTokens,e,M)}spendTokens(e){return this.send(ut.SpendTokens,e,Vo)}claimMilestone(e){return this.send(ut.ClaimMilestone,e,No)}claimMilestonesBatch(e){return this.send(ut.ClaimMilestonesBatch,e,jo)}claimAllMilestones(e){return this.send(ut.ClaimAllMilestones,e,jo)}spendTokensBatch(e){return this.send(ut.SpendTokensBatch,e,Yu)}grantTokensBatch(e){return this.send(ut.GrantTokensBatch,e,Xu)}};var vs=class extends L{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(je.GetDefinitions,e,tr)}getLeaderboard(e){return this.send(je.GetLeaderboard,e,Ui)}getMyProgress(e){return this.send(je.GetMyProgress,e,Jn)}submitScore(e){return this.send(je.SubmitScore,e,Zn)}submitScoreFromSource(e){return this.send(je.SubmitScoreFromSource,e,Zn)}claimCycleReward(e){return this.send(je.ClaimCycleReward,e,Yn)}claimMilestone(e){return this.send(je.ClaimMilestone,e,Xn)}getFriendsLeaderboard(e){return this.send(je.GetFriendsLeaderboard,e,Ui)}getLeaderboardsBatch(e){return this.send(je.GetLeaderboardsBatch,e,ic)}getProgressBatch(e){return this.send(je.GetProgressBatch,e,er)}claimCycleRewardsBatch(e){return this.send(je.ClaimCycleRewardsBatch,e,nc)}claimMilestonesBatch(e){return this.send(je.ClaimMilestonesBatch,e,rc)}submitScoresBatch(e){return this.send(je.SubmitScoresBatch,e,sc)}claimAllRewardsBatch(e){return this.send(je.ClaimAllRewardsBatch,e,oc)}getOverviewBatch(e){return this.send(je.GetOverviewBatch,e,ac)}};var Ts=class extends L{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Gt.GetDefinitions,e,rr)}getActiveSeason(e){return this.send(Gt.GetActiveSeason,e,nr)}getUserState(e){return this.send(Gt.GetUserState,e,Wo)}grantStatusTokens(e){return this.send(Gt.GrantStatusTokens,e,pc)}claimTierReward(e){return this.send(Gt.ClaimTierReward,e,Ko)}claimTierRewardsBatch(e){return this.send(Gt.ClaimTierRewardsBatch,e,dc)}};var As=class extends L{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(ei.GetDefinitions,e,Ch)}getUserState(e){return this.send(ei.GetUserState,e,Sh)}activateTrial(e){return this.send(ei.ActivateTrial,e,hs)}purchaseItemOrCurrency(e){return this.send(ei.PurchaseWithResources,e,Ie(hs))}purchaseRealMoney(e){return this.send(ei.PurchaseRealMoney,e,hs)}};var ws=class extends L{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(We.GetCharacterDefinitions,e,lr)}getUserCharacters(e){return this.send(We.GetUserCharacters,e,Rc)}unlockCharacter(e){return this.send(We.UnlockCharacter,e,Ie(Jo))}upgradeStatLevel(e){return this.send(We.UpgradeStatLevel,e,Ie(Ho))}upgradeCharacterLevel(e){return this.send(We.UpgradeCharacterLevel,e,Ie($o))}equipItems(e){return this.send(We.EquipItems,e,Cc)}unequipItems(e){return this.send(We.UnequipItems,e,Sc)}unequipAllCharacters(e){return this.send(We.UnequipAllCharacters,e,xc)}unlockCharactersBatch(e){return this.send(We.UnlockCharactersBatch,e,vc)}upgradeCharacterLevelsBatch(e){return this.send(We.UpgradeCharacterLevelsBatch,e,Tc)}upgradeStatLevelsBatch(e){return this.send(We.UpgradeStatLevelsBatch,e,Ac)}unlockSkin(e){return this.send(We.UnlockSkin,e,Ie(bc))}equipSkin(e){return this.send(We.EquipSkin,e,Dc)}unequipSkin(e){return this.send(We.UnequipSkin,e,Pc)}getCharacterSkins(e){return this.send(We.GetCharacterSkins,e,Ic)}};var ks=class extends L{constructor(e){super(e,"Match");}createMatch(e){return this.send(xt.CreateMatch,e,ld)}updateMatch(e){return this.send(xt.UpdateMatch,e,ud)}cancelMatch(e){return this.send(xt.CancelMatch,e,cd)}instantBattle(e){return this.send(xt.InstantBattle,e,pd)}saveStrategy(e){return this.send(xt.SaveStrategy,e,Be)}getMyMatches(e){return this.send(xt.GetMyMatches,e,Ia)}getAvailableMatches(e){return this.send(xt.GetAvailableMatches,e,Ia)}getDefinitions(e){return this.send(xt.GetDefinitions,e,fd)}};var bP={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Wh=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),DP={None:"None",Min:"Min",Average:"Average",Max:"Max"},PP=zod.z.enum(["None","Min","Average","Max"]).catch("None"),IP={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},vP=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),TP={Clamp:"Clamp",Reject:"Reject"},AP=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),wP=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),kP=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:co.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(wP).nullish()}),Kh=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,Type:Wh.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:M.nullish(),Inventory:K.nullish(),Results:zod.z.array(kP).nullish()}),zP=zod.z.object({CraftID:zod.z.string().nullish(),Type:Wh.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:ce.nullish(),OutputLevelMode:PP.nullish(),InputSelection:vP.nullish(),OutputLevelOverflow:AP.nullish()}).passthrough(),el=zod.z.object({Definitions:zod.z.record(zod.z.string(),zP).nullish()}).passthrough(),Qh=zod.z.object({ServerTimeUtc:p.nullish(),CraftDefinitions:el.nullish()}),zs={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Ms=class extends L{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(zs.GetDefinitions,e,Qh)}craft(e){return this.send(zs.Craft,e,Ie(Kh))}};var MP=2e5,Os=class extends L{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,Ie(dr),{timeoutMs:MP,autoRetry:false})}readGeneration(e,t){return this.send(e,t,dr,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Ve.GetDefinitions,e,Lc)}generateText(e){return this.generate(Ve.GenerateText,e)}getText(e){return this.readGeneration(Ve.GetText,e)}generateImage(e){return this.generate(Ve.GenerateImage,e)}editImage(e){return this.generate(Ve.EditImage,e)}getImage(e){return this.readGeneration(Ve.GetImage,e)}generateVideo(e){return this.generate(Ve.GenerateVideo,e)}getVideo(e){return this.readGeneration(Ve.GetVideo,e)}generateAudio(e){return this.generate(Ve.GenerateAudio,e)}getAudio(e){return this.readGeneration(Ve.GetAudio,e)}generateMusic(e){return this.generate(Ve.GenerateMusic,e)}getMusic(e){return this.readGeneration(Ve.GetMusic,e)}generateThreeD(e){return this.generate(Ve.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Ve.GetThreeD,e)}listGenerations(e){return this.send(Ve.ListGenerations,e,qc)}getGeneration(e){return this.readGeneration(Ve.GetGeneration,e)}};var OP={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},EP=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),Hh=zod.z.object({}).passthrough().transform(s=>s),vi=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()}),$h=zod.z.object({GrantedCollectibles:zod.z.array(vi).nullish(),DuplicateCollectibles:zod.z.array(vi).nullish(),CollectionCurrencyEarned:j.nullish()}),Jh=zod.z.object({CreditsConfirmation:fe.nullish(),OpenedCount:zod.z.number().nullish(),Packs:zod.z.array($h).nullish(),GrantedCollectibles:zod.z.array(vi).nullish(),DuplicateCollectibles:zod.z.array(vi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Zh=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array($h).nullish(),GrantedCollectibles:zod.z.array(vi).nullish(),DuplicateCollectibles:zod.z.array(vi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Yh=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),tl=zod.z.object({SetID:zod.z.string(),Resources:M.nullish(),Inventory:K.nullish()}),Xh=zod.z.array(we(tl)),em=zod.z.object({Resources:M.nullish(),Inventory:K.nullish()}),UP=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:qe.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:EP.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RespondedAtUtc:p.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),tm=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:p.nullish(),Resources:M.nullish()}),im=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),nm=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()}),rm=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),il=zod.z.object({Offers:zod.z.array(UP).nullish()}),qP=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(),LP=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(qP).nullish(),SetCompletionReward:H.nullish()}).passthrough(),BP=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(LP).nullish(),GrandPrize:H.nullish()}).passthrough(),sm=zod.z.object({BonusRewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),GP=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:ce.nullish(),BonusRewardSlots:zod.z.array(Pi).nullish(),PityRules:zod.z.array(Ii).nullish(),Presets:sm.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(),_P=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),FP=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(Pi).nullish(),PityRules:zod.z.array(Ii).nullish(),Presets:sm.nullish(),Tier:zod.z.number().nullish()}).passthrough(),VP=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),NP=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),Es=zod.z.object({Collections:zod.z.record(zod.z.string(),BP).nullish(),PackTypes:zod.z.record(zod.z.string(),GP).nullish(),CollectionChests:zod.z.array(FP).nullish(),DuplicateConversions:zod.z.array(_P).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(VP).nullish(),RewardPools:fs.nullish(),Settings:NP.nullish()}).passthrough(),Ke={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var Us=class extends L{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ke.GetDefinitions,e,Es)}getUserState(e){return this.send(Ke.GetUserState,e,Hh)}openPack(e){return this.send(Ke.OpenPack,e,Ie(Jh))}openCollectionChest(e){return this.send(Ke.OpenCollectionChest,e,Zh)}useCollectibleJoker(e){return this.send(Ke.UseCollectibleJoker,e,Yh)}claimSetReward(e){return this.send(Ke.ClaimSetReward,e,tl)}claimSetRewardsBatch(e){return this.send(Ke.ClaimSetRewardsBatch,e,Xh)}claimGrandPrize(e){return this.send(Ke.ClaimGrandPrize,e,em)}sendTradeOffer(e){return this.send(Ke.SendTradeOffer,e,tm)}cancelTradeOffer(e){return this.send(Ke.CancelTradeOffer,e,im)}acceptTradeOffer(e){return this.send(Ke.AcceptTradeOffer,e,nm)}declineTradeOffer(e){return this.send(Ke.DeclineTradeOffer,e,rm)}getMyTradeOffers(e){return this.send(Ke.GetMyTradeOffers,e,il)}getIncomingTradeOffers(e){return this.send(Ke.GetIncomingTradeOffers,e,il)}};var qs=class extends L{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(ft.GetDefinitions,e,gr)}getActiveEvent(e){return this.send(ft.GetActiveEvent,e,_c)}getUserState(e){return this.send(ft.GetUserState,e,fr)}getGroupState(e){return this.send(ft.GetGroupState,e,ia)}joinOrCreateGroup(e){return this.send(ft.JoinOrCreateGroup,e,ia)}spin(e){return this.send(ft.Spin,e,Ie(Vc))}claimObjectReward(e){return this.send(ft.ClaimObjectReward,e,na)}claimGrandPrize(e){return this.send(ft.ClaimGrandPrize,e,na)}leaveGroup(e){return this.send(ft.LeaveGroup,e,Nc)}};var Ls=class extends L{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(St.GetDefinition,e,ep)}getUserState(e){return this.send(St.GetUserState,e,tp)}getActiveDeals(e){return this.send(St.GetActiveDeals,e,Cr)}dismissDeal(e){return this.send(St.DismissDeal,e,np)}executeNode(e){return this.send(St.ExecuteNode,e,Ie(ip))}recordShow(e){return this.send(St.RecordShow,e,rp)}claimMilestone(e){return this.send(St.ClaimMilestone,e,sp)}claimMilestonesBatch(e){return this.send(St.ClaimMilestonesBatch,e,op)}};var jP=zod.z.object({}).passthrough().transform(s=>s),WP=zod.z.object({FeatureKey:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Rate:zod.z.number().nullish(),Basis:zod.z.string().nullish(),SourceCurrencyID:zod.z.string().nullish(),TargetCurrencyID:zod.z.string().nullish(),MinSourceAmount:zod.z.number().nullish(),MaxRewardPerOperation:zod.z.number().nullish(),Limits:Se.nullish()}).passthrough(),nl=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:zod.z.record(zod.z.string(),_e).nullish(),SpendRewards:zod.z.array(WP).nullish(),Qualification:zod.z.object({}).passthrough().transform(s=>s).nullish()}).passthrough(),rl=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(),om=zod.z.object({ReferralDefinitions:nl.nullish()}).passthrough(),am=zod.z.object({Referral:jP.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:rl.nullish()}).passthrough(),lm=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:rl.nullish()}).passthrough(),um=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),QualificationPending:zod.z.boolean().nullish(),Qualification:rl.nullish()}).passthrough(),sl=zod.z.object({RewardID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}).passthrough(),cm=Rt(sl),Kt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var Bs=class extends L{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Kt.GetDefinitions,e,om)}getUserState(e){return this.send(Kt.GetUserState,e,am)}activateReferralCode(e){return this.send(Kt.ActivateReferralCode,e,um)}claimInviteReward(e){return this.send(Kt.ClaimInviteReward,e,sl)}claimInviteRewardsBatch(e){return this.send(Kt.ClaimInviteRewardsBatch,e,cm)}checkQualification(e){return this.send(Kt.CheckQualification,e,lm)}};var Gs=class extends L{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(nt.GetDefinitions,e,pp)}getMessages(e){return this.send(nt.GetMessages,e,dp)}getUnreadCount(e){return this.send(nt.GetUnreadCount,e,br)}readMessages(e){return this.send(nt.ReadMessages,e,oa)}claimReward(e){return this.send(nt.ClaimReward,e,Dr)}claimRewardsBatch(e){return this.send(nt.ClaimRewardsBatch,e,Dr)}claimAll(e){return this.send(nt.ClaimAll,e,Dr)}deleteMessages(e){return this.send(nt.DeleteMessages,e,oa)}sendGift(e){return this.send(nt.SendGift,e,hp)}sendTransfer(e){return this.send(nt.SendTransfer,e,mp)}getGiftStatus(e){return this.send(nt.GetGiftStatus,e,fp)}};var _s=class extends L{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Ir.RequestAdPermit,e,gp)}completeView(e){return this.send(Ir.CompleteView,e,yp)}};var Fs=class extends L{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(xe.GetFriendsList,e,Li)}getIncomingRequests(e){return this.send(xe.GetIncomingRequests,e,Li)}getOutgoingRequests(e){return this.send(xe.GetOutgoingRequests,e,Li)}getRecommendedFriends(e){return this.send(xe.GetRecommendedFriends,e,Li)}sendFriendRequest(e){return this.send(xe.SendFriendRequest,e,Bi)}acceptFriendRequest(e){return this.send(xe.AcceptFriendRequest,e,Bi)}declineFriendRequest(e){return this.send(xe.DeclineFriendRequest,e,Bi)}removeFriend(e){return this.send(xe.RemoveFriend,e,Bi)}getInbox(e){return this.send(xe.GetInbox,e,Cp)}markInboxSeen(e){return this.send(xe.MarkInboxSeen,e,Gi)}getInboxUnread(e){return this.send(xe.GetInboxUnread,e,Gi)}follow(e){return this.send(xe.Follow,e,Vt)}unfollow(e){return this.send(xe.Unfollow,e,Vt)}getFollowers(e){return this.send(xe.GetFollowers,e,Ar)}getFollowing(e){return this.send(xe.GetFollowing,e,Ar)}block(e){return this.send(xe.Block,e,Vt)}unblock(e){return this.send(xe.Unblock,e,Vt)}getBlocked(e){return this.send(xe.GetBlocked,e,Ar)}react(e){return this.send(xe.React,e,Vt)}unreact(e){return this.send(xe.Unreact,e,Vt)}getMyReactions(e){return this.send(xe.GetMyReactions,e,xp)}getEntityStates(e){return this.send(xe.GetEntityStates,e,Sp)}addComment(e){return this.send(xe.AddComment,e,wr)}editComment(e){return this.send(xe.EditComment,e,wr)}deleteComment(e){return this.send(xe.DeleteComment,e,Dp)}getComments(e){return this.send(xe.GetComments,e,bp)}report(e){return this.send(xe.Report,e,Pp)}};var KP={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var ni=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),QP=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:ce.nullish(),Effect:ni.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(),Vs=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),ol=zod.z.object({Availability:Q.nullish(),Effects:Q.nullish()}).passthrough(),HP=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(ni).nullish(),Availability:Vs.nullish(),Presets:ol.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$P=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(ni).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),JP=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($P).nullish(),Availability:Vs.nullish(),Presets:ol.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ZP=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(ot).nullish(),Effects:zod.z.array(ni).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:Vs.nullish(),Presets:ol.nullish()}).passthrough(),YP=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),XP=zod.z.object({Effects:zod.z.array(ni).nullish()}).passthrough(),eI=zod.z.object({Availability:zod.z.record(zod.z.string(),Vs).nullish(),Effects:zod.z.record(zod.z.string(),XP).nullish()}).passthrough(),tI=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),YP).nullish()}).passthrough(),Ns=zod.z.object({Definitions:zod.z.record(zod.z.string(),QP).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),HP).nullish(),BoostChains:zod.z.record(zod.z.string(),JP).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),ZP).nullish(),Settings:tI.nullish(),Presets:eI.nullish()}).passthrough(),pm=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:ni.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:p.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:p.nullish()}).passthrough();var dm=zod.z.object({ServerTimeUtc:p.nullish(),Active:zod.z.record(zod.z.string(),pm).nullish()}),hm=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:pm.nullish(),Resources:M.nullish()}),iI={Scheduled:"Scheduled",Chain:"Chain"},nI=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),Effects:zod.z.array(ni).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),mm=zod.z.object({ServerTimeUtc:p.nullish(),Windows:zod.z.array(nI).nullish()}),ri={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var js=class extends L{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(ri.GetDefinitions,e,Ns)}getActive(e){return this.send(ri.GetActive,e,dm)}getActiveWindows(e){return this.send(ri.GetActiveWindows,e,mm)}activate(e){return this.send(ri.Activate,e,Ie(hm))}cleanupExpired(e){return this.send(ri.CleanupExpired,e,Be)}};var Ws=class extends L{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(gt.GetUserCustomDataDefinitions,e,Or)}getMyUserCustomData(e){return this.send(gt.GetMyUserCustomData,e,Ap)}getPublicUserCustomDataOf(e){return this.send(gt.GetPublicUserCustomDataOf,e,ma)}setPrivateData(e){return this.send(gt.SetPrivateData,e,fa)}setPublicData(e){return this.send(gt.SetPublicData,e,fa)}deleteKey(e){return this.send(gt.DeleteKey,e,Be)}batchSet(e){return this.send(gt.BatchSet,e,wp)}batchDelete(e){return this.send(gt.BatchDelete,e,kp)}batchGetPublicUserCustomDataOf(e){return this.send(gt.BatchGetPublicUserCustomDataOf,e,zp)}};var rI={Static:"Static",Runtime:"Runtime"},sI={Public:"Public",Private:"Private"},oI=zod.z.enum(["Client","Server","System"]).catch("Client"),aI=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),lI=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:p.nullish(),Version:zod.z.number().nullish(),LastWriter:oI.nullish(),ExpiresAt:p.nullish()}).passthrough(),fm=zod.z.record(zod.z.string(),lI),al=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:fm.nullish(),Runtime:fm.nullish(),NotModified:zod.z.boolean().nullish()}),uI=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:aI.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Ks=zod.z.object({Keys:zod.z.record(zod.z.string(),uI).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(),Ki={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Qs=class extends L{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Ki.GetTitleCustomDataDefinitions,e,Ks)}getPublicTitleData(e){return this.send(Ki.GetPublicTitleData,e,al)}getPublicTitleDataKeys(e){return this.send(Ki.GetPublicTitleDataKeys,e,al)}};var cI={Fast:"Fast",Sequential:"Sequential"},pI={Instant:"Instant",Timed:"Timed"};var dI={Hit:"Hit",Blocked:"Blocked"},hI=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),mI=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:H.nullish()}).passthrough();var fI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:H.nullish()}).passthrough(),gI=zod.z.object({Reward:H.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(fI).nullish(),Rate:gI.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 gm=zod.z.object({}).passthrough().transform(s=>s),ym=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Qe=zod.z.object({Operation:M.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),yI=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),RI=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(),CI=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(),SI=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(),Rm=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:H.nullish()}).passthrough(),xI=zod.z.object({Index:zod.z.number().nullish(),Type:zod.z.string().nullish(),CustomTypeID:zod.z.string().nullish(),RandomActionAttackWeight:zod.z.number().nullish(),RandomActionRaidWeight:zod.z.number().nullish(),ChanceTableID:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),bI=zod.z.object({Tiles:zod.z.record(zod.z.string(),xI).nullish()}).passthrough(),DI=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Qe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),PI=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(DI).nullish(),GuaranteedBonus:Qe.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),II=zod.z.object({Variants:zod.z.array(PI).nullish()}).passthrough(),vI=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:Qe.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),TI=zod.z.object({Outcomes:zod.z.array(vI).nullish()}).passthrough(),Cm=zod.z.object({PerAdMultiplierRange:ym.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),AI=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Qe.nullish()}).passthrough(),wI=zod.z.object({Tiers:zod.z.array(AI).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Qe.nullish()}).passthrough(),kI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Qe.nullish()}).passthrough(),zI=zod.z.object({Reward:Qe.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(kI).nullish(),Rate:zI.nullish()}).passthrough(),Sm=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),MI).nullish()}).passthrough(),OI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ce.nullish(),Multipliers:Cm.nullish(),Gradation:wI.nullish(),RunStats:Sm.nullish()}).passthrough(),EI=zod.z.object({Choices:zod.z.array(OI).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),UI=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Qe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),qI=zod.z.object({OnPassStart:Qe.nullish(),OnTileLanding:zod.z.record(zod.z.string(),Qe).nullish(),OnAttack:zod.z.record(zod.z.string(),Qe).nullish(),OnRaid:zod.z.record(zod.z.string(),Qe).nullish(),OnBuild:Qe.nullish(),OnStageComplete:Qe.nullish(),OnAttackBonusDrops:zod.z.array(UI).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),TI).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),EI).nullish()}).passthrough(),xm=zod.z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Rm).nullish(),HeistGridBonusConfig:II.nullish(),StageOperations:qI.nullish(),TileLandingMultiplier:ym.nullish(),EconomyOverride:SI.nullish()}).passthrough(),LI=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(Rm).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:xm.nullish()}).passthrough(),BI=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(),GI=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(),Hs=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(),bI).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),xm).nullish(),StagesByLevel:zod.z.record(zod.z.string(),LI).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:CI.nullish(),Dice:yI.nullish(),Bots:RI.nullish(),Targeting:BI.nullish(),BotRaids:GI.nullish()}).passthrough(),_I=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:p.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),GrandPrize:H.nullish()}).passthrough(),$s=zod.z.object({Board:Hs.nullish(),CommunityChest:_I.nullish()}).passthrough(),bm=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),pe).nullish()}).passthrough(),FI=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:qe.nullish(),TargetBuildingStates:zod.z.array(hI).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:bm.nullish()}).passthrough(),VI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ce.nullish(),Multipliers:Cm.nullish(),RunStats:Sm.nullish()}).passthrough(),NI=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(VI).nullish()}).passthrough(),jI=zod.z.object({GroupID:zod.z.string().nullish(),Delta:j.nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),Dm=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:j.nullish(),LandedTileType:zod.z.string().nullish(),Operation:M.nullish(),Inventory:K.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:FI.nullish(),SpecialModeOffer:NI.nullish(),CommunityChestContribution:jI.nullish()}).passthrough(),Pm=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:vt.nullish()}).passthrough(),ll=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:H.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(mI).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:vt.nullish(),RaidRewardPreview:bm.nullish()}).passthrough(),Im=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish()}).passthrough(),vm=zod.z.object({CreditsConfirmation:fe.nullish(),Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:M.nullish(),Inventory:K.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish()}).passthrough(),Tm=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),WI=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),Am=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:M.nullish(),Inventory:K.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(WI).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),KI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},wm=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),QI={Active:"Active",Left:"Left",Replaced:"Replaced"},HI=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),$I=zod.z.object({CurrentProgress:j.nullish(),MaxProgress:j.nullish()}).passthrough(),JI=zod.z.object({UserID:zod.z.string().nullish(),PublicData:qe.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:j.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),ql).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:HI.nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),km=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(JI).nullish(),SharedProgress:$I.nullish(),Status:wm.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:zod.z.number().nullish()}).passthrough(),ZI=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:wm.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:p.nullish()}).passthrough(),YI=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(ZI).nullish()}).passthrough(),zm=zod.z.object({ServerTimeUtc:p.nullish(),UserState:YI.nullish(),ActiveGroup:km.nullish(),SecondsRemaining:j.nullish()}),Mm=zod.z.object({ServerTimeUtc:p.nullish(),Group:km.nullish(),SecondsRemaining:j.nullish()}),ul=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Om=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Ge={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var XI={Mesh:"Mesh",Host:"Host"},cl=zod.z.enum(["Mesh","Host"]).catch("Mesh"),ev={ServerRelay:"ServerRelay",P2P:"P2P"},pl=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),tv={Public:"Public",Private:"Private"},iv=zod.z.enum(["Public","Private"]).catch("Public"),nv={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},rv=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Em=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),sv=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Um=zod.z.object({SystemState:sv.nullish(),DefaultTopology:cl.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:pl.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(Em).nullish()}).passthrough(),ov=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(),av=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:cl.nullish(),ChatMode:pl.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(),lv=zod.z.object({Seq:zod.z.number().nullish(),Type:rv.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(),Qi=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:cl.nullish(),ChatMode:pl.nullish(),Visibility:iv.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(ov).nullish(),IceServers:zod.z.array(Em).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),qm=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),Lm=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),dl=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),Bm=zod.z.object({Rooms:zod.z.array(av).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Gm=zod.z.object({Envelopes:zod.z.array(lv).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Js=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),Ze={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 hl=zod.z.object({TitleCustomData:Ks.nullish(),Character:lr.nullish(),Item:ls.nullish(),Currency:Gr.nullish(),Store:An.nullish(),Lootbox:Ja.nullish(),Quest:tn.nullish(),TimedEvent:Qn.nullish(),Leaderboard:tr.nullish(),Season:rr.nullish(),Reward:Ya.nullish(),Collection:Es.nullish(),Craft:el.nullish(),DealOffer:ra.nullish(),Premium:Qa.nullish(),TimedBoost:Ns.nullish(),CoopEvent:gr.nullish(),GameLoop:$s.nullish(),Match:va.nullish(),Experiment:Yd.nullish(),Blockchain:Ca.nullish(),Marketplace:za.nullish(),Multiplayer:Um.nullish(),UserCustomData:Or.nullish(),Referral:nl.nullish(),Localization:lh.nullish(),Analytics:Fd.nullish(),Social:Ip.nullish(),PlatformBridge:vp.nullish(),GameSpec:zod.z.string().nullish()}).passthrough();var si={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Zs=class extends L{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(si.GetTitlePublicConfiguration,e,hl)}getTitlePublicConfigurationExcept(e){return this.send(si.GetTitlePublicConfigurationExcept,e,hl)}getCurrencyDefinitions(e){return this.send(si.GetCurrencyDefinitions,e,Gr)}getItemDefinitions(e){return this.send(si.GetItemDefinitions,e,ls)}getServerTime(e){return this.send(si.GetServerTime,e,Be)}};var Ys=class extends L{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Ge.GetGameLoops,e,$s)}getBoardDefinition(e,t=false){return this.send(Ge.GetBoardDefinition,e,Hs,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Ge.GetBoardDefinitionForLevel,e,Hs,{silent:t})}getUserBoardState(e){return this.send(Ge.GetUserBoardState,e,gm)}boardLoopRoll(e){return this.send(Ge.BoardLoopRoll,e,Dm)}boardLoopAttack(e){return this.send(Ge.BoardLoopAttack,e,Pm)}boardLoopRaid(e){return this.send(Ge.BoardLoopRaid,e,ll)}boardLoopRaidFast(e){return this.send(Ge.BoardLoopRaidFast,e,ll)}boardLoopBuild(e){return this.send(Ge.BoardLoopBuild,e,Im)}boardSpecialChoose(e){return this.send(Ge.BoardSpecialChoose,e,Ie(vm))}boardSpecialApplyMultiplier(e){return this.send(Ge.BoardSpecialApplyMultiplier,e,Tm)}boardSpecialClaim(e){return this.send(Ge.BoardSpecialClaim,e,Am)}getCommunityChestState(e){return this.send(Ge.GetCommunityChestState,e,zm)}joinOrCreateCommunityChest(e){return this.send(Ge.JoinOrCreateCommunityChest,e,Mm)}claimCommunityChestMilestone(e){return this.send(Ge.ClaimCommunityChestMilestone,e,ul)}claimCommunityChestGrandPrize(e){return this.send(Ge.ClaimCommunityChestGrandPrize,e,ul)}leaveCommunityChest(e){return this.send(Ge.LeaveCommunityChest,e,Om)}};var uv={Live:"Live",Latest:"Latest",Specific:"Specific"},cv={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},pv=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),dv={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"},hv=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),mv=zod.z.object({Level:pv,Message:zod.z.string().nullish(),Data:_t.nullish()}),fv=zod.z.object({Error:hv,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Fm=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:_t.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(mv).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:fv.nullish()}),ml={Execute:"Execute"};var Xs=class extends L{constructor(e){super(e,"CloudCode");}execute(e){return this.send(ml.Execute,e,Fm)}};var eo=class extends L{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Je.GetDefinitions,e,$p)}getUserState(e){return this.send(Je.GetUserState,e,Jp)}depositToken(e){return this.send(Je.DepositToken,e,Zp)}depositNFT(e){return this.send(Je.DepositNFT,e,Yp)}requestTokenWithdrawal(e){return this.send(Je.RequestTokenWithdrawal,e,Xp)}requestNFTWithdrawal(e){return this.send(Je.RequestNFTWithdrawal,e,ed)}getTransactionHistory(e){return this.send(Je.GetTransactionHistory,e,td)}retryWithdrawal(e){return this.send(Je.RetryWithdrawal,e,id)}confirmWithdrawal(e){return this.send(Je.ConfirmWithdrawal,e,nd)}donateToDeveloper(e){return this.send(Je.DonateToDeveloper,e,Da)}donateToUsersPool(e){return this.send(Je.DonateToUsersPool,e,Da)}getPlayAccess(e){return this.send(Je.GetPlayAccess,e,Qp)}confirmPlayAccess(e){return this.send(Je.ConfirmPlayAccess,e,Nt)}};var to=class extends L{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Oe.GetDefinitions,e,yd)}getGroupedOffers(e){return this.send(Oe.GetGroupedOffers,e,Rd)}getOffersByItem(e){return this.send(Oe.GetOffersByItem,e,Ma)}getOffer(e){return this.send(Oe.GetOffer,e,Cd)}getBuyOrders(e){return this.send(Oe.GetBuyOrders,e,Ma)}getMyState(e){return this.send(Oe.GetMyState,e,Kr)}getHistory(e){return this.send(Oe.GetHistory,e,xd)}createListing(e){return this.send(Oe.CreateListing,e,Ni)}cancelListing(e){return this.send(Oe.CancelListing,e,ct)}buy(e){return this.send(Oe.Buy,e,ct)}marketBuy(e){return this.send(Oe.MarketBuy,e,ct)}marketSell(e){return this.send(Oe.MarketSell,e,ct)}createAuction(e){return this.send(Oe.CreateAuction,e,Ni)}placeBid(e){return this.send(Oe.PlaceBid,e,Sd)}claimAuction(e){return this.send(Oe.ClaimAuction,e,ct)}createBuyOrder(e){return this.send(Oe.CreateBuyOrder,e,Ni)}cancelBuyOrder(e){return this.send(Oe.CancelBuyOrder,e,ct)}fillBuyOrder(e){return this.send(Oe.FillBuyOrder,e,ct)}createDirectTrade(e){return this.send(Oe.CreateDirectTrade,e,Ni)}respondDirectTrade(e){return this.send(Oe.RespondDirectTrade,e,ct)}cancelDirectTrade(e){return this.send(Oe.CancelDirectTrade,e,ct)}claimBack(e){return this.send(Oe.ClaimBack,e,ct)}};var io=class extends L{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(Ze.CreateRoom,e,Qi)}joinRoom(e){return this.send(Ze.JoinRoom,e,Qi)}leaveRoom(e,t=false){return this.send(Ze.LeaveRoom,e,dl,{keepalive:t})}listRooms(e){return this.send(Ze.ListRooms,e,Bm)}getRoom(e){return this.send(Ze.GetRoom,e,Qi)}closeRoom(e){return this.send(Ze.CloseRoom,e,dl)}poll(e){return this.send(Ze.Poll,e,Gm)}sendSignal(e){return this.send(Ze.SendSignal,e,Js,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(Ze.ClaimHost,e,Qi)}kickMember(e){return this.send(Ze.KickMember,e,qm)}unbanMember(e){return this.send(Ze.UnbanMember,e,Lm)}sendChat(e){return this.send(Ze.SendChat,e,Js)}setMemberState(e){return this.send(Ze.SetMemberState,e,Js)}};var gv={Free:"Free",Price:"Price",Holding:"Holding"},fl=zod.z.enum(["Free","Price","Holding"]).catch("Free"),yv={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},Rv=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),Cv={All:"All",Any:"Any"},Sv=zod.z.enum(["All","Any"]).catch("All"),xv={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},bv=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),Dv={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},Pv=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),Iv={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Nm=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),vv={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},Tv={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},Av=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),wv=zod.z.object({Type:hi.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(),kv=zod.z.object({Requirements:zod.z.array(wv).nullish(),Match:Sv.nullish(),Mode:Rv.nullish()}).passthrough(),zv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:fl.nullish(),Price:pe.nullish(),Holding:kv.nullish()}).passthrough(),Mv=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(),Ov=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),Mv).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(fl).nullish(),PricePolicy:Wr.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ce.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),Ev=zod.z.object({Allowed:zod.z.array(Vi).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),Uv=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),qv=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(),Lv=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Schedule:Re.nullish(),Gate:Z.nullish(),Order:zod.z.number().nullish()}).passthrough(),Bv=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:Re.nullish(),ContentTypes:zod.z.record(zod.z.string(),Ov).nullish(),PricePolicy:Wr.nullish(),Commission:ka.nullish(),HoldingPolicy:Ev.nullish(),Moderation:Uv.nullish(),Limits:qv.nullish(),Featured:zod.z.array(Lv).nullish()}).passthrough(),Gv=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(),oi=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:qe.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:bv.nullish(),Access:zod.z.array(zv).nullish(),Status:Pv.nullish(),ModerationNote:zod.z.string().nullish(),Stats:Gv.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),PublishedAt:p.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),_v=zod.z.object({OptionID:zod.z.string().nullish(),Mode:fl.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),jm=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(),Wm=zod.z.object({Definitions:Bv.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(jm).nullish()}).passthrough(),no=zod.z.object({Items:zod.z.array(oi).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Km=zod.z.object({Content:oi.nullish(),AccessState:zod.z.array(_v).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Qm=zod.z.object({Collection:jm.nullish(),Items:zod.z.array(oi).nullish()}).passthrough(),Hm=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:qe.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(oi).nullish()}).passthrough(),Vm=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(),$m=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(Vm).nullish(),ThumbnailUpload:Vm.nullish(),ExpiresAt:p.nullish()}).passthrough(),Jm=zod.z.object({CreditsConfirmation:fe.nullish(),Content:oi.nullish(),Resources:M.nullish()}).passthrough(),gl=zod.z.object({Content:oi.nullish()}).passthrough(),Zm=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Nm.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:vt.nullish(),Resources:M.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Fv=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),Ym=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:Av.nullish(),Files:zod.z.array(Fv).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:p.nullish()}).passthrough(),Vv=zod.z.object({ContentID:zod.z.string().nullish(),Source:Nm.nullish(),OptionID:zod.z.string().nullish(),PricePaid:pe.nullish(),AcquiredAt:p.nullish(),Content:oi.nullish()}).passthrough(),Xm=zod.z.object({Licenses:zod.z.array(Vv).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),He={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 ro=class extends L{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(He.GetDefinitions,e,Wm)}browse(e){return this.send(He.Browse,e,no)}getContent(e){return this.send(He.GetContent,e,Km)}getCollection(e){return this.send(He.GetCollection,e,Qm)}getCreatorProfile(e){return this.send(He.GetCreatorProfile,e,Hm)}beginUpload(e){return this.send(He.BeginUpload,e,$m)}publish(e){return this.send(He.Publish,e,Ie(Jm))}updateContent(e){return this.send(He.UpdateContent,e,gl)}unpublish(e){return this.send(He.Unpublish,e,gl)}getMyContent(e){return this.send(He.GetMyContent,e,no)}acquire(e){return this.send(He.Acquire,e,Zm)}getDownload(e){return this.send(He.GetDownload,e,Ym)}getMyLicenses(e){return this.send(He.GetMyLicenses,e,Xm)}getMyFavorites(e){return this.send(He.GetMyFavorites,e,no)}};var so=class extends L{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,n){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${n}`})}sendPublic(e,t,i,n){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${n}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,Td,"defs")}get(e){return this.sendKeyed("Get",e,Ea,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,wd,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,Ua,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,kd,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,qa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,qa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,zd,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,Od,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Md,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,Ed,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,Ad,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Ud,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,Ea,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,Ua,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var oo=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;credits;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.settings=xl(e),this.emitter=new wi,this.platform=e.platform??new ci,this.clientPlatform=e.clientPlatform??El(),this.acquisition=new Ht(this.platform),this.acquisition.capture(),this.playtime=new ki(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new un({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 hn(this.emitter),this.cache=new fn(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new gn(this.platform.storage,this.settings.titleID),this.api={authentication:new ns(this),user:new ss(this),currency:new os(this),item:new us(this),store:new cs(this),purchase:new ms(this),lootbox:new ys(this),reward:new Rs(this),quest:new Ps(this),tutorial:new Cs(this),communityMarketing:new Ss(this),chat:new xs(this),push:new bs(this),localization:new Ds(this),timedEvent:new Is(this),leaderboard:new vs(this),season:new Ts(this),premium:new As(this),character:new ws(this),match:new ks(this),craft:new Ms(this),ai:new Os(this),collection:new Us(this),coopEvent:new qs(this),dealOffer:new Ls(this),referral:new Bs(this),mailbox:new Gs(this),advertising:new _s(this),social:new Fs(this),timedBoost:new js(this),userCustomData:new Ws(this),titleCustomData:new Qs(this),title:new Zs(this),gameLoop:new Ys(this),cloudCode:new Xs(this),blockchain:new eo(this),marketplace:new to(this),multiplayer:new io(this),workshop:new ro(this),dataCollections:new so(this),analytics:new ts(this),experiment:new is(this)},this.userService=new bn(this),this.cache.attachState(this.userService),this.auth=new Rn(this),this.currency=new Pn(this),this.item=new In(this),this.store=new kn(this),this.credits=new zn(this),this.purchase=new Mn(this),this.checkout=new On(this),this.lootbox=new En(this),this.reward=new qn(this),this.quest=new Kn(this),this.tutorial=new Bn(this),this.communityMarketing=new Gn(this),this.chat=new Vn(this),this.push=new Nn(this),this.localization=new Wn(this),this.timedEvent=new $n(this),this.leaderboard=new ir(this),this.season=new sr(this),this.premium=new or(this),this.character=new ur(this),this.match=new cr(this),this.craft=new pr(this),this.ai=new hr(this),this.collection=new mr(this),this.coopEvent=new yr(this),this.dealOffer=new Sr(this),this.referral=new xr(this),this.mailbox=new Pr(this),this.ads=new Tr(this),this.social=new kr(this),this.timedBoost=new zr(this),this.userCustomData=new Er(this),this.titleCustomData=new Ur(this),this.title=new qr(this),this.gameLoop=new Lr(this),this.cloudCode=new Br(this),this.blockchain=new Fr(this),this.marketplace=new Qr(this),this.multiplayer=new Hr(this),this.workshop=new $r(this),this.dataCollections=new Zr(this),this.analytics=new Xr(this),this.experiments=new es(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.platform.getFullURL(),RelatedEntityID:B()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var ao=class{ctx;constructor(e){this.ctx=new oo(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let n=this.ctx.buildAuthedBaseRequest(),r=Wt(this.ctx.settings.titleID,e,t,n.UserID??"");return this.ctx.transport.post(r,{...n,...i},zod.z.unknown(),{ticket:n.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get platform(){return this.ctx.platform}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 jv(s){return new ao(s)}var ef="idos_sso",tf="state",yl="idos:sso:state",Wv="https://idosgames.com/sso/",Kv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],Qv=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function Hv(){if(typeof window>"u")return false;let{origin:s}=window.location;return Kv.includes(s)||Qv.test(s)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function $v(){if(typeof window>"u")return null;let s=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!s)return null;let e=new URLSearchParams(s),t=e.get(ef);if(!t)return null;let i=e.get(tf)??"",n=eT();return iT(e),tT(),n&&i!==n?null:{code:t,state:i}}function Jv(s){if(typeof window>"u")return;let e=s.returnTo??Zv(),t=Yv();Xv(t);let i=new URL(s.ssoUrl??Wv);i.searchParams.set("title",s.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function Zv(){let{origin:s,pathname:e,search:t}=window.location;return `${s}${e}${t}`}function Yv(){let s=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(s);else for(let e=0;e<s.length;e++)s[e]=Math.floor(Math.random()*256);return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}function Xv(s){try{window.sessionStorage.setItem(yl,s);}catch{}}function eT(){try{return window.sessionStorage.getItem(yl)}catch{return null}}function tT(){try{window.sessionStorage.removeItem(yl);}catch{}}function iT(s){s.delete(ef),s.delete(tf);let e=s.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var nT={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 rT(s,e="Something went wrong. Please try again."){return s?nT[s]??s:e}function sT(s,e){return !!s?.Claims?.[e]?.ClaimedAt}function oT(s){let e=s?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function aT(s,e){return s?.Claims?.[e]?.PremiumTiers??[]}function rf(s,e,t,i=1){if(!s)return e;let n=s.Base??e,r=Math.max(0,t-i),o;switch(s.Shape??"Flat"){case "PerStep":o=n+(s.PerStep??0)*r;break;case "PerStepRate":o=n*(1+(s.PerStepRate??0)*r);break;case "Geometric":o=n*Math.pow(1+(s.GrowthRate??0),r);break;case "Table":o=n*nf(s,t,1);break;case "TableAbsolute":o=nf(s,t,n);break;default:o=n;break}return Number.isNaN(o)?n:(s.MinResult!=null&&o<s.MinResult&&(o=s.MinResult),s.MaxResult!=null&&o>s.MaxResult&&(o=s.MaxResult),o)}function lT(s,e,t=1){return rf(s,1,e,t)}function uT(s){if(!s)return false;switch(s.Shape??"Flat"){case "PerStep":return (s.PerStep??0)!==0;case "PerStepRate":return (s.PerStepRate??0)!==0;case "Geometric":return (s.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return sf(s.Points).length>0;default:return s.MinResult!=null||s.MaxResult!=null}}function cT(s){if(Number.isNaN(s)||s<=0)return 0;if(!Number.isFinite(s))return Number.MAX_SAFE_INTEGER;let e=Math.round(s);return Math.abs(s-e)<=1e-9*Math.max(1,Math.abs(s))?e:Math.ceil(s)}function sf(s){if(!s)return [];let e=[];for(let t of s)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function nf(s,e,t){let i=sf(s.Points);if(i.length===0)return t;let n=null,r=null,o=null;for(let c of i)(o===null||c.AtStep>o.AtStep)&&(o=c),c.AtStep<=e&&(n===null||c.AtStep>=n.AtStep)&&(n=c),c.AtStep>e&&(r===null||c.AtStep<r.AtStep)&&(r=c);if(n===null)return t;if(r===null){let c=s.TailGrowthRate??0;return c===0?o.Value:o.Value*Math.pow(1+c,e-o.AtStep)}switch(s.Interpolation??"Step"){case "Linear":{let c=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value+c*(r.Value-n.Value)}case "Geometric":{if(n.Value<=0||r.Value<=0){let h=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value+h*(r.Value-n.Value)}let c=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value*Math.pow(r.Value/n.Value,c)}default:return n.Value}}var pT={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Rl=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),dT={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},hT=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),mT=zod.z.object({PlacementID:zod.z.string().nullish(),Type:Rl.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(),fT=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(),gT=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),yT=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:hT.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),RT=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),CT=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),ST=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),DisableInterstitials:zod.z.boolean().nullish(),DisableBanners:zod.z.boolean().nullish(),DisableAppOpen:zod.z.boolean().nullish()}).passthrough(),xT=zod.z.object({RequirePersonalizedAdsConsent:zod.z.boolean().nullish(),RequireTrackingConsent:zod.z.boolean().nullish(),CurrentPolicyVersion:zod.z.string().nullish(),RegulatedRegions:zod.z.array(zod.z.string()).nullish()}).passthrough(),bT=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),DT=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:Rl.nullish()}).passthrough(),PT={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},IT=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),vT=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:IT.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(),DT).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),mT).nullish(),Providers:zod.z.record(zod.z.string(),vT).nullish(),RewardedVideo:fT.nullish(),Interstitial:gT.nullish(),Banner:yT.nullish(),AppOpen:RT.nullish(),FrequencyCapping:CT.nullish(),PremiumAdReductions:zod.z.array(ST).nullish(),Consent:xT.nullish(),Verification:bT.nullish()}).passthrough();var TT=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),AT=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:p.nullish(),LastCompletedAt:p.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),wT=zod.z.object({Date:p.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),kT=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:p.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),zT=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:p.nullish(),ConsentRevokedAt:p.nullish()}).passthrough(),MT=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:Rl.nullish(),IssuedAt:p.nullish(),ExpiresAt:p.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),OT=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:p.nullish()}).passthrough();zod.z.object({Credits:TT.nullish(),Placements:zod.z.record(zod.z.string(),AT).nullish(),Daily:wT.nullish(),Session:kT.nullish(),LastImpressionAt:p.nullish(),LastInterstitialAt:p.nullish(),LastRewardedAt:p.nullish(),LastAppOpenAt:p.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:p.nullish(),Consent:zT.nullish(),PendingRequests:zod.z.record(zod.z.string(),MT).nullish(),FraudFlags:OT.nullish(),UpdatedAt:p.nullish()}).passthrough();var of="idos_device_id",lo=class{storage;constructor(e=new li){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(of);return e||(e="noop-device",this.storage.setString(of,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};
|
|
2
|
-
exports.AIAction=
|
|
1
|
+
'use strict';var zod=require('zod'),Zt=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Zt__default=/*#__PURE__*/_interopDefault(Zt);var zi=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,n=>{i(),t(n);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let n of [...i])n(t);}removeAllListeners(){this.listeners.clear();}};function cf(){let s=new Map;return {get:e=>s.get(e)??null,set:(e,t)=>{s.set(e,t);},remove:e=>{s.delete(e);}}}function xl(){return pf()??cf()}function pf(){try{let s=globalThis.localStorage;if(!s)return null;let e="__idos_probe__";return s.setItem(e,"1"),s.removeItem(e),{get:t=>{try{return s.getItem(t)}catch{return null}},set:(t,i)=>{try{s.setItem(t,i);}catch{try{s.removeItem(t);}catch{}}},remove:t=>{try{s.removeItem(t);}catch{}}}}catch{return null}}var bl="https://api.idosgames.com";function Dl(s){return {titleID:s.titleID,titleTemplateID:s.titleTemplateID??"default",buildKey:s.buildKey??"",baseUrl:(s.baseUrl??bl).replace(/\/+$/,""),devBuild:s.devBuild??false,debugLogging:s.debugLogging??false,configStorage:s.configStorage??xl(),locale:s.locale??df(),appVersion:s.appVersion??""}}function df(){try{return globalThis.navigator?.language??""}catch{return ""}}var li=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{}}},ui=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);}};function ci(){return globalThis.Telegram?.WebApp??null}function G(){return crypto.randomUUID()}var Il="idos_device_id",pi=class{storage;constructor(e=new li){this.storage=e;}getPlatform(){return ci()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=ci()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=ci()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(Il);return e||(e=G(),this.storage.setString(Il,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let t=ci();if(t?.openTelegramLink){t.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let t=ci();if(t?.openInvoice){t.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let t=globalThis;typeof t.showAd=="function"&&await t.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var po="idos_acq",Pl=["gclid","fbclid","ttclid","msclkid","yclid"],hf=["ref","r"],mf=["ref_","ref-","ref=","r_","r-"];var $t=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();ff(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},n=Rf(this.platform.getDeviceModel());return n&&(i.OsVersion=n),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(po);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let i=Al(Tl(t));if(i)return i}return Ji(t)}readFromEnvironment(){let e={},t=Tl(this.platform.getFullURL());Ht(e,"UtmSource",t.get("utm_source")),Ht(e,"UtmMedium",t.get("utm_medium")),Ht(e,"UtmCampaign",t.get("utm_campaign")),Ht(e,"UtmTerm",t.get("utm_term")),Ht(e,"UtmContent",t.get("utm_content")),Ht(e,"ClaimToken",t.get("idos_click"));for(let y of Pl){let V=t.get(y);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",n=yf(i);if(n){for(let y of gf)Ht(e,y,n.get(wl[y])??null);for(let y of Pl){let V=n.get(y);if(V){e.ClickID=V;break}}}let r=Ji(n?n.get("ref")??n.get("r")??"":i),o=Al(t),c=r||o;c&&(e.ReferralCode=c,e.ChannelHint=r?"telegram":"query");let h=this.platform.getReferrer?.();return h&&(e.Referrer=h),e}read(){try{let e=this.platform.storage.getString(po);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.platform.storage.setString(po,JSON.stringify(e));}catch{}}};function ff(s){return !!(s.UtmSource||s.UtmMedium||s.UtmCampaign||s.ClickID||s.Referrer||s.ReferralCode||s.ClaimToken)}function Ht(s,e,t){t&&(s[e]=t);}var vl="a1_",wl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},gf=Object.keys(wl);function yf(s){let e=(s||"").trim();if(!e.startsWith(vl))return null;let t=e.slice(vl.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(i+"=".repeat((4-i.length%4)%4)),r=Uint8Array.from(n,h=>h.charCodeAt(0)),o=new TextDecoder().decode(r),c=new URLSearchParams(o);return [...c.keys()].length>0?c:null}catch{return null}}function Tl(s){try{let e=s.indexOf("?");return new URLSearchParams(e>=0?s.slice(e):"")}catch{return new URLSearchParams}}function Al(s){for(let e of hf){let t=s.get(e);if(t)return Ji(t)}return null}function Ji(s){let e=(s||"").trim();if(!e)return null;for(let t of mf)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Rf(s){let e=s||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var kl="idos_usage_pending",zl="idos_usage_session",Ml="idos_usage_closed_session",Ol="idos_usage_new_session",El="idos_usage_last_activity",Mi=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;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=typeof document<"u"&&document.visibilityState==="hidden",this.timer=setInterval(()=>this.tick(),200*1e3),window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide)),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();}};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,i=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,i,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(kl),this.currentSessionSeconds=this.readNumber(zl),this.pendingClosedSessionSeconds=this.readNumber(Ml),this.isNewSessionPending=this.readNumber(Ol)!==0;let e=this.readNumber(El);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(kl,this.pendingSeconds),this.writeNumber(zl,this.currentSessionSeconds),this.writeNumber(Ml,this.pendingClosedSessionSeconds),this.writeNumber(Ol,this.isNewSessionPending?1:0),this.writeNumber(El,Date.now());}readNumber(e){let t=this.ctx.platform.storage.getString(e),i=t?Number(t):0;return Number.isFinite(i)&&i>0?i:0}writeNumber(e,t){try{this.ctx.platform.storage.setString(e,String(Math.floor(t)));}catch{}}};var ht={Virtual:"Virtual",Crypto:"Crypto"},hi=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),Zi={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},mi=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),Rt={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Yi=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),Cf={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Xi=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),Sf={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},en=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),xf={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},Oi=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),ze={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function ql(){let s=globalThis,e=s.Capacitor?.getPlatform?.();if(e)return Ul(e);let t=s.cordova?.platformId;return t?Ul(t):s.navigator?.userAgent??""?Rt.Web:Rt.Unknown}function Ul(s){let e=s.toLowerCase();return e==="android"?Rt.Android:e==="ios"?Rt.Ios:e==="web"?Rt.Web:Rt.Unknown}function N(s){return {ok:true,data:s}}function u(s,e){return {ok:false,reason:s,error:e}}var a=u("unauthorized","Not logged in.");function bf(s){return s.ok}function Df(s){return !s.ok}var W=zod.z.union([zod.z.number(),zod.z.string()]).transform((s,e)=>{let t=typeof s=="string"?Number(s):s;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(s)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((s,e)=>{let t=typeof s=="number"?String(s):s.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(s)}`}),zod.z.NEVER):t}),p=zod.z.string();var ho=zod.z.object({Type:mi.nullish(),CurrencyID:zod.z.string().nullish(),Amount:W.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),If=zod.z.object({Type:en.nullish(),EntityID:zod.z.string()}),Pf=zod.z.object({Address:If.nullish(),Amount:W.nullish(),Source:zod.z.string().nullish()}),pe=zod.z.object({Entries:zod.z.array(ho).nullish(),EventTokens:zod.z.array(Pf).nullish()}),Ll=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:pe.nullish()}),H=zod.z.object({Standard:pe.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Ll).nullish()}),vt=zod.z.object({Standard:pe.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Ll).nullish()}),M=zod.z.object({Grant:H.nullish(),Consume:vt.nullish()}),Tt=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:pe.nullish()});var vf=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Tf={Completed:"Completed",Started:"Started",StepReached:"StepReached"},Af=zod.z.object({FlowIDs:zod.z.array(zod.z.string()).nullish(),Mode:zod.z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:zod.z.string().nullish(),Negate:zod.z.boolean().nullish(),SkippedCountsAsCompleted:zod.z.boolean().nullish()}).passthrough(),Z=zod.z.object({Segments:zod.z.array(zod.z.string()).nullish(),MinPremiumTier:zod.z.number().nullish(),RequiredPremiumIDs:zod.z.array(zod.z.string()).nullish(),MinLevel:zod.z.number().nullish(),MaxLevel:zod.z.number().nullish(),Countries:zod.z.array(zod.z.string()).nullish(),RegisteredWithinDays:zod.z.number().nullish(),ActiveWithinDays:zod.z.number().nullish(),Experiment:vf.nullish(),Tutorial:Af.nullish(),Platforms:zod.z.array(Yi).nullish()}).passthrough();var Se=zod.z.object({TotalCap:zod.z.number().nullish(),DailyCap:zod.z.number().nullish(),DailyWeightCap:zod.z.number().nullish(),PerActivationCap:zod.z.number().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish()}).passthrough();var wf=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),kf=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),zf=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 Mf=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 ot=zod.z.object({SourceType:zod.z.string().nullish(),BaseWeight:zod.z.number().nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish(),TileTypeFilter:zod.z.array(zod.z.string()).nullish(),TileIndexFilter:zod.z.array(zod.z.number()).nullish(),ChanceOutcomeFilter:zod.z.array(zod.z.string()).nullish(),OutcomeFilter:zod.z.array(zod.z.string()).nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Limits:Se.nullish()}).passthrough(),Re=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:kf.nullish(),Chain:zf.nullish(),Cyclic:Mf.nullish(),ActivationTriggers:zod.z.array(ot).nullish(),Relative:wf.nullish()}).passthrough();var Of={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},Ef=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Uf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},qf=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),Lf=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Ne=zod.z.object({Base:zod.z.number().nullish(),Shape:Ef.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(Lf).nullish(),Interpolation:qf.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var Bf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:H.nullish()}).passthrough(),Gf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),mo=zod.z.object({Bundles:zod.z.array(Bf).nullish(),Multipliers:zod.z.array(Gf).nullish()}).passthrough();var Ff=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),tn=zod.z.object({Source:Ff.nullish(),SourceKey:zod.z.string().nullish(),Curve:Ne.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:pe.nullish(),ExcludeRewards:pe.nullish()}).passthrough(),Bl=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),_e=zod.z.object({MilestoneID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredProgress:zod.z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:mo.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),fi=zod.z.object({Milestones:zod.z.record(zod.z.string(),_e).nullish()}).passthrough();var Q=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var _f=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Jt=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:_f.nullish()}).passthrough();var Vf=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),Gl=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:Vf.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),K=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),Gl).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var we=s=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:s.nullish()}),Ct=s=>zod.z.object({ServerTimeUtc:p,Items:zod.z.array(we(s)),Resources:M.nullish(),Inventory:K.nullish()});var Nf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Fl=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),jf=zod.z.object({}).passthrough().transform(s=>s),Wf=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:p.nullish(),CycleEndUtc:p.nullish(),PointsTotalEarned:W.nullish(),PointsCurrent:W.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),fo=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:W.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:Fl}),_l=zod.z.object({State:jf.nullish(),PointsTracks:zod.z.record(zod.z.string(),Wf).nullish()}),go=zod.z.object({ServerTimeUtc:p,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:Fl.nullish(),Resources:M.nullish(),Inventory:K.nullish()}),yo=zod.z.object({ServerTimeUtc:p,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:W.nullish(),Resources:M.nullish(),Inventory:K.nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Vl=zod.z.object({ServerTimeUtc:p,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Nl=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(fo).nullish()}),jl=zod.z.array(we(go)),Wl=zod.z.array(we(yo)),Kf={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Qf=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Hf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},$f=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),Kl=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:Qf.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(ot).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),Ro=zod.z.object({Milestones:Q.nullish(),Linking:Q.nullish(),Availability:Q.nullish(),Reward:Q.nullish(),Objectives:Q.nullish()}).passthrough(),Jf=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(),Ql=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:$f.nullish()}).passthrough(),Hl=zod.z.object({Schedule:Re.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),$l=zod.z.object({Grant:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Zf=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Jf.nullish(),Linking:Ql.nullish(),Availability:Hl.nullish(),Objectives:zod.z.record(zod.z.string(),Kl).nullish(),Reward:$l.nullish(),Presets:Ro.nullish()}).passthrough(),Yf=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Xf=zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Gate:Z.nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:Ro.nullish(),PointsToken:Jt.nullish()}).passthrough(),eg=zod.z.object({Milestones:zod.z.record(zod.z.string(),fi).nullish(),Linking:zod.z.record(zod.z.string(),Ql).nullish(),Availability:zod.z.record(zod.z.string(),Hl).nullish(),Reward:zod.z.record(zod.z.string(),$l).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Kl)).nullish()}).passthrough(),tg=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Gate:Z.nullish(),PointsToken:Jt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),Yf).nullish(),Phases:zod.z.record(zod.z.string(),Xf).nullish(),Presets:Ro.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rn=zod.z.object({Cycles:zod.z.record(zod.z.string(),tg).nullish(),Quests:zod.z.record(zod.z.string(),Zf).nullish(),Presets:eg.nullish()}).passthrough(),ft={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var ig={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},ng=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),rg={Never:"Never",OnRequest:"OnRequest",Always:"Always"},sg=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),og={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},ag=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),lg={GameLoop:"GameLoop"},ug={Raid:"Raid",Attack:"Attack"},cg=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(),pg=zod.z.object({Mode:ng.nullish(),Triggers:zod.z.array(ot).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),dg=zod.z.object({Grant:H.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),hg=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(),mg=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:hg.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),fg=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),Co=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:cg.nullish(),Completion:pg.nullish(),Effects:dg.nullish(),Script:mg.nullish(),Policy:fg.nullish()}).passthrough(),gg=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(),Jl=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:ot.nullish()}).passthrough(),Zl=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:sg.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Yl=zod.z.object({Grant:H.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),yg=zod.z.object({Availability:Q.nullish(),Policy:Q.nullish(),Reward:Q.nullish(),Steps:Q.nullish()}).passthrough(),Rg=zod.z.object({FlowID:zod.z.string().nullish(),Identity:gg.nullish(),Availability:Jl.nullish(),Policy:Zl.nullish(),Steps:zod.z.record(zod.z.string(),Co).nullish(),Reward:Yl.nullish(),Presets:yg.nullish()}).passthrough(),Cg=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(),Sg=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:Cg.nullish()}).passthrough(),xg=zod.z.object({Availability:zod.z.record(zod.z.string(),Jl).nullish(),Policy:zod.z.record(zod.z.string(),Zl).nullish(),Reward:zod.z.record(zod.z.string(),Yl).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Co)).nullish()}).passthrough(),Xl=zod.z.object({Flows:zod.z.record(zod.z.string(),Rg).nullish(),Settings:Sg.nullish(),Presets:xg.nullish()}).passthrough(),bg=zod.z.object({}).passthrough().transform(s=>s),eu=zod.z.object({FlowID:zod.z.string(),Status:ag,CurrentStepID:zod.z.string().nullish(),CurrentStep:Co.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(),sn=zod.z.object({State:bg.nullish(),Flows:zod.z.array(eu).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Lt=zod.z.object({Flow:eu.nullish()}).passthrough(),tu=zod.z.object({FlowID:zod.z.string().nullish(),Granted:M.nullish()}).passthrough(),iu=zod.z.array(we(Lt)),nu=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),at={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function on(s){return Array.isArray(s)?s.filter(e=>e!==null).map(on):s!==null&&typeof s=="object"?Object.fromEntries(Object.entries(s).filter(([,e])=>e!==null).map(([e,t])=>[e,on(t)])):s}var an=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var ln=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function ru(s){return s===429||s>=500&&s<=599}function un(s,e=Math.random){let t=Math.min(500*Math.pow(2,s-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Bt(s){return new Promise(e=>setTimeout(e,s))}var su=15e3;async function ou(s){try{let t=JSON.parse(await s.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(s.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function au(s,e=Math.random){return s+10+Math.min(250,s*.2)*e()}function lu(s,e=Math.random){let t=s<=1?1500:s===2?4e3:6e3;return t+t*.1*e()}var So=15,uu=1e3,cn=class{constructor(e=So,t=()=>Date.now(),i=Bt){this.perSecond=e;this.now=t;this.wait=i;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=uu;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(uu-(e-this.starts[0])+5);}}};var Dg=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function yi(s){if(!s)return null;let e=Dg.exec(s);if(!e)return null;let[,t,i,n]=e;if(!t||i===void 0||n===void 0)return null;let r=new Zt__default.default(i),o=new Zt__default.default(n),c=o.minus(Zt__default.default.max(r,0));return c.lte(0)?null:{currencyID:t,required:o.toNumber(),available:r.toNumber(),missing:c.toNumber(),missingAmount:c.toFixed()}}var Ig=12e3,Pg=new Set(["RelatedEntityID"]);function vg(s,e){if(e===null||typeof e!="object"||Array.isArray(e))return s;let t={};for(let[i,n]of Object.entries(e))Pg.has(i)||(t[i]=n);try{return `${s}|${JSON.stringify(t)}`}catch{return s}}var Tg=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(fo).nullish(),TutorialProgress:zod.z.array(nu).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),pn=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new ln;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 an(e.throttleMs),this.pacer=new cn(e.maxRequestsPerSecond??So),this.clientPlatform=e.clientPlatform??Rt.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,n={}){let r=n.throttleKey??vg(e,t);if(!this.throttler.tryAcquire(r))return u("throttled","Throttled");if(!this.inflight.add(r))return u("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,c=JSON.stringify(t),h=n.ticket??null,y=n.silent??!1,V=n.timeoutMs??Ig,oe=n.autoRetry??!0,be=!1,le=!1,ge=0;for(;;){let Pt;n.keepalive||await this.pacer.take();try{Pt=await this.doFetch(o,c,h,V,n.keepalive??!1);}catch{if(oe&&ge<3){ge++,await Bt(un(ge));continue}return this.connectionFailure("Internet Connection Error",y)}let Xe=Pt.status;if(Xe>=200&&Xe<300){let se=!le&&this.cryptoTopUpHandler!==null,Ae=await this.parseSuccess(Pt,i,y,e,se);if(!Ae.ok&&se){let de=yi(Ae.error);if(de){if(le=!0,await this.runTopUp(de))continue;y||this.emitter.emit("error:global",Ae.error);}}return Ae}if(Xe===401){if(!be&&this.sessionRefreshHandler){be=!0;let se=null;try{se=await this.sessionRefreshHandler();}catch{se=null;}if(se){h=se;continue}}return this.emitter.emit("auth:unauthorized",void 0),u("unauthorized","Unauthorized")}if(ru(Xe)){let se=Xe===429?await ou(Pt):null;if(se!==null&&se>su)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(se/1e3)} s`,y);if(oe&&ge<3){ge++,await Bt(se!==null?au(se):Xe===429?lu(ge):un(ge));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Xe})`,y)}let wi="";try{wi=await Pt.text();}catch{}if(Xe===409&&/operation in progress/i.test(wi)&&oe&&ge<3){ge++,await Bt(un(ge));continue}return this.handleWebError(wi,Xe,y)}}finally{this.inflight.remove(r),this.lowerBusy();}}async doFetch(e,t,i,n,r=false){let o=new AbortController,c=setTimeout(()=>{o.abort();},n);try{let h={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(h.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:h,signal:o.signal,...r?{keepalive:!0}:{}})}finally{clearTimeout(c);}}async parseSuccess(e,t,i,n,r=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",i)}let c;try{c=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",i)}let h=Tg.safeParse(c);if(!h.success)return this.globalError("Malformed response envelope",i);if(!h.data.Success){let le=h.data.Error??"Server returned Success=false",ge=r&&yi(le);return !i&&!ge&&this.emitter.emit("error:global",le),u("server",le)}let y=h.data.StateVersions;y&&Object.keys(y).length>0&&this.emitter.emit("user:stateVersions",{epoch:h.data.StateEpoch??null,versions:y});let V=h.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);let oe=h.data.TutorialProgress;oe&&oe.length>0&&this.emitter.emit("tutorial:systemProgress",oe);let be=t.safeParse(h.data.Data);if(!be.success){let le=t.safeParse(on(h.data.Data));le.success&&(be=le);}if(!be.success){let le=`Validation error (${n}): ${be.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",le),i||this.emitter.emit("error:global",le),u("validation",le)}return N(be.data)}handleWebError(e,t,i){let n=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),u("server","PLAY_ACCESS_REQUIRED");n=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{n=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",n),u("server",n)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),u("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),u("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function Ri(s){return (typeof s=="string"?s:s.toISOString()).slice(0,10)}function Ei(s){return `${Ri(s)}T00:00:00.000Z`}function cu(s){let e=new Date(s);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function pu(s,e){return new Date(s.getTime()+e*6e4).toISOString()}function Do(s,e,t,i){let n={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return n;s.InventoryV2??={};let r=s.InventoryV2,o=i.toISOString(),c=new Map,h=new Map,y=new Map,V=new Map,oe=new Map,be=new Map,le=new Map,ge=new Map,Pt=e.Grant?.PremiumTiers??[],Xe=Pt.length;for(let se=0;;se++){let Ae,de;if(se===0)Ae=e.Grant?.Standard?.Entries,de=false;else if(se-1<Xe)Ae=Pt[se-1]?.Resources?.Entries,de=false;else if(se===1+Xe)Ae=e.Consume?.Standard?.Entries,de=true;else break;if(Ae)for(let ue of Ae){if(ue.Type==null)continue;let he=Math.max(0,ue.Amount??0);if(!(he<=0))switch(ue.Type){case "VirtualCurrency":{if(!ue.CurrencyID)continue;let me=de?h:c;me.set(ue.CurrencyID,(me.get(ue.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!ue.CurrencyID)continue;let me=de?V:y;me.set(ue.CurrencyID,(me.get(ue.CurrencyID)??new Zt__default.default(0)).plus(he));break}case "Item":{if(!ue.ItemID)continue;let me=wg(t,ue.CatalogID,ue.ItemID),Ie=(me?me.IsStackable??true:true)?de?be:oe:de?ge:le;Ie.set(ue.ItemID,(Ie.get(ue.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(n.vcChanged=c.size>0||h.size>0,n.vcChanged){r.VirtualCurrencies??={};for(let se of new Set([...c.keys(),...h.keys()])){let Ae=c.get(se)??0,de=h.get(se)??0,ue=Ae-de,he=r.VirtualCurrencies[se];he?(he.Amount+=ue,he.UpdatedAt=o,he.Daily&&Ri(he.Daily.PeriodStartUtc)===Ri(i)?(he.Daily.Earned+=Ae,he.Daily.Spent+=de):he.Daily={PeriodStartUtc:Ei(i),Earned:Ae,Spent:de}):r.VirtualCurrencies[se]={Amount:ue,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:Ei(i),Earned:Ae,Spent:de}};}}if(n.ccChanged=y.size>0||V.size>0,n.ccChanged){r.CryptoCurrencies??={};for(let se of new Set([...y.keys(),...V.keys()])){let Ae=y.get(se)??new Zt__default.default(0),de=V.get(se)??new Zt__default.default(0),ue=Ae.minus(de),he=r.CryptoCurrencies[se];he?(he.Amount=new Zt__default.default(he.Amount).plus(ue).toString(),he.UpdatedAt=o):r.CryptoCurrencies[se]={Amount:ue.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(n.itemsChanged=oe.size>0||be.size>0||le.size>0||ge.size>0,n.itemsChanged){r.Items??={},r.UnstackableItems??={};let se=r.UnstackableItems,Ae=new Set([...oe.keys(),...be.keys(),...le.keys(),...ge.keys()]);for(let de of Ae){let ue=(oe.get(de)??0)-(be.get(de)??0),he=(le.get(de)??0)-(ge.get(de)??0),me=ue+he,st=r.Items[de];st?(ue!==0&&(st.StackableAmount+=ue),he!==0&&(st.UnstackableAmount+=he),me!==0&&(st.TotalAmount+=me)):r.Items[de]={StackableAmount:Math.max(0,ue),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,me)};}for(let[de,ue]of ge){if(ue<=0)continue;let he=Object.values(se).filter(me=>me.ItemID===de&&me.EquippedSlot==null&&(me.ExpiresAt==null||new Date(me.ExpiresAt)>i)).sort(Ag).slice(0,ue).map(me=>me.ItemInstanceID);for(let me of he)delete se[me];}for(let[de,ue]of le){let he=kg(t,de);for(let me=0;me<ue;me++){let st=G();se[st]={ItemInstanceID:st,ItemID:de,CatalogID:he,RemainingUses:1,AcquiredAt:o};}}}s.EventToken??={};let wi=s.EventToken;for(let se=0;;se++){let Ae,de;if(se===0)Ae=e.Grant?.Standard?.EventTokens,de=false;else if(se-1<Xe)Ae=Pt[se-1]?.Resources?.EventTokens,de=false;else if(se===1+Xe)Ae=e.Consume?.Standard?.EventTokens,de=true;else break;if(!(!Ae||Ae.length===0))for(let ue of Ae){let he=ue.Address;if(!he||he.Type==null)continue;let me=ue.Amount??0;if(me<=0)continue;let st=zg(wi,he.Type);if(!st)continue;let Ie=st[he.EntityID];Ie||(Ie={},st[he.EntityID]=Ie),Ie.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Ie.Daily??={Date:Ei(i),TotalEarned:0},Ie.Meta??={};let ki=ue.Source&&ue.Source.length>0?ue.Source:"CustomAction";de?(Ie.Balance.Current-=me,Ie.Balance.TotalSpent+=me):(Ie.Balance.Current+=me,Ie.Balance.TotalEarned+=me,Ri(Ie.Daily.Date)!==Ri(i)&&(Ie.Daily={Date:Ei(i),TotalEarned:0}),Ie.Daily.TotalEarned+=me,Ie.Daily.EarnedBySource??={},Ie.Daily.EarnedBySource[ki]=(Ie.Daily.EarnedBySource[ki]??0)+me,Ie.Daily.TriggersBySource??={},Ie.Daily.TriggersBySource[ki]=(Ie.Daily.TriggersBySource[ki]??0)+1,Ie.Daily.LastTriggerBySource??={},Ie.Daily.LastTriggerBySource[ki]=o,Ie.Meta.JoinedAtUtc||(Ie.Meta.JoinedAtUtc=o),Ie.Meta.LastEarnedAtUtc=o),n.tokensChanged=true;}}return n}function Ag(s,e){return s.AcquiredAt!==e.AcquiredAt?s.AcquiredAt<e.AcquiredAt?-1:1:s.ItemInstanceID===e.ItemInstanceID?0:s.ItemInstanceID<e.ItemInstanceID?-1:1}function wg(s,e,t){let i=s?.Catalogs;if(i){if(e){let n=i[e]?.Items?.[t];if(n)return n}for(let n of Object.values(i)){let r=n.Items?.[t];if(r)return r}}}function kg(s,e){let t=s?.Catalogs;if(t){for(let[i,n]of Object.entries(t))if(n.Items&&e in n.Items)return i}}function zg(s,e){switch(e){case "TimedEvent":return s.TimedEvent??={};case "Quest":return s.Quest??={};case "Leaderboard":return s.Leaderboard??={};case "CoopEvent":return s.CoopEvent??={};case "Season":return s.Season??={};default:return null}}function du(s,e,t){let i={drop:[],restore:{}};if(!t)return i;let n=t.ChangedInstances??{},r=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let h of Object.values(n))h?.ItemID&&o.add(h.ItemID);for(let h of r){let y=s[h]?.ItemID;y&&o.add(y);}if(o.size===0)return i;let c=h=>r.has(h)||h in n;if(e){for(let[h,y]of Object.entries(e))h in s||c(h)||y&&o.has(y.ItemID)&&i.drop.push(h);for(let[h,y]of Object.entries(s))h in e||c(h)||y&&o.has(y.ItemID)&&(i.restore[h]=y);}return i}function Io(s,e){return s===e||s.startsWith(`${e}:`)}var hn=class s{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){s.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];s.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){s.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let n=Do(this.currentState,e,t,i);this.emitResourceChanges(n,false);}applyResourcesWithDelta(e,t,i,n=new Date){if(!this.currentState)return;let r=this.currentState,o={...r.InventoryV2?.UnstackableItems??{}},c=Do(r,e,i,n),h=du(o,r.InventoryV2?.UnstackableItems,t),y=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],oe=h.drop.length>0||Object.keys(h.restore).length>0||y.length>0||V.length>0;if(oe){r.InventoryV2??={},r.InventoryV2.UnstackableItems??={};let be=r.InventoryV2.UnstackableItems;for(let le of h.drop)delete be[le];for(let[le,ge]of Object.entries(h.restore))be[le]=ge;for(let[le,ge]of y)be[le]=ge;for(let le of V)delete be[le];}this.emitResourceChanges(c,oe);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,n){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let r=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof Zt__default.default?t:new Zt__default.default(t),c=n===void 0?new Zt__default.default(0):n instanceof Zt__default.default?n:new Zt__default.default(n),h=i??new Date().toISOString(),y=r[e];y?(y.Amount=new Zt__default.default(y.Amount).plus(o).toString(),c.isZero()||(y.Frozen=new Zt__default.default(y.Frozen??0).plus(c).toString()),y.UpdatedAt=h):r[e]={Amount:o.toString(),Frozen:c.toString(),CreatedAt:h,UpdatedAt:h},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let n=this.currentState.Store.Purchases,r=n[e];r||(r={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},n[e]=r),r.TotalPurchases+=t,r.LastPurchasedAt=i,i>=r.DailyResetUtc?(r.DailyPurchases=t,r.DailyResetUtc=cu(i)):r.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let n=this.currentState.Lootbox??={};if(n.Pity??={},t){let r=new Date().toISOString();for(let o of t)o.RuleID&&(n.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:r});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchRewardWindowState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Windows??={},this.currentState.Reward.Windows[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let n=this.currentState.Quest;if(t){n.Cycles??={};let r=n.Cycles[t];if(!r)return;r.Quests??={};let o=r.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {n.PermanentQuests??={};let r=n.PermanentQuests[e]??={QuestID:e,Status:i};r.Status=i,i==="Claimed"&&(r.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let n=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,r=t[n]??={};r.Balance??={Current:0,TotalEarned:0,TotalSpent:0},r.Balance.Current=i.PointsCurrent??0,r.Balance.TotalEarned=i.PointsTotalEarned??0,r.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(r.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let n=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};n.Steps??={};let r=n.Steps[i.StepID]??={StepID:i.StepID};r.Progress=i.Progress,i.Completed&&(r.CompletedAtUtc??=new Date().toISOString(),n.CurrentStepID===i.StepID&&(n.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let n;if(!i.CycleID)t.PermanentQuests??={},n=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let r=t.Cycles[i.CycleID];if(!r)continue;r.Quests??={},n=r.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(n.Status=i.Status,i.ObjectiveID){n.Objectives??={};let r=n.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};r.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(r.Completed=true,r.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(n.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,n]of Object.entries(t))if(Io(i,e)&&n)return n;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,n){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[r,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((n?r!==n:!Io(r,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,n),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,n){let r=this.activeEventsCache?.ActiveEvents;if(r)for(let o of r)o.Type!==e||o.TimedEventID!==t||n&&o.TokenEntityID&&o.TokenEntityID!==n||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,n){if(!e)return;let r=this.ensureLeaderboardProgress(e);(r.ScoreCycleVersion??0)<n&&(r.ScoreEarnedThisCycle=0,r.ClaimedMilestoneIDs=[],r.BracketID=null),r.CurrentScore=t,r.ScoreEarnedThisCycle=(r.ScoreEarnedThisCycle??0)+i,r.ScoreCycleVersion=n,r.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let n=false;for(let r of Object.values(i))for(let o of Object.values(r.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,n=true);n&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,n=i[e];n||(n={CharacterID:e},i[e]=n),t(n),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let n=this.currentState?.Character?.Characters?.[e];n&&(n.Equipment??={},i===null?delete n.Equipment[t]:n.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[n,r]of Object.entries(e.ChangedInstances??{}))t[n]=r,i=true;for(let n of e.RemovedInstanceIDs??[])n in t&&(delete t[n],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let n=this.currentState.CoopEvent??={MyObjectIndex:-1};n.ActiveGroupID=e,n.ActiveCoopEventID=t,n.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let n of Object.keys(i)){let r=i[n];r&&r.BoostID===e.BoostID&&n!==e.InstanceID&&delete i[n];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,n,r){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,c={Value:i,UpdatedAt:new Date().toISOString(),Version:n,LastWriter:"Client",ExpiresAt:r??null};if(e==="Private")o.Private??={},o.Private[t]=c;else if(e==="Public")o.Public??={},o.Public[t]=c;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let n=i.BuildingStates.find(r=>r.SlotIndex===e);n||(n={SlotIndex:e},i.BuildingStates.push(n)),t(n),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let n=this.ensureBoard().Pending;n&&(e&&(n.RaidLayout=e),t>=0&&(n.OpenedIndices??=[],n.OpenedIndices.includes(t)||n.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let n of Object.values(e.CryptoBalances??{}))n?.CurrencyID&&this.patchCryptoCurrencyDelta(n.CurrencyID,n.AmountDelta,n.UpdatedAt,n.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let n=this.currentState.Blockchain??={},r=n.PendingWithdrawals??[];t.size>0&&(r=r.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!r.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(r=[...r,i]),n.PendingWithdrawals=r;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var mn=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,i]of Object.entries(e))this.sections.has(t)||this.sections.set(t,i);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let i=this.config?.[e];return i??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var fn=class{user;config;constructor(e){this.user=new hn(e),this.config=new mn;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Mg(s){return s}var Og=0,Eg=1500,Ug=3,yn=class{constructor(e,t,i=null,n="",r="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=n;this.loginMode=r;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return N(void 0);let i=Date.now(),n=[],r=[];for(let h of new Set(e)){let y=this.rules.get(h);if(y&&(t?.force||y.needsServer(i))){n.push(this.runRule(h,y));continue}(t?.force||!this.state.isStateFresh(h,t?.maxAgeMs))&&r.push(h);}let c=(await Promise.all([...n,r.length>0?this.queueSlice(r):Promise.resolve(N(void 0))])).find(h=>!h.ok);return c&&!c.ok?c:N(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let n=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,n),n}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},Og),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(n=>i=n);try{let n=this.state?await this.state.readStateSlice(e):N(void 0),r=n.ok?N(void 0):n;for(let o of t)o(r);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let n=gn(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let y=this.fresh(n,i?.maxAgeMs);if(y)return N(y.data);let V=this.loginFailures.get(n);if(V)return this.loginFailures.delete(n),V;let oe=this.inflight.get(n);if(oe)return oe}let r=this.generation.get(n)??0,o=Date.now(),h=t().then(y=>{if(!y.ok)return y;let V=Date.now();if((this.generation.get(n)??0)===r)return this.entries.set(n,{data:y.data,storedAt:V,expiresAt:Po(e,y.data,V)}),y;let oe=this.entries.get(n);if(oe&&oe.storedAt>=o)return y;let be=Po(e,y.data,V);return this.entries.set(n,{data:y.data,storedAt:V,expiresAt:Math.min(be??1/0,V+Eg)}),y}).finally(()=>{this.inflight.get(n)===h&&this.inflight.delete(n);});return this.inflight.set(n,h),h}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let n=t.Key?t.Key:void 0,r=gn(i.view,n);if(!t.Success){this.loginFailures.set(r,u("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(r),i.apply(o.data,n),this.put(i.view,o.data,n));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let n=e.login;this.loadUsed().then(()=>{let r=hu({Name:n,Key:t});this.used.get(r)?.n!==this.session&&(this.used.set(r,{Name:n,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>Ug||this.used.set(hu(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(n=>n&&typeof n.Name=="string"&&typeof n.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(gn(e,t))?.data}put(e,t,i){this.register(e);let n=gn(e,i);this.bump(n);let r=Date.now();this.entries.set(n,{data:t,storedAt:r,expiresAt:Po(e,t,r)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let n of [...this.entries.keys(),...this.inflight.keys()])(n===i||n.startsWith(`${i}|`))&&this.drop(n);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let n=Date.now();if(!(i.expiresAt!==null&&n>=i.expiresAt)&&!(t!==void 0&&n-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(n=>t.has(n))&&this.invalidate(i);}};function gn(s,e){return e===void 0?s.key:`${s.key}|${e}`}function hu(s){return s.Key?`${s.Name}|${s.Key}`:s.Name}function Po(s,e,t){let i=s.expiresAt?.(e)??null,n=s.ttlMs!==void 0?t+s.ttlMs:null;return i!==null&&n!==null?Math.min(i,n):i??n}var Rn=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 qg(e)?e:ze.None}saveAuthType(e){this.storage.setString(this.authTypeKey,e);}get savedEmail(){return this.storage.getString(this.emailKey)??""}get savedPassword(){return this.storage.getString(this.passwordKey)??""}saveEmailAndPassword(e,t){this.storage.setString(this.emailKey,e),this.storage.setString(this.passwordKey,t);}get savedRefreshToken(){return this.storage.getString(this.refreshTokenKey)??""}saveRefreshToken(e){e?this.storage.setString(this.refreshTokenKey,e):this.storage.remove(this.refreshTokenKey);}clear(){this.storage.remove(this.authTypeKey),this.storage.remove(this.emailKey),this.storage.remove(this.passwordKey),this.storage.remove(this.refreshTokenKey);}};function qg(s){return s!==null&&Object.values(ze).includes(s)}var At=["https://idosgames.com","https://www.idosgames.com"],Cn="https://platform.idosgames.com",mu=/^[a-z0-9]{8}-preview\.idos\.games$/;function vo(s){return s==="localhost"||s==="127.0.0.1"||s==="[::1]"||s.endsWith(".localhost")}function To(){if(typeof window>"u")return false;let s=window.location.hostname.toLowerCase();return mu.test(s)?true:vo(s)&&globalThis.__IDOS_PREVIEW__!=null}function Ui(s){if(typeof window<"u"&&mu.test(window.location.hostname.toLowerCase()))return s===Cn;if(At.includes(s))return true;if(typeof window>"u"||!vo(window.location.hostname))return false;try{return vo(new URL(s).hostname)}catch{return false}}var fu="IDOS_PLATFORM_WALLET_ACK",gu="PLATFORM_WALLET_UNAVAILABLE",Lg=5e3,Bg=18e4;function Gg(){if(Ui(Cn))return [Cn];let s=[...At],e=window.location.ancestorOrigins?.[0];return e&&!s.includes(e)&&Ui(e)&&s.push(e),s}function Fg(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function wt(s,e,t,i={}){let n={ok:false,error:gu,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(n);let r=window.parent;if(!r)return Promise.resolve(n);let o=Fg(),c=i.answerTimeoutMs??Bg;return new Promise(h=>{let y=false,V,oe=le=>{y||(y=true,window.removeEventListener("message",be),clearTimeout(V),h(le));},be=le=>{if(!Ui(le.origin))return;let ge=le.data;if(!(!ge||ge.requestId!==o)){if(ge.type===fu){clearTimeout(V),V=setTimeout(()=>oe({ok:false,error:"TIMEOUT",data:{}}),c);return}ge.type===e&&oe({ok:ge.ok===true,error:typeof ge.error=="string"?ge.error:void 0,data:ge});}};V=setTimeout(()=>oe(n),Lg),window.addEventListener("message",be);for(let le of Gg())try{r.postMessage({type:s,requestId:o,...t},le);}catch{}})}var Ao={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},_g=30*6e4,wo="idos:platformSignIn:declined:";function Vg(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(To())return false;let s=window.location.ancestorOrigins?.[0];if(s&&!At.includes(s))try{let e=new URL(s).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}function Ng(){if(typeof window>"u"||!To())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function ko(s){let e=await wt(Ao.request,Ao.response,{titleID:s,supports:["pgs"]},{answerTimeoutMs:_g}),t=e.data.ticket;if(e.ok&&typeof t=="string"&&t.length>0)return {ticket:t};let i=e.data.code;return e.ok&&typeof i=="string"&&i.length>0?{code:i}:{error:e.error??"no_code"}}function jg(s){try{window.localStorage.setItem(wo+s,"1");}catch{}}function Wg(s){try{window.localStorage.removeItem(wo+s);}catch{}}function Kg(s){try{return window.localStorage.getItem(wo+s)==="1"}catch{return false}}var Qg=8,Hg=100,$g=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,yu=["GameLoop"];function Jg(s){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(s)}var Sn=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=ze.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let n=this.authContext;if(!n)return a;let r=this.baseRequest();r.UserID=n.userID,r.ClientSessionTicket=n.clientSessionTicket,r.WalletAddress=e,r.NetworkID=t,i&&(r.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(r);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return a;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let n=await this.ctx.api.authentication.unlinkWallet(i);return n.ok&&n.data.PlayAccess&&this.setPlayAccess(n.data.PlayAccess),n}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.platform.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.platform.getDeviceID(),e.Device=this.ctx.platform.getDeviceModel(),e.Platform=this.ctx.platform.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(ze.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return u("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let n=await this.ctx.api.authentication.loginWithEmail(i);if(!n.ok)return n;this.applyAuthContext(n.data);let r=await this.fetchAndApplyClientState(ze.Email);return r.ok&&this.keepEmailCredentials(e,t),r}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.platform.getDeviceID(),i.Device=this.ctx.platform.getDeviceModel(),i.Platform=this.ctx.platform.getPlatform();let n=await this.ctx.api.authentication.registerWithEmail(i);return n.ok?(this.pendingRegistration={email:e,password:t},N({codeTtlMinutes:n.data.CodeTtlMinutes??0,resendCooldownSeconds:n.data.ResendCooldownSeconds??0})):n}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let n=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!n.ok)return n;this.applyAuthContext(n.data);let r=await this.fetchAndApplyClientState(ze.Email);return r.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,r}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?N(void 0):i}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let i=await this.ctx.api.authentication.loginWithGoogle(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Google)):i}async loginWithApple(e,t){if(!e?.trim())return u("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let n=await this.ctx.api.authentication.loginWithApple(i);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(ze.Apple)):n}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.WalletAddress=e,n.NetworkID=t,n.WalletSignature=i,n.Platform=this.ctx.platform.getPlatform(),n.Device=this.ctx.platform.getDeviceModel(),n.DeviceID=this.ctx.platform.getDeviceID();let r=await this.ctx.api.authentication.loginWithWallet(n);return r.ok?(this.applyAuthContext(r.data),this.fetchAndApplyClientState(ze.Wallet)):r}async loginWithSsoCode(e){if(!e)return u("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.platform.getDeviceID(),t.Device=this.ctx.platform.getDeviceModel(),t.Platform=this.ctx.platform.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.iDosGames)):i}async loginWithPlatformGameTicket(e){if(!e)return u("client","Platform game ticket is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.PlatformGameTicket=e;let i=await this.ctx.api.authentication.resolvePlatformGameSession(t);return i.ok?(this.applyAuthContext(i.data),this.platformGameSession=true,this.fetchAndApplyClientState(ze.iDosGames)):i}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.Email=e,n.ResetToken=t,n.Password=i,this.ctx.api.authentication.resetPassword(n)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==ze.None?e:ze.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let n=await this.ctx.api.authentication.refreshSession(i);return n.ok?(this.applyRefresh(n.data),"ok"):(Jg(n.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case ze.Email:return this.loginWithEmail(t,i);case ze.Device:case ze.None:return this.loginWithDeviceID();case ze.Telegram:return this.loginWithTelegram();default:return Promise.resolve(u("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;if(this.platformGameSession){this.refreshing=true;try{let t=await ko(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let n=await this.ctx.api.authentication.resolvePlatformGameSession(i);return n.ok?(this.applyAuthContext(n.data),this.platformGameSession=!0,n.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==ze.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===ze.None)return null;this.refreshing=true;try{return (await this.replay(e,this.sessionEmail||this.ctx.authStore.savedEmail,this.sessionPassword||this.ctx.authStore.savedPassword)).ok&&this.authContext?this.authContext.clientSessionTicket:null}catch{return null}finally{this.refreshing=false;}}logout(){this.authContext=null,this.playAccessStatus=null,this.forgetSession(),this.ctx.authStore.clear(),this.ctx.data.reset(),this.ctx.emitter.emit("auth:loggedOut",void 0);}static isValidEmail(e){return e.length>0&&$g.test(e)}static isValidPasswordLength(e){return e.length>=Qg&&e.length<=Hg}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=ze.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e){let t=await this.ctx.userService.getClientStateExcept(yu,yu);return t.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)),t}};var Zg="idos:cfg",Ci=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Ru(t)}`:e&&e.length>0?`f:${Ru(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${Zg}:${this.titleId}:${e}`}};function Ru(s){return [...s].map(e=>e.toLowerCase()).sort().join(",")}var Cu="idos:loc",Si=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(n)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[n,r]of Object.entries(t))typeof r=="number"&&r>0&&(i[n]=r);return i}catch{return {}}}async noteVersion(e,t){let i=await this.readVersions();i[e]!==t&&(i[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(i)));}keyOf(e){return `${Cu}:${this.titleId}:${e}`}versionsKey(){return `${Cu}:${this.titleId}:versions`}};var Yg="idos:sec",xn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let i=JSON.parse(t);return !i||typeof i!="object"||i.v!==e||!i.s||typeof i.s!="object"?{}:i.s}catch{return {}}}async write(e,t){try{let i={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(i));}catch{}}keyOf(){return `${Yg}:${this.titleId}`}};var Xg="idos:state",bn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,n){if(!(!e||!t))try{let r={e:t,v:i,s:n};await this.storage.set(this.keyOf(e),JSON.stringify(r));}catch{}}keyOf(e){return `${Xg}:${this.titleId}:${e}`}};function ey(s,e){if(!s)return;let t=new Set((e??[]).map(n=>n.trim().toLowerCase()));if(t.size===0)return s;let i={};for(let[n,r]of Object.entries(s))t.has(n.toLowerCase())||(i[n]=r);return i}function zo(s,e,t,i){let n={...s??{}};if(!e||!t||!i)return n;for(let[r,o]of Object.entries(t))i[r]===o&&r in e&&(n[r]=e[r]);return n}function ty(s){return {...s??{}}}function Mo(s){return typeof s.StateEpoch=="string"&&s.StateEpoch.length>0?s.StateEpoch:null}var Dn=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let n=this.confirmedAt[e];return n===void 0?false:t===void 0||i-n<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=ey(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let r=Object.keys(this.versions);this.reset(e),this.notify(r);}return}let i=Date.now(),n=[];for(let[r,o]of Object.entries(t)){let c=this.versions[r];c!==o&&(c!==void 0&&o===c+1?(this.versions[r]=o,this.confirmedAt[r]=i):(delete this.versions[r],delete this.confirmedAt[r]),n.push(r),this.dirty=true);}this.notify(n);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=ty(t);let n=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=n;this.dirty=true;let r=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&r.add(o);this.notify([...r]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),n=[];for(let[r,o]of Object.entries(t??{}))this.versions[r]!==o&&n.push(r),this.versions[r]=o,this.confirmedAt[r]=i;this.dirty=true,this.notify(n);}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 Su=u("server","Title configuration is unavailable (CDN and API both failed)."),In=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.platform.getFullURL(),RelatedEntityID:G()}:null}get configCache(){return this.cache??=new Ci(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new Si(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new xn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new Dn(new bn(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return a;let t=Ci.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let n=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let r=await this.ctx.api.user.getClientState(e);if(!r.ok)return r;let o=await this.resolveTitleConfig(r.data,t,i,{Fields:e.TitleFields});return o==null?Su:(this.finishStateHandshake(r.data,n),await this.restoreSections(r.data.TitleConfigVersion,o),await this.applyClientState(r.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(r.data.Views),await this.applyLocalization(r.data.Localization),await this.flushState(n),r)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let n=this.stateStore.versionsFor(t);if(n){e.KnownStateVersions=n;let r=this.stateStore.currentEpoch;r&&(e.KnownStateEpoch=r);}return {userId:i,cached:this.stateStore.cachedState,sent:n}}finishStateHandshake(e,t){let i=zo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let n=Mo(e);!n||!t.userId||this.stateStore.afterFullRead(n,e.StateVersions);}async resolveTitleConfig(e,t,i,n){let r=e.TitleConfigVersion;if(i&&r&&i.v===r)return i.c;if(e.TitleConfigUrl){let c=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(c!=null)return r&&await this.configCache.write(t,r,c),c}let o=await this.fetchConfigFromApi(n);return o!=null?(r&&await this.configCache.write(t,r,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},n=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return n.ok?n.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return a;i.ExcludeFields=e,i.ExcludeTitleFields=t;let n=Ci.scopeOf(null,t??[]),r=await this.configCache.read(n);r&&(i.KnownTitleConfigVersion=r.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let c=await this.ctx.api.user.getClientStateExcept(i);if(!c.ok)return c;let h=await this.resolveTitleConfig(c.data,n,r,{ExcludeFields:t??[]});return h==null?Su:(this.finishStateHandshake(c.data,o),await this.restoreSections(c.data.TitleConfigVersion,h),await this.applyClientState(c.data,h,e,t),this.ctx.cache.acceptLoginViews(c.data.Views),await this.applyLocalization(c.data.Localization),await this.flushState(o),c)}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let i=t,n={};for(let[r,o]of Object.entries(await this.sectionCache.read(e)))i[r]==null&&(n[r]=o);this.ctx.data.config.restoreSections(n),this.ctx.data.config.setSectionSink((r,o)=>{i[r]!=null||o==null||(n[r]=o,this.sectionCache.write(e,n));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let n=await this.localizationCache.read(t);if(i<=0)return n?.t??null;if(n&&n.v===i)return n.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let r=await this.fetchLocalizationFromApi(t,n?.v??0);return r??n?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let n=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!n.ok)return null;let r=n.data;if(r.NotModified)return null;let o=r.Entries??{},c=r.Version??0,h=r.Locale??e;return c>0&&await this.localizationCache.write(h,c,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):a}async getUserState(e){let t=this.baseRequest();if(!t)return a;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),n=await this.ctx.api.user.getUserState(t);if(!n.ok)return n;let r=zo(n.data.User,i.cached,i.sent,n.data.StateVersions);n.data.User=r;let o=i.sent??{},c=Object.entries(n.data.StateVersions??{}).filter(([y,V])=>o[y]!==V||this.ctx.data.user.state?.[y]===void 0).map(([y])=>y);this.ctx.data.user.applyUserStateContainers(r,c);let h=Mo(n.data);return h&&(this.stateStore.afterSliceRead(h,n.data.StateVersions),await this.flushState(i)),n}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let n=this.baseRequest();if(!n)return a;n.UsageTime=e,n.IsNewSession=t,n.SessionDurationSeconds=i;let r=await this.ctx.api.user.addUsageTime(n);return r.ok&&this.ctx.emitter.emit("user:usageTimeAdded",r.data),r}async deleteUserAccount(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return a;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,n){let r=i?.includes("GameLoop")===true,o=n?.includes("GameLoop")===true,c=r?this.ctx.data.user.state?.GameLoop:void 0,h=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let y=this.ctx.data.user.state;r&&y&&y.GameLoop==null&&(y.GameLoop=c);let V=this.ctx.data.config.titlePublicConfiguration;o&&V&&V.GameLoop==null&&(V.GameLoop=h),this.ctx.emitter.emit("user:clientStateReceived",e);}};var vn=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return u("client","SpendID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${G()}`},n=await this.ctx.api.currency.spend(i);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",n.data)),n}async convert(e,t,i,n,r,o){if(!t)return u("client","SourceID is required.");if(!n)return u("client","TargetID is required.");if(r<=0)return u("client","Amount must be positive.");if(e===i&&t===n)return u("client","Source and target must differ.");if(e===ht.Crypto||i===ht.Crypto)return u("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return a;let c={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:String(Math.trunc(r)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${n}_${G()}`},h=await this.ctx.api.currency.convert(c);if(h.ok){let y=h.data,V={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:y.SourceID,Amount:y.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:y.TargetID,Amount:y.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",y);}return h}async cryptoConvert(e,t,i,n,r,o){let c=r instanceof Zt__default.default?r:new Zt__default.default(r);if(!t)return u("client","SourceID is required.");if(!n)return u("client","TargetID is required.");if(c.lte(0))return u("client","SourceAmount must be a positive decimal.");if(e===i&&t===n)return u("client","Source and target must differ.");if(e===ht.Virtual&&i===ht.Virtual)return u("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ht.Virtual&&!c.isInteger())return u("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:c.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${n}_${G()}`},y=await this.ctx.api.currency.cryptoConvert(h);if(y.ok){let V=y.data,oe=[],be=[];if(V.SourceType===ht.Virtual&&oe.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===ht.Virtual&&be.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),oe.length>0||be.length>0){let le={Consume:oe.length>0?{Standard:{Entries:oe}}:null,Grant:be.length>0?{Standard:{Entries:be}}:null};this.ctx.data.user.applyResourceOperation(le,this.ctx.data.config.itemDefinitions);}V.SourceType===ht.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new Zt__default.default(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===ht.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new Zt__default.default(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return y}};var Tn=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i,n){let r=e.trim();if(!r)return u("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:r,SelectedOptionID:i,CreditsConfirmationID:n,RelatedEntityID:`upgrade_item_${r}_${G()}`};t&&t.length>0&&(o.FodderInstanceIDs=[...t]);let c=await this.ctx.api.item.upgradeLevel(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(c.data.ItemInstanceID??r,c.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",c.data)),c}async upgradeLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let n of i.data)n.Success&&n.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(n.Data.ItemInstanceID,n.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var An=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:vt.nullish(),AllowedPlatforms:zod.z.array(Yi).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ce=zod.z.record(zod.z.string(),An),iy=zod.z.object({Store:Xi,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var qi={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},fe=zod.z.object({ConfirmationID:zod.z.string(),Url:zod.z.string(),Status:zod.z.string(),PriceCredits:zod.z.number(),ExpiresAt:p}).passthrough(),xu=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),ny={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"},Oo=zod.z.object({ServerTimeUtc:p,OfferID:zod.z.string(),Count:zod.z.number(),Resources:M.nullish(),Inventory:K.nullish(),CreditsConfirmation:fe.nullish()}),bu=zod.z.array(we(Oo)),ry=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:p,LastPurchasedAt:p}),sy=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:p}),Du=zod.z.object({Purchases:zod.z.record(zod.z.string(),ry).nullish(),Rotations:zod.z.record(zod.z.string(),sy).nullish()}).passthrough().transform(s=>s),kt=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(),wn=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),oy={Fixed:"Fixed",Title:"Title",Player:"Player"},ay=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:Z.nullish()}).passthrough(),Iu=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(ay).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),ly=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Rotation:Q.nullish()}).passthrough(),uy=zod.z.object({SlotID:zod.z.string().nullish(),Identity:kt.nullish(),Availability:wn.nullish(),Rotation:Iu.nullish(),Presets:ly.nullish()}).passthrough(),cy=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish()}).passthrough(),py=zod.z.object({SectionID:zod.z.string().nullish(),Identity:kt.nullish(),Availability:wn.nullish(),Slots:zod.z.record(zod.z.string(),uy).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:cy.nullish()}).passthrough(),Pu=zod.z.object({Sections:zod.z.record(zod.z.string(),py).nullish()}).passthrough(),dy=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Layout:Q.nullish()}).passthrough(),hy=zod.z.object({StoreID:zod.z.string().nullish(),Identity:kt.nullish(),Availability:wn.nullish(),Layout:Pu.nullish(),Presets:dy.nullish()}).passthrough(),vu=zod.z.object({Options:ce.nullish(),CompareAt:zod.z.record(zod.z.string(),vt).nullish()}).passthrough(),Tu=zod.z.object({Grant:H.nullish()}).passthrough(),Au=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),my=zod.z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish(),Availability:Q.nullish()}).passthrough(),fy=zod.z.object({OfferID:zod.z.string().nullish(),Identity:kt.nullish(),Pricing:vu.nullish(),Reward:Tu.nullish(),Availability:Au.nullish(),Presets:my.nullish()}).passthrough(),gy=zod.z.object({Identity:zod.z.record(zod.z.string(),kt).nullish(),Availability:zod.z.record(zod.z.string(),wn).nullish(),Layout:zod.z.record(zod.z.string(),Pu).nullish(),Rotation:zod.z.record(zod.z.string(),Iu).nullish(),Pricing:zod.z.record(zod.z.string(),vu).nullish(),Reward:zod.z.record(zod.z.string(),Tu).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Au).nullish()}).passthrough(),kn=zod.z.object({Stores:zod.z.record(zod.z.string(),hy).nullish(),StoreOffers:zod.z.record(zod.z.string(),fy).nullish(),Presets:gy.nullish()}).passthrough(),yy=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:p.nullish()}).passthrough(),Ry=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:vt.nullish(),CompareAtCost:vt.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(),Cy=zod.z.object({OfferID:zod.z.string(),Identity:kt.nullish(),PriceOptions:zod.z.array(Ry).nullish(),Rewards:H.nullish(),State:yy.nullish()}).passthrough(),Sy=zod.z.object({SlotID:zod.z.string(),Identity:kt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:p.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:Cy.nullish()}).passthrough(),xy=zod.z.object({SectionID:zod.z.string(),Identity:kt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(Sy).nullish()}).passthrough(),by=zod.z.object({StoreID:zod.z.string(),Identity:kt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:p.nullish(),Sections:zod.z.array(xy).nullish()}).passthrough(),zn=zod.z.object({ServerTimeUtc:p,Stores:zod.z.array(by).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),zt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},Dy="OFFER_NOT_IN_ROTATION";var wu="Store",ku={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:s=>{let e=null;for(let t of s.Stores??[])for(let i of t.Sections??[])for(let n of i.Slots??[]){let r=Date.parse(n.RefreshesAtUtc??"");!Number.isNaN(r)&&(e===null||r<e)&&(e=r);}return e}},Mn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ku,{schema:zn,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return u("client","OfferID is required.");if(t<1)return u("client","Count must be at least 1.");let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${n.userID}_${G()}`},o=await this.ctx.api.store.purchase(r);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;this.ctx.data.user.patchStorePurchase(e,t,c.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",c);}return o}async purchaseWithCredits(e,t=1,i={}){return await this.ctx.credits.pay(n=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:n}),{onConfirmation:i.onConfirmation,signal:i.signal,pollMs:i.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):a}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):a}async purchaseBatch(e){if(!e||e.length===0)return u("client","purchases is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||!r.Data.OfferID||(this.ctx.data.user.patchStorePurchase(r.Data.OfferID,r.Data.Count,r.Data.ServerTimeUtc),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(wu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.store.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(wu,n.data),this.ctx.emitter.emit("store:definitionsLoaded",n.data)),n}getStorefront(e){return this.ctx.cache.read(ku,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let n of i.Slots??[]){let r=n.RefreshesAtUtc;r&&(e===null||Date.parse(r)<Date.parse(e))&&(e=r);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var Eo={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},Iy=15*6e4,Py=/^[a-z0-9]{8}-preview\.idos\.games$/;function Yt(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !Py.test(window.location.hostname.toLowerCase())}async function Uo(s){let e=await wt(Eo.request,Eo.response,{titleID:s.titleID,userID:s.userID,currencyID:s.currencyID,amount:s.amount},{answerTimeoutMs:Iy});return e.ok?{ok:true}:{ok:false,error:e.error}}var qo={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},vy=10*6e4;function Ty(){let s=globalThis.navigator?.userAgent??"";if(!/\biDosGamesApp\/(?:player|studio)\//.test(s))return true;let e=/\biDosGamesPlatform\/(ios|android)\b/.exec(s);return (e?e[1]:/\bAndroid\b/.test(s)?"android":"ios")!=="ios"}function Lo(){return Yt()}async function Bo(s){let e=await wt(qo.request,qo.response,{titleID:s.titleID,confirmationID:s.confirmationID},{answerTimeoutMs:vy});return e.ok?{ok:true}:{ok:false,error:e.error}}var On=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let i=await e(void 0);if(!i.ok||!i.data.CreditsConfirmation)return i;let n=i.data.CreditsConfirmation,r=()=>e(n.ConfirmationID);if(Lo()){let h=await Bo({titleID:this.ctx.settings.titleID,confirmationID:n.ConfirmationID});if(h.ok)return await r();if(h.error==="DECLINED")return u("server","CREDITS_CONFIRMATION_DECLINED");if(h.error==="NOT_ENOUGH_CREDITS")return u("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(n);let o=Math.max(1e3,t.pollMs??2500),c=Date.parse(n.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return u("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>c)return u("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(V=>setTimeout(V,o));let h=await this.ctx.store.getCreditsConfirmation(n.ConfirmationID);if(!h.ok)continue;let y=h.data.Status;if(y!==qi.Pending)return y===qi.Declined?u("server","CREDITS_CONFIRMATION_DECLINED"):y===qi.Expired?u("server","CREDITS_CONFIRMATION_EXPIRED"):await r()}}};var En=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?N(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return u("client","Receipt is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},r=await this.ctx.api.purchase.validatePurchase(n);return r.ok&&this.applyValidation(r.data),r}async buyWithTelegramStars(e,t){if(!e)return u("client","productID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},n=await this.ctx.api.purchase.createTelegramInvoice(i);return n.ok&&t?.open!==false&&this.ctx.platform.openInvoice(n.data.InvoiceLink),n}async validatePurchasesBatch(e){if(!e||e.length===0)return u("client","receipts is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let n of i.data.Items)n.Success&&n.Data&&this.applyValidation(n.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var zu=3,Ay=700,Un=class{constructor(e){this.ctx=e;Yt()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return yi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await Uo({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return i.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:i.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=zu;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===zu)break;await Bt(Ay);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t)if(i?.Type===Zi.Purchase&&i.ProductID)return i.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t){if(i?.Type!==Zi.CryptoCurrency||!i.CurrencyID)continue;let n=Number(i.Amount??0);if(!(n>0))continue;let r=this.cryptoBalance(i.CurrencyID);return r>=n?null:{currencyID:i.CurrencyID,required:n,available:r,missing:n-r}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var Mu="Lootbox",qn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Mu,e);if(t){let r={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.lootbox.getDefinitions(i);if(n.ok){let r=n.data.LootboxDefinitions;r&&(this.ctx.data.config.patchSection(Mu,r),this.ctx.emitter.emit("lootbox:definitionsLoaded",r));}return n}async open(e,t,i,n,r){if(!e)return u("client","LootboxID is required.");if(t<1)return u("client","Count must be at least 1.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:n,CreditsConfirmationID:r,RelatedEntityID:`lootbox_${e}_${i??"default"}_${G()}`},c=await this.ctx.api.lootbox.open(o);if(c.ok&&!c.data.CreditsConfirmation){let h=c.data;h.TriggeredPity&&h.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,h.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(h.Resources,h.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",h);}return c}};var Go="Reward";function Ln(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var Bn=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(Go)?.Comebacks??{}).some(i=>i?.TrackPresenceOnRead===true),refresh:async()=>{let i=await this.getUserRewardsState();return i.ok&&(t=true),i}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(Go,e);if(t){let r={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.reward.getRewardDefinitions(i);if(n.ok){let r=n.data.RewardDefinitions;r&&(this.ctx.data.config.patchSection(Go,r),this.ctx.emitter.emit("reward:definitionsLoaded",r));}return n}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${G()}`},n=await this.ctx.api.reward.claimDailyReward(i);if(n.ok){let r=n.data;this.ctx.data.user.patchDailyCalendarState(r.CalendarID,r.DailyState),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",r);}return n}async collectIdleAccrual(e){if(!Ln(e))return u("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${G()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let n=i.data;this.ctx.data.user.patchIdleAccrualState(n.AccrualID,n.IdleState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",n);}return i}async claimComebackReward(e){if(!Ln(e))return u("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchComebackState(n.ComebackID,n.ComebackState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",n);}return i}async claimReward(e){if(!Ln(e))return u("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchClaimRewardState(n.ClaimID,n.ClaimState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",n);}return i}async claimRewardWindow(e,t,i={}){if(!Ln(e))return u("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return u("client","Amount must be a positive number.");let n=i.boost??"None";if(n==="Ad"&&!i.adRequestID)return u("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:n,...i.adRequestID?{AdRequestID:i.adRequestID}:{},RelatedEntityID:i.roundID??`reward_window_${e}_${G()}`},o=await this.ctx.api.reward.claimRewardWindow(r);if(o.ok){let c=o.data;this.ctx.data.user.patchRewardWindowState(c.WindowID,c.WindowState),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:windowClaimed",c);}return o}};var Gn="Tutorial",Ou={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"]},Fn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ou,{schema:sn,apply:i=>this.applyUserTutorialState(i)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(Gn)?.Flows??{}).length>0,refresh:async()=>{let i=await this.getUserTutorialState();return i.ok&&(t=true),i}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(Gn,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.tutorial.getTutorialDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Gn,n.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",n.data)),n}getUserTutorialState(e=true,t){return this.ctx.cache.read(Ou,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${G()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return u("client","FlowID is required.");if(!t||t.length===0)return u("client","stepIDs is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${G()}`},r=await this.ctx.api.tutorial.completeStepsBatch(n);return r.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",r.data)),r}async skipStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.skipStep(i))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${G()}`},n=await this.ctx.api.tutorial.claimFlowReward(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",n.data)),n}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let n=e?.trim();if(!n)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),FlowID:n},o=await t(r);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,n){let r=e?.trim(),o=t?.trim();if(!r)return u("client","FlowID is required.");if(!o)return u("client","StepID is required.");if(!this.ctx.auth.context)return a;let c={...this.ctx.buildAuthedBaseRequest(),FlowID:r,StepID:o};n?.relatedEntityID&&(c.RelatedEntityID=n.relatedEntityID);let h=this.ctx.data.user.state?.Tutorial?.Flows?.[r]?.RewardClaimed===true,y=await i(c);return y.ok&&(this.applyFlowView(y.data),this.mayHavePaid(r,o,h,y.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",y.data)),y}mayHavePaid(e,t,i,n){return !i&&n.Flow?.RewardClaimed===true?true:n.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Gn)?.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 _n=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return a;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return u("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return u("client","campaignID is required.");if(!t)return u("client","walletAddress is required.");let n=this.ctx.authedRequest();if(!n)return a;n.CampaignID=e,n.WalletAddress=t,i&&(n.Amount=i);let r=await this.ctx.api.communityMarketing.withdrawCryptoReward(n);return r.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",r.data),r}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var qe=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 wy={Global:"Global",Announcement:"Announcement",Group:"Group"},Uu=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),ky={None:"None",Language:"Language",Region:"Region"},zy=zod.z.enum(["None","Language","Region"]).catch("None"),My={Anyone:"Anyone",Friends:"Friends"},Oy=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),Ey={Reject:"Reject",Mask:"Mask"},Uy=zod.z.enum(["Reject","Mask"]).catch("Reject"),qy={Player:"Player",Publisher:"Publisher",System:"System"},Ly=zod.z.enum(["Player","Publisher","System"]).catch("Player"),By={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Gy=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),qu=zod.z.object({Gate:Z.nullish(),Schedule:Re.nullish()}).passthrough(),Lu=zod.z.object({Gate:Z.nullish(),Limits:Se.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Bu=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),Fy=zod.z.object({Availability:Q.nullish(),Write:Q.nullish(),Retention:Q.nullish()}).passthrough(),_y=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:Gy.nullish(),Type:Uu.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:zy.nullish(),Capacity:zod.z.number().nullish(),Availability:qu.nullish(),Write:Lu.nullish(),Retention:Bu.nullish(),Presets:Fy.nullish()}).passthrough(),Vy=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:Oy.nullish(),Limits:Se.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),Ny=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:Uy.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Se.nullish()}).passthrough(),jy=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),Wy=zod.z.object({Availability:zod.z.record(zod.z.string(),qu).nullish(),Write:zod.z.record(zod.z.string(),Lu).nullish(),Retention:zod.z.record(zod.z.string(),Bu).nullish()}).passthrough(),Gu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),_y).nullish(),Direct:Vy.nullish(),Moderation:Ny.nullish(),Polling:jy.nullish(),Presets:Wy.nullish()}).passthrough(),Ky=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),Eu=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(),Ky).nullish(),Limits:zod.z.record(zod.z.string(),Eu).nullish(),ReportLimits:Eu.nullish()}).passthrough();var Fo=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),Vn=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:qe.nullish(),AuthorType:Ly.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),Qy=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:Uu.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(),Nn=zod.z.object({Channels:zod.z.array(Qy).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),Hy=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Vn).nullish(),NextCursor:Fo.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Fu=zod.z.object({Rooms:zod.z.array(Hy).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),_u=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Vn).nullish(),NextBefore:Fo.nullish()}).passthrough(),Vu=zod.z.object({Message:Vn.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),Nu=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:qe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),$y=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:qe.nullish(),LastMessage:Vn.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),ju=zod.z.object({Conversations:zod.z.array($y).nullish()}).passthrough(),xi=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:Fo.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),Wu=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),$e={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 Ku="Chat",Qu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},jn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Qu,{schema:Nn,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(Ku,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.chat.getChatDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Ku,n.data),this.ctx.emitter.emit("chat:definitionsLoaded",n.data)),n}getChannels(e,t){return this.ctx.cache.read(Qu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let n of i.data.Rooms??[])n.NextCursor&&n.RoomID&&this.cursors.set(n.RoomID,n.NextCursor),n.Messages&&n.Messages.length>0&&this.ctx.emitter.emit("chat:messages",n);return i}async getHistory(e,t,i){let n=this.ctx.authedRequest();return n?(n.RoomID=e,t&&(n.Before=t),i&&(n.Limit=i),this.ctx.api.chat.getHistory(n)):a}async sendMessage(e,t,i){let n=this.ctx.authedRequest();if(!n)return a;n.ChannelID=e,n.Text=t,i&&(n.Locale=i);let r=await this.ctx.api.chat.sendMessage(n);return r.ok&&this.ctx.emitter.emit("chat:sent",r.data),r}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Text=t;let n=await this.ctx.api.chat.sendMessage(i);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):a}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):a}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let n=await this.ctx.api.chat.markRead(i);return n.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),n}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):a}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):a}async reportMessage(e,t,i,n){let r=this.ctx.authedRequest();return r?(r.RoomID=e,r.MessageID=t,r.Reason=i,n&&(r.Comment=n),this.ctx.api.chat.reportMessage(r)):a}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):a}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):a}resetCursors(){this.cursors.clear();}};var Jy={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},Zy=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),Yy={Player:"player",Title:"title",Creator:"creator"},bi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Hu=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),Xy=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),_o=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:Zy.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(Xy).nullish()}).passthrough(),$u=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(_o).nullish()}).passthrough(),Mt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var eR="IDOS_PLATFORM_PUSH_REQUEST",tR="IDOS_PLATFORM_PUSH_RESPONSE",iR=12e4;function Ju(s){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let n=false,r=h=>{n||(n=true,window.removeEventListener("message",o),clearTimeout(c),i(h));},o=h=>{let y=h?.data;!y||y.type!==tR||y.requestId!==t||At.includes(h.origin)&&r(y.ok===true);},c=setTimeout(()=>r(false),iR);window.addEventListener("message",o);for(let h of At)try{e.postMessage({type:eR,requestId:t,titleID:s},h);}catch{}})}var Wn=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),n=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=n,i.ok&&this.ctx.emitter.emit("push:configLoaded",n),n}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return Mt.Unsupported;if(this.isEmbedded())return Mt.Embedded;if(!this.isSupported())return Mt.Unsupported;let t=Notification.permission;return t==="denied"?Mt.Blocked:t!=="granted"?Mt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?Mt.Subscribed:Mt.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return u("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Ju(this.ctx.settings.titleID)?N({Where:"portal",Subscription:null}):u("client","The portal did not complete the subscription.");if(!this.isSupported())return u("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return u("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let n=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await n.pushManager.getSubscription()??await n.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:nR(t.PublicKey)}),c=this.ctx.authedRequest();if(!c)return a;let h=o.toJSON();c.PushEndpoint=h.endpoint,c.PushP256dh=h.keys?.p256dh,c.PushAuth=h.keys?.auth,c.PushTransport="WebPush",c.PushLocale=e.locale??navigator.language,c.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let y=await this.ctx.api.push.subscribePush(c);return y.ok?(this.ctx.emitter.emit("push:subscribed",y.data),N({Where:"game",Subscription:y.data})):y}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return a;if(this.isSupported()){let n=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();n&&(e.PushEndpoint=n.endpoint,await n.unsubscribe());}if(!e.PushEndpoint)return u("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):a}async unsubscribeByHash(e){if(!e)return u("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return a;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function nR(s){let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),n=new Uint8Array(i);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return i}var Kn=Object.freeze({}),Qn=class{constructor(e){this.ctx=e;}ctx;table={...Kn};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new Si(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),n=this.lookup(i)??this.lookup(e);return n===void 0?this.onMissing(e):t?rR(n,t):n}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Kn},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return a;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:n,table:r,fallbackLocale:o}=i.data,c=null;if(o){let h=await this.loadTableFromApi(o);h.ok&&(c=h.data.table);}return this.table=r,this.fallbackTable=c,this.currentFallbackLocale=o,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:o,entryCount:Object.keys(r).length}),{ok:true,data:n}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):a}reset(){this.table={...Kn},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:G()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return a;t.Locale=e;let i=await this.cache.read(Zu(e));i&&(t.KnownVersion=i.v);let n=await this.ctx.api.localization.getLocalizationTable(t);if(!n.ok)return n;let r=n.data,o=r.Locale??Zu(e),c=r.Version??0;if(r.NotModified){let y=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:y?.t??{...Kn},fallbackLocale:r.FallbackLocale??null}}}let h=r.Entries??{};return c>0&&await this.cache.write(o,c,h),{ok:true,data:{locale:o,table:h,fallbackLocale:r.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let n=this.pluralCategory(i),r=`${e}.${n}`;if(this.lookup(r)!==void 0)return r;let o=`${e}.other`;return this.lookup(o)!==void 0?o:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function rR(s,e){return s.replace(/\{(\w+)\}/g,(t,i)=>{let n=e[i];return n===void 0?t:String(n)})}function Zu(s){return s.trim().replace(/_/g,"-").toLowerCase()}var Vo="Quest",sR={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:s=>{let e=Date.now(),t=null,i=[...Object.values(s.PointsTracks??{}).map(n=>n?.CycleEndUtc),...Object.values(s.State?.Cycles??{}).map(n=>n?.CycleEndUtc)];for(let n of i){let r=Date.parse(n??"");!Number.isNaN(r)&&r>e&&(t===null||r<t)&&(t=r);}return t}},Hn=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let n=e.cache.configSection(Vo)?.Cycles;if(!n)return false;let r=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(n)){let c=Date.parse(r[o]?.CycleEndUtc??"");if(Number.isNaN(c)){if(t===0)return true}else if(c<=i&&t<c)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true,{forceRefresh:true});return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(Vo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.quest.getQuestDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Vo,n.data),this.ctx.emitter.emit("quest:definitionsLoaded",n.data)),n}getUserQuestState(e=true,t){return this.ctx.cache.read(sR,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let n=i.data.State??{};this.ctx.data.user.applyQuest(n),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",n);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let i=e.trim();if(!i)return u("client","QuestID is required.");if(!this.ctx.auth.context)return a;let n=t&&t.trim().length>0?t.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:n,RelatedEntityID:`quest_claim_${n??""}_${i}_${G()}`},o=await this.ctx.api.quest.claimQuestReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchQuestStatus(c.QuestID,c.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",c);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return u("client","quests is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||(this.ctx.data.user.patchQuestStatus(r.Data.QuestID,r.Data.CycleID,"Claimed"),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return u("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:n,RelatedEntityID:`milestone_claim_${i}_${n}_${G()}`},o=await this.ctx.api.quest.claimMilestoneReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchMilestoneClaimed(c.CycleID,c.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",c);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||(this.ctx.data.user.patchMilestoneClaimed(r.Data.CycleID,r.Data.MilestoneID),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return u("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:n,RelatedEntityID:`group_completion_${i}_${n}_${G()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchGroupCompletionClaimed(c.CycleID,c.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",c);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return u("client","MetricID is required.");if(t<0)return u("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},r=await this.ctx.api.quest.addQuestProgress(n);return r.ok&&(this.ctx.data.user.patchQuestProgressUpdates(r.data.Updates),this.ctx.emitter.emit("quest:progressAdded",r.data)),r}};var Yu=zod.z.object({}).passthrough().transform(s=>s);var oR=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),aR=zod.z.object({Schedule:zod.z.array(oR).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),lR=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:p.nullish(),NextBonusStartUtc:p.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),uR=zod.z.object({Milestones:Q.nullish()}).passthrough(),No=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:Jt.nullish(),TokenSources:zod.z.array(ot).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:uR.nullish(),BonusWindow:aR.nullish()}).passthrough(),cR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:No.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),pR=zod.z.object({TimedEventID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:Re.nullish(),Content:No.nullish(),Events:zod.z.array(cR).nullish(),Gate:Z.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),dR=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),hR=zod.z.object({Milestones:zod.z.record(zod.z.string(),fi).nullish()}).passthrough(),$n=zod.z.object({Definitions:zod.z.record(zod.z.string(),pR).nullish(),Settings:dR.nullish(),Presets:hR.nullish()}).passthrough(),mR=zod.z.object({Type:Oi,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:No.nullish(),Progress:Yu.nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:_e.nullish(),BonusWindow:lR.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),Jn=zod.z.object({ActiveEvents:zod.z.array(mR).nullish()}).passthrough(),Xu=zod.z.object({Tokens:zod.z.record(zod.z.string(),Yu).nullish()}),jo=zod.z.object({Type:Oi.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Wo=zod.z.object({Type:Oi.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:M.nullish(),Inventory:K.nullish()}),fR=zod.z.object({Type:Oi.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Ko=zod.z.array(we(Wo)),ec=zod.z.array(we(jo)),tc=zod.z.array(we(fR)),ut={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var ic="TimedEvent",nc={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:s=>{let e=null;for(let t of s.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Zn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(nc,{schema:Jn,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(nc,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(ic,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.timedEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ic,n.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",n.data)),n}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,n,r,o,c=1){if(!t)return u("client","LteID is required.");if(!i)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:n,AmountOverride:r,SourceParams:o,RollMultiplier:c},y=await this.ctx.api.timedEvent.grantTokens(h);return y.ok&&(this.ctx.data.user.applyResourceOperation(y.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",y.data)),y}async spendTokens(e,t,i){if(!t)return u("client","LteID is required.");if(i<=0)return u("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},r=await this.ctx.api.timedEvent.spendTokens(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",r.data)),r}async claimMilestone(e,t,i){if(!t||!i)return u("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},r=await this.ctx.api.timedEvent.claimMilestone(n);if(r.ok){let o=r.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return r}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return a;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return u("client","spends is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(r.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return u("client","grants is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(r.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let n=i.Data;n.Type&&n.LteID&&n.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(n.Type,n.LteID,n.MilestoneID,n.TokenEntityID),!t&&n.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(n.Rewards,n.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var gR=zod.z.object({UserID:zod.z.string(),Score:W.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:p.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:qe.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),Li=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:W.nullish(),CycleEndUtc:p.nullish(),TopUsers:zod.z.array(gR).nullish(),BracketID:zod.z.string().nullish()}),yR=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:p.nullish(),ClaimDeadlineUtc:p.nullish(),MilestoneTokensEarned:W.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Yn=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:W.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:W.nullish(),MilestoneTokensEarned:W.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(yR).nullish()}),Xn=zod.z.object({LeaderboardID:zod.z.string(),NewScore:W,CycleVersion:zod.z.number()}),er=zod.z.object({ServerTimeUtc:p,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),tr=zod.z.object({ServerTimeUtc:p,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:M.nullish(),Inventory:K.nullish()}),rc=zod.z.array(we(Li)),ir=zod.z.array(we(Yn)),sc=zod.z.array(we(er)),oc=zod.z.array(we(tr)),ac=zod.z.array(we(Xn)),RR=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:we(er).nullish(),Milestones:zod.z.array(we(tr)).nullish()}),lc=zod.z.array(RR),CR=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:we(Li).nullish(),Progress:we(Yn).nullish()}),uc=zod.z.array(CR),SR=zod.z.string(),cc=zod.z.object({Rank:zod.z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:mo.nullish()}).passthrough(),xR=zod.z.object({RankRewards:zod.z.array(cc).nullish()}).passthrough(),bR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),DR=zod.z.object({Milestones:Q.nullish(),RankRewards:Q.nullish()}).passthrough(),IR=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:SR.nullish(),Schedule:Re.nullish(),ChainEvents:zod.z.array(bR).nullish(),Gate:Z.nullish(),TopUsersLimit:zod.z.number().nullish(),MinScoreToEnterTop:zod.z.number().nullish(),BracketSize:zod.z.number().nullish(),LinkedSeasonChainID:zod.z.string().nullish(),RankRewards:zod.z.array(cc).nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:DR.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(ot).nullish()}).passthrough(),PR=zod.z.object({Milestones:zod.z.record(zod.z.string(),fi).nullish(),RankRewards:zod.z.record(zod.z.string(),xR).nullish()}).passthrough(),nr=zod.z.object({Definitions:zod.z.record(zod.z.string(),IR).nullish(),Presets:PR.nullish()}).passthrough(),je={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 pc="Leaderboard",dc={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"]},rr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(dc,{schema:ir,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(pc,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.leaderboard.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(pc,n.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",n.data)),n}async getLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return u("client","LeaderboardID is required.");if(t<=0)return u("client","Score must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},n=await this.ctx.api.leaderboard.submitScore(i);if(n.ok){let r=n.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),r.NewScore,t,r.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",r);}return n}async submitScoreFromSource(e,t,i,n,r=1){if(!e)return u("client","LeaderboardID is required.");if(!t)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:n,RollMultiplier:r},c=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(c.ok){let h=c.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),h.NewScore,h.NewScore,h.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",h);}return c}async claimCycleReward(e){if(!e)return u("client","LeaderboardID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",n);}return i}async claimMilestone(e,t,i){if(!e||!t)return u("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},r=await this.ctx.api.leaderboard.claimMilestone(n);if(r.ok){let o=r.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",o);}return r}async getFriendsLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(u("client","leaderboardIDs is required.")):this.ctx.cache.read(dc,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(n.Data.LeaderboardID)),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(n.Data.LeaderboardID),n.Data.MilestoneID),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return u("client","scores is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(n.Data.LeaderboardID),n.Data.NewScore,n.Data.NewScore,n.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let n of i.data){let r=this.cycleDocID(n.LeaderboardID);n.CycleReward?.Success&&n.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(r),n.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.CycleReward.Data.Resources,n.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of n.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(r,o.Data.MilestoneID),o.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(o.Data.Resources,o.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let n of i.data)n.Progress?.Success&&n.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(n.LeaderboardID),n.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var Qo=zod.z.object({}).passthrough().transform(s=>s),sr=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>gc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:W.nullish(),UserState:Qo.nullish(),NextTier:zod.z.lazy(()=>fc).nullish()}).passthrough(),hc=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:W.nullish(),NewStatusTokens:W.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),Ho=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:M.nullish(),Inventory:K.nullish()}),mc=Ct(Ho);var fc=zod.z.object({Tier:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredTokens:W.nullish(),TierReachedReward:H.nullish()}).passthrough(),gc=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:W.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(fc).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var vR=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Seasons:zod.z.array(gc).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:Z.nullish()}).passthrough(),or=zod.z.object({Chains:zod.z.record(zod.z.string(),vR).nullish()}).passthrough(),Ft={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var yc="Season",Rc={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:s=>{let e=Date.parse(s.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},ar=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Rc,{schema:sr,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(yc,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.season.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(yc,n.data),this.ctx.emitter.emit("season:definitionsLoaded",n.data)),n}getActiveSeason(e,t){return e?this.ctx.cache.read(Rc,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(u("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return u("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","Amount must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${G()}`},n=await this.ctx.api.season.grantStatusTokens(i);return n.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,n.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",n.data)),n}async claimTierReward(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","TierNumber must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${G()}`},n=await this.ctx.api.season.claimTierReward(i);if(n.ok){let r=n.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",r);}return n}async claimTierRewardsBatch(e,t){if(!e)return u("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return u("client","TierNumbers is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${G()}`},r=await this.ctx.api.season.claimTierRewardsBatch(n);if(r.ok){let o=r.data;for(let c of o.Items??[]){let h=c.Data?.TierNumber;c.Success&&typeof h=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,h);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return r}};var Cc="Premium",lr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Cc,e);if(t){let r={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",r),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.premium.getDefinitions(i);return n.ok&&n.data.Premium&&(this.ctx.data.config.patchSection(Cc,n.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},n=await this.ctx.api.premium.activateTrial(i);return n.ok&&(n.data.Premium&&this.ctx.data.user.applyPremium(n.data.Premium),this.ctx.emitter.emit("premium:trialActivated",n.data)),n}async purchaseItemOrCurrency(e,t,i="Default",n=1,r){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:n,CreditsConfirmationID:r,RelatedEntityID:`premium_purchase_${e}_${t}`},c=await this.ctx.api.premium.purchaseItemOrCurrency(o);if(c.ok&&!c.data.CreditsConfirmation){let h=c.data;h.Premium&&this.ctx.data.user.applyPremium(h.Premium),this.ctx.data.user.applyResourceOperation(h.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",h);}return c}async purchaseRealMoney(e,t,i,n,r,o,c,h){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!n||!r)return u("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return a;let y={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:n,ReceiptData:r,PurchaseToken:o,PackageName:c,AppStoreEnvironment:h,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(y);if(V.ok){let oe=V.data;oe.Premium&&this.ctx.data.user.applyPremium(oe.Premium),this.ctx.data.user.applyResourceOperation(oe.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",oe);}return V}};var ur=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:p.nullish()}),$o=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:W.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),ur).nullish(),UpdatedAt:p.nullish()}).passthrough(),Sc=zod.z.object({Characters:zod.z.record(zod.z.string(),$o).nullish()}),Jo=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),Zo=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),xc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),ur).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),bc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),TR=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Dc=zod.z.object({ServerTimeUtc:p,Characters:zod.z.record(zod.z.string(),TR).nullish(),Inventory:K.nullish()}),Yo=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:M.nullish()}),Ic=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:M.nullish(),Inventory:K.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:ur.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Pc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:ur.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),vc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),AR=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:p.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:ce.nullish()}),wR=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(AR).nullish()}),Tc=zod.z.object({ServerTimeUtc:p,Characters:zod.z.record(zod.z.string(),wR).nullish()}),Ac=Ct(Yo),wc=Ct(Zo),kc=Ct(Jo),Xo=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),zc=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:ce.nullish(),CostCurve:Ne.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Ne.nullish(),RankCurve:Ne.nullish(),Requirements:zod.z.array(Xo).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),kR=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Xo).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(),Mc=zod.z.object({Slots:zod.z.record(zod.z.string(),kR).nullish()}).passthrough(),Oc=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(),zR=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),MR=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:ce.nullish()}).passthrough(),OR=zod.z.object({Stats:Q.nullish(),Levels:Q.nullish(),Equipment:Q.nullish()}).passthrough(),Ec=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:Ne.nullish()}).passthrough(),ea="@skin";function ER(s){return !!s&&s.startsWith("@")}var UR=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),qR=zod.z.object({PriceOptions:ce.nullish(),Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),LR=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Xo).nullish()}).passthrough(),BR=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Oc.nullish(),Item:UR.nullish(),Sale:qR.nullish(),Requirements:LR.nullish()}).passthrough(),GR=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),BR).nullish()}).passthrough(),FR=zod.z.object({CharacterID:zod.z.string(),Identity:Oc.nullish(),Classification:zR.nullish(),Unlock:MR.nullish(),Presets:OR.nullish(),Equipment:Mc.nullish(),Stats:zod.z.record(zod.z.string(),zc).nullish(),RankLadder:Ec.nullish(),RankStatCurve:Ne.nullish(),StatMaxLevelCurve:Ne.nullish(),Skins:GR.nullish()}).passthrough(),_R=zod.z.object({Stats:zod.z.record(zod.z.string(),zc).nullish()}).passthrough(),VR=zod.z.object({RankLadder:Ec.nullish()}).passthrough(),NR=zod.z.object({Equipment:Mc.nullish()}).passthrough(),jR=zod.z.object({Stats:zod.z.record(zod.z.string(),_R).nullish(),Levels:zod.z.record(zod.z.string(),VR).nullish(),Equipment:zod.z.record(zod.z.string(),NR).nullish()}).passthrough(),cr=zod.z.object({Definitions:zod.z.record(zod.z.string(),FR).nullish(),Presets:jR.nullish()}).passthrough(),We={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"},WR="SKIN_ALREADY_OWNED";var ta="Character",pr=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(ta)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([n,r])=>r?.Unlock?.UnlockedByDefault===true&&!i[r.CharacterID??n])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(ta,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.character.getCharacterDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ta,n.data),this.ctx.emitter.emit("character:definitionsLoaded",n.data)),n}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${G()}`},n=await this.ctx.api.character.unlockCharacter(i);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},r.Power!=null&&(o.Power=r.Power),o.UpdatedAt=r.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",r);}return n}async upgradeStatLevel(e,t,i){if(!e||!t)return u("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${G()}`,SelectedOptionID:i?.selectedOptionID,CreditsConfirmationID:i?.creditsConfirmationID,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},r=await this.ctx.api.character.upgradeStatLevel(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;this.ctx.data.user.patchCharacter(o.CharacterID,c=>{c.StatLevels??={},c.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(c.Power=o.Power),c.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return r}async upgradeCharacterLevel(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${G()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},n=await this.ctx.api.character.upgradeCharacterLevel(i);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,o=>{o.Level=r.NewLevel,r.Power!=null&&(o.Power=r.Power),o.UpdatedAt=r.ServerTimeUtc,r.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",r);}return n}async equipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},n=await this.ctx.api.character.equipItems(i);return n.ok&&(this.applyEquipChangesLocally(e,n.data),this.ctx.emitter.emit("character:itemsEquipped",n.data)),n}async unequipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},n=await this.ctx.api.character.unequipItems(i);if(n.ok){let r=n.data;this.applyUnequipChangesLocally(e,r),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:r.ClearedSlotIDs??[],power:r.Power??null});}return n}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${G()}`},r=await this.ctx.api.character.unlockSkin(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),o.Equipped&&o.Equipment&&this.applySkinLocally(o.CharacterID,o.Equipment,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",o);}return r}async equipSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},r=await this.ctx.api.character.equipSkin(n);if(r.ok){let o=r.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return r}async unequipSkin(e){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let n=i.data;n.Cleared&&(this.applyInventoryDelta(n.Inventory),this.applySkinLocally(n.CharacterID,null,n.Power,n.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",n);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):a}applySkinLocally(e,t,i,n){let r=this.ctx.data.user;r.patchCharacterEquipment(e,ea,t??null),r.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=n;});}async unlockCharactersBatch(e){if(!e||e.length===0)return u("client","characterIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level??=1,r.StatLevels??={},r.Equipment??={},n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level=n.NewLevel,n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(r.StatLevels??={},r.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.StatLevels??={},r.StatLevels[n.StatID]=n.StatLevel,n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[n,r]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,n,r);i.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let r of i)n.patchCharacterEquipment(e,r,null);n.patchCharacter(e,r=>{t.Power!=null&&(r.Power=t.Power),r.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,n]of Object.entries(e.Characters??{})){for(let r of n.ClearedSlotIDs??[])t.patchCharacterEquipment(i,r,null);t.patchCharacter(i,r=>{n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=e.ServerTimeUtc;});}}};var Uc="Match",dr=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,n,r,o){let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:n,TargetUserID:r,SelectedOptionID:o,RelatedEntityID:`pvp_create_${c.userID}_${G()}`},y=await this.ctx.api.match.createMatch(h);return y.ok&&(this.ctx.data.user.applyResourceOperation(y.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",y.data)),y}async updateMatch(e,t={}){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},n=await this.ctx.api.match.updateMatch(i);return n.ok&&this.ctx.emitter.emit("match:updated",n.data),n}async cancelMatch(e){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,n){let r=this.ctx.auth.context;if(!r)return a;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:n,RelatedEntityID:`pvp_battle_${e}_${G()}`},c=await this.ctx.api.match.instantBattle(o);if(c.ok){let h=c.data,y=this.ctx.data.config.itemDefinitions;if(h.Resources)this.ctx.data.user.applyResourceOperation(h.Resources,y);else if(h.ResourcesDual){let V=h.ResourcesDual;V.FromUserID===r.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,y):V.ToUserID===r.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,y);}this.ctx.emitter.emit("match:instantBattleCompleted",h);}return c}async saveStrategy(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let n=this.ctx.authedRequest();if(!n)return a;n.Page=e,n.PageSize=t,n.Statuses=i;let r=await this.ctx.api.match.getMyMatches(n);return r.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",r.data),r}async getAvailableMatches(e=0,t=20,i=false){let n=this.ctx.authedRequest();if(!n)return a;n.Page=e,n.PageSize=t,n.OnlyPublic=i;let r=await this.ctx.api.match.getAvailableMatches(n);return r.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",r.data),r}async getDefinitions(e){let t=this.ctx.cache.configSection(Uc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.match.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Uc,n.data),this.ctx.emitter.emit("match:definitionsLoaded",n.data)),n}};var qc="Craft",hr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(qc,e);if(t){let r={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.craft.getDefinitions(i);return n.ok&&n.data.CraftDefinitions&&(this.ctx.data.config.patchSection(qc,n.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",n.data.CraftDefinitions)),n}async craft(e,t,i=1,n,r,o){if(!e)return u("client","CraftID is required.");let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:n,InputInstanceIDs:r,CreditsConfirmationID:o,RelatedEntityID:`craft_${e}_${c.userID}_${G()}`},y=await this.ctx.api.craft.craft(h);return y.ok&&!y.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(y.data.Resources,y.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",y.data)),y}};var _t=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(_t),zod.z.record(zod.z.string(),_t)]));var Vt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Lc=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Xt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Bi(s){return s!==Xt.Pending&&s!==Xt.Running}var KR={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 QR(s){return s?/\b(AI_[A-Z_]+)\s*:/.exec(s)?.[1]??null:null}var HR=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),$R=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),mr=zod.z.object({CreditsConfirmation:fe.nullish(),GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Lc.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),_t).nullish(),Assets:zod.z.array(HR).nullish(),Error:$R.nullish(),Charge:M.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:M.nullish(),Context:zod.z.record(zod.z.string(),_t).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish()}),Bc=zod.z.object({Data:zod.z.array(mr).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),JR=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(),Di=zod.z.record(zod.z.string(),zod.z.string()),ZR=zod.z.object({Key:zod.z.string().nullish(),Role:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),Label:Di.nullish()}).passthrough(),YR=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:Di.nullish(),Placeholder:Di.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string().nullish(),Label:Di.nullish()}).passthrough()).nullish()}).passthrough(),XR=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:Di.nullish(),Description:Di.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(ZR).nullish(),Variables:zod.z.array(YR).nullish()}).passthrough(),eC=zod.z.object({Modality:Lc.nullish(),Async:zod.z.boolean().nullish(),Limits:Se.nullish(),PriceOptions:ce.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:H.nullish(),PromptVariables:zod.z.array(JR).nullish(),AllowFreePrompt:zod.z.boolean().nullish(),PlatformTemplateId:zod.z.string().nullish(),PlatformTemplate:XR.nullish(),FreePerDay:zod.z.number().nullish(),FreeLeftToday:zod.z.number().nullish()}).passthrough(),Gc=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),eC).nullish()}).passthrough(),Be={GetDefinitions:"GetDefinitions",GenerateText:"GenerateText",GetText:"GetText",GenerateImage:"GenerateImage",EditImage:"EditImage",GenerateVideo:"GenerateVideo",GetVideo:"GetVideo",GenerateAudio:"GenerateAudio",GenerateMusic:"GenerateMusic",GenerateThreeD:"GenerateThreeD",GetThreeD:"GetThreeD",ListGenerations:"ListGenerations",GetGeneration:"GetGeneration",GetImage:"GetImage",GetAudio:"GetAudio",GetMusic:"GetMusic",GenerateFromTemplate:"GenerateFromTemplate"};var Fc="AI",tC=/^[A-Za-z0-9_-]{1,128}$/,iC=2e3,nC=5e3,rC=30*6e4;function sC(s,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(n),e?.removeEventListener("abort",i),t();},n=setTimeout(i,s);e?.addEventListener("abort",i,{once:true});})}var fr=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(Fc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.ai.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Fc,n.data),this.ctx.emitter.emit("ai:definitionsLoaded",n.data)),n}generateText(e,t,i){return this.generate(e,{Text:t},i,n=>this.ctx.api.ai.generateText(n))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,n=>this.ctx.api.ai.generateImage(n))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,n=>this.ctx.api.ai.editImage(n))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,n=>this.ctx.api.ai.generateVideo(n))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,n=>this.ctx.api.ai.generateAudio(n))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,n=>this.ctx.api.ai.generateMusic(n))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,i){return this.generate(e,{TemplateInputs:t},i,n=>this.ctx.api.ai.generateFromTemplate(n))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,n=>this.ctx.api.ai.generateThreeD(n))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):a}async getGeneration(e){if(!e)return u("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):a}isTerminal(e){return Bi(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let c=await this.getGeneration(e);if(!c.ok)return c;i=c.data;}else {if(!e?.GenerationID)return u("client","GenerationID is required.");i=e;}let n=Date.now()+(t.timeoutMs??rC),r=Math.max(1,t.intervalMs??iC),o=Math.max(r,t.maxIntervalMs??nC);for(;!Bi(i.Status);){if(t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");if(Date.now()+r>n)return u("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await sC(r,t.signal),t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");let c=await this.pollFor(i);if(r=Math.min(o,Math.round(r*1.5)),!c.ok){if(c.reason==="connection")continue;return c}i=c.data,Bi(i.Status)||t.onUpdate?.(i);}return N(i)}pollFor(e){switch(e.Modality){case Vt.Text:return this.getText(e.GenerationID);case Vt.Image:return this.getImage(e.GenerationID);case Vt.Audio:return this.getAudio(e.GenerationID);case Vt.Music:return this.getMusic(e.GenerationID);case Vt.Video:return this.getVideo(e.GenerationID);case Vt.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,n){if(!e)return u("client","FeatureKey is required.");let r=i?.relatedEntityID;if(r!==void 0&&!tC.test(r))return u("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,Variables:i?.variables,Context:i?.context,RelatedEntityID:r??G()},c=await n(o);return c.ok&&!c.data.CreditsConfirmation&&(await this.reconcileCharge(c.data,true),this.emitView(c.data)),c}async poll(e,t){if(!e)return u("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.GenerationID=e;let n=await t(i);return n.ok&&(await this.reconcileCharge(n.data,false),this.emitView(n.data)),n}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Xt.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===Xt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Xt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var ia="Collection",gr=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let i=e.cache.configSection(ia),n=Object.keys(i?.Collections??{});if(n.length===0||t)return false;let r=e.cache.configSection("Season");return Object.values(r?.Chains??{}).some(c=>(c?.Seasons??[]).some(h=>!!h?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==n[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ia,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.collection.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ia,n.data),this.ctx.emitter.emit("collection:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,n){let r=this.ctx.auth.context;if(!r)return a;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${r.userID}_${G()}`},c=await this.ctx.api.collection.openPack(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",c.data)),c}async openCollectionChest(e,t,i=1){let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${n.userID}_${G()}`},o=await this.ctx.api.collection.openCollectionChest(r);return o.ok&&(this.ctx.data.user.applyResourcesWithDelta(o.data.Resources,o.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",o.data)),o}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${G()}`},r=await this.ctx.api.collection.useCollectibleJoker(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",r.data)),r}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${G()}`},r=await this.ctx.api.collection.claimSetReward(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",r.data)),r}async claimSetRewardsBatch(e){if(!e||e.length===0)return u("client","sets is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${G()}`},n=await this.ctx.api.collection.claimGrandPrize(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",n.data)),n}async sendTradeOffer(e,t,i,n,r,o=false){let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:n,RequestedCollectibleID:r,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${c.userID}_${n}_${G()}`},y=await this.ctx.api.collection.sendTradeOffer(h);return y.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",y.data)),y}async cancelTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${G()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${G()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${G()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var oC=zod.z.object({}).passthrough().transform(s=>s),aC={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},lC={Active:"Active",Left:"Left",Replaced:"Replaced"},uC=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),cC=zod.z.object({UserID:zod.z.string().nullish(),PublicData:qe.nullish(),BuildObjectsProgress:uC.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),pC=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(),dC=zod.z.object({Objects:zod.z.array(pC).nullish()}).passthrough(),_c=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(cC).nullish(),BuildObjectsState:dC.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:zod.z.number().nullish()}).passthrough(),Vc=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>Nc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),hC=zod.z.string(),na=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(),mC=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:H.nullish()}).passthrough(),fC=zod.z.object({Objects:zod.z.array(mC).nullish(),PriceOptions:ce.nullish(),SpinnerTable:zod.z.array(na).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),Nc=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:hC.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:fC.nullish(),GrandPrize:H.nullish()}).passthrough(),gC=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Events:zod.z.array(Nc).nullish(),Gate:Z.nullish()}).passthrough(),yr=zod.z.object({ServerTimeUtc:p.nullish(),UserState:oC.nullish(),ActiveGroup:_c.nullish()}),ra=zod.z.object({ServerTimeUtc:p.nullish(),Group:_c.nullish(),SecondsRemaining:W.nullish()}),jc=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Resources:M.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:na.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(na).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),sa=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Wc=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Rr=zod.z.object({Chains:zod.z.record(zod.z.string(),gC).nullish()}).passthrough(),gt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Kc="CoopEvent",Qc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},Cr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Qc,{schema:yr,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Kc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.coopEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Kc,n.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",n.data)),n}async getActiveEvent(e){if(!e)return u("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(Qc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return u("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return u("client","CoopChainID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let n=i.data.Group;n&&this.ctx.data.user.patchCoopEventActiveGroup(n.GroupID??null,n.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,n,r){if(!e||!t)return u("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:n,CreditsConfirmationID:r,RelatedEntityID:G()},c=await this.ctx.api.coopEvent.spin(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(c.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",c.data)),c}async claimObjectReward(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var yC={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},RC={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},CC=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:p.nullish(),CompletedAtUtc:p.nullish(),LastExecutedAtUtc:p.nullish(),NextAvailableAtUtc:p.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),SC=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),Hc=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:p.nullish(),ExhaustedAtUtc:p.nullish(),ExpiredAtUtc:p.nullish(),DismissedAtUtc:p.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:p.nullish(),Nodes:zod.z.record(zod.z.string(),CC).nullish(),Tracks:zod.z.record(zod.z.string(),SC).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),xC=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:p.nullish(),ActiveOfferExpiresAtUtc:p.nullish(),ActiveOffer:Hc.nullish(),NextCycleStartsAtUtc:p.nullish(),LastUpdatedUtc:p.nullish(),DismissSkipAvailableAtUtc:p.nullish(),LastDismissedAtUtc:p.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),bC=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),DC=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:p.nullish(),LastActivatedAtUtc:p.nullish(),LastExhaustedAtUtc:p.nullish(),NodeCounts:zod.z.record(zod.z.string(),bC).nullish()}).passthrough(),IC=zod.z.object({Slots:zod.z.record(zod.z.string(),xC).nullish(),OfferHistory:zod.z.record(zod.z.string(),DC).nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),PC={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},vC={Eq:"Eq",Gte:"Gte",Lte:"Lte"},TC=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),Sr=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(),$c=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),Jc=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),AC=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Behaviour:Q.nullish()}).passthrough(),wC=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:Sr.nullish(),Availability:$c.nullish(),Behaviour:Jc.nullish(),Queue:zod.z.array(TC).nullish(),Presets:AC.nullish()}).passthrough(),kC=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),zC=zod.z.object({RewardedVideo:kC.nullish()}).passthrough(),MC=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),OC=zod.z.object({Identity:Q.nullish(),Graph:Q.nullish(),Milestones:Q.nullish()}).passthrough(),EC=zod.z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish()}).passthrough(),UC=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),qC=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(),LC=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(MC).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),Zc=zod.z.object({Options:ce.nullish()}).passthrough(),Yc=zod.z.object({Grants:H.nullish(),TrackChanges:zod.z.array(UC).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),BC=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:Sr.nullish(),Pricing:Zc.nullish(),Reward:Yc.nullish(),Action:zC.nullish(),UnlockRules:LC.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:Se.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:EC.nullish()}).passthrough(),Xc=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(BC).nullish(),Tracks:zod.z.array(qC).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),ep=zod.z.object({Milestones:zod.z.record(zod.z.string(),_e).nullish(),ClaimMode:zod.z.string().nullish(),Token:Jt.nullish()}).passthrough(),tp=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:Sr.nullish(),Graph:Xc.nullish(),Milestones:ep.nullish(),Presets:OC.nullish()}).passthrough(),GC=zod.z.object({Identity:zod.z.record(zod.z.string(),Sr).nullish(),Availability:zod.z.record(zod.z.string(),$c).nullish(),Behaviour:zod.z.record(zod.z.string(),Jc).nullish(),Graph:zod.z.record(zod.z.string(),Xc).nullish(),Milestones:zod.z.record(zod.z.string(),ep).nullish(),Pricing:zod.z.record(zod.z.string(),Zc).nullish(),Reward:zod.z.record(zod.z.string(),Yc).nullish()}).passthrough(),oa=zod.z.object({Slots:zod.z.record(zod.z.string(),wC).nullish(),Offers:zod.z.record(zod.z.string(),tp).nullish(),Presets:GC.nullish()}).passthrough(),ip=zod.z.object({DealOfferDefinitions:oa.nullish()}),np=zod.z.object({DealOffers:IC.nullish()}),FC=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(),_C=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:tp.nullish(),ActivationState:Hc.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:p.nullish(),Cost:vt.nullish(),Milestone:FC.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),xr=zod.z.object({Slots:zod.z.array(_C).nullish()}),rp=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),sp=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),op=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),ap=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),lp=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:M.nullish(),Inventory:K.nullish()}),xt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var VC="DealOffer",up={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},br=class{constructor(e){this.ctx=e;e.cache.bindLoginView(up,{schema:xr,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(VC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(up,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${G()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,n){if(!e||!t)return u("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return a;let r=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:r??`deal_exec_${e}_${t}_${G()}`},c=await this.ctx.api.dealOffer.executeNode(o);return c.ok&&!c.data.CreditsConfirmation&&(c.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",c.data)),c}async recordShow(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${G()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return u("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${G()}`},n=await this.ctx.api.dealOffer.claimMilestone(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",n.data)),n}async claimMilestonesBatch(e,t){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${G()}`},r=await this.ctx.api.dealOffer.claimMilestonesBatch(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",r.data)),r}};var cp="Referral",Dr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(cp,e);if(t){let r={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",r),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.referral.getDefinitions(i);return n.ok&&n.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(cp,n.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=$t.parseReferralCode(e)?.toUpperCase();if(!t)return u("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},r=await this.ctx.api.referral.activateReferralCode(n);if(r.ok){let o=r.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID,o.QualificationPending),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return r}async claimInviteReward(e){let t=e.trim();if(!t)return u("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},r=await this.ctx.api.referral.claimInviteReward(n);if(r.ok){let o=r.data;o.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(o.RewardID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",o);}return r}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return u("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},r=await this.ctx.api.referral.claimInviteRewardsBatch(n);if(r.ok){let o=r.data;for(let c of o.Items??[])c.Success&&c.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(c.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return r}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.checkQualification(e);return t.ok&&t.data.Qualification&&!t.data.QualificationPending&&await this.getUserState(),t}async checkQualificationIfPending(){this.ctx.data.user.state?.Referral?.QualificationPending===true&&await this.checkQualification();}};var NC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},pp=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),jC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},WC=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),KC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},QC=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),nt={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},HC={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"},$C=100,JC=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),dp=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(),ZC=zod.z.object({Texts:zod.z.record(zod.z.string(),JC).nullish(),Category:pp.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:dp.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),YC=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:pe.nullish(),Cost:pe.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:p.nullish(),SenderGate:Z.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),XC=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(),eS=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(XC).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:p.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:pe.nullish(),SenderGate:Z.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),hp=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(),ZC).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),YC).nullish(),Transfer:eS.nullish()}).passthrough().nullish(),Integrations:zod.z.object({Leaderboard:zod.z.boolean().nullish(),CoopEvent:zod.z.boolean().nullish(),Season:zod.z.boolean().nullish(),Referral:zod.z.boolean().nullish()}).passthrough().nullish()}).passthrough(),tS=zod.z.object({MessageID:zod.z.string(),Source:WC,Category:pp,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:dp.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:H.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:p,ExpiresAt:p.nullish(),ReadAt:p.nullish(),ClaimedAt:p.nullish()}).passthrough(),iS=zod.z.object({MessageID:zod.z.string(),Module:QC,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:H.nullish()}).passthrough(),aa=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),mp=zod.z.object({ServerTimeUtc:p.nullish(),Messages:zod.z.array(tS).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(iS).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),Ir=zod.z.object({ServerTimeUtc:p.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),la=zod.z.object({ServerTimeUtc:p.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(aa).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),nS=zod.z.object({MessageID:zod.z.string(),Rewards:pe.nullish()}).passthrough(),Pr=zod.z.object({ServerTimeUtc:p.nullish(),Claimed:zod.z.array(nS).default([]),Failed:zod.z.array(aa).default([]),Resources:M.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),fp=zod.z.object({ServerTimeUtc:p.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(aa).default([]),Resources:M.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish()}).passthrough(),gp=zod.z.object({ServerTimeUtc:p.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish(),RecipientReceives:pe.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),yp=zod.z.object({ServerTimeUtc:p.nullish(),ResetsAt:p.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:p.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish()}).passthrough().nullish()}).passthrough();var ua="Mailbox",ca={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},vr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ca,{schema:Ir,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(ca,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(ua)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(ua,e);if(t)return N(t);let i=this.request();if(!i)return a;let n=await this.ctx.api.mailbox.getDefinitions(i);return n.ok&&this.ctx.data.config.patchSection(ua,n.data),n}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return a;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(ca,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return a;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return a;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return u("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):a}async claimRewards(e){let t=(e??[]).map(n=>n?.trim()).filter(Boolean);if(t.length===0)return u("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):a}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):a}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return a;let n=await this.ctx.api.mailbox.deleteMessages(i);return n.ok&&this.emitCounters(n.data),n}async sendGift(e,t){if(!e?.trim())return u("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return u("client","Recipients are required.");let n=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!n)return a;let r=await this.ctx.api.mailbox.sendGift(n);return r.ok&&(r.data.Resources&&this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",r.data)),r}async sendTransfer(e,t,i){if(!e?.trim())return u("client","RecipientUserID is required.");if(!i?.requestID?.trim())return u("client","requestID is required.");let n=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!n)return a;let r=await this.ctx.api.mailbox.sendTransfer(n);return r.ok&&(r.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(r.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",r.data)),r}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):a}};var Tr={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},pa="idos-app",Rp=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()}),Cp=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:M.nullish()});var da={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},rS=5*6e4;function Ar(){return Yt()}async function ha(s){let e=await wt(da.request,da.response,{titleID:s.titleID,userID:s.userID,requestID:s.requestID,placementID:s.placementID,adUnitID:s.adUnitID??null},{answerTimeoutMs:rS});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var sS=new Set(["CANCELLED","DECLINED","CLOSED"]),oS=45e3,aS=s=>new Promise(e=>setTimeout(e,s)),wr=class{constructor(e){this.ctx=e;}ctx;get available(){return Ar()}async showRewarded(e){if(!Ar())return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let i=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!i.ok)return {status:"unavailable",reason:i.error};let n=i.data;if(!n.Allowed)return {status:"denied",reason:n.DenyReason??void 0,retryAfterSeconds:n.RetryAfterSeconds??void 0};if(n.ProviderID!==pa||!n.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let r=await ha({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:n.RequestID,placementID:e,adUnitID:n.AdUnitID});return r.ok?{...await this.awaitReward(n.RequestID,r.via),requestID:n.RequestID}:{status:sS.has(r.error??"")?"cancelled":"unavailable",reason:r.error}}async awaitReward(e,t){let i=Date.now()+oS;for(;;){let n=this.ctx.authedRequest();if(!n)return {status:"pending",via:t};let r=await this.ctx.api.advertising.completeView({...n,RequestID:e});if(r.ok&&r.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:r.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((r.ok?r.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>i)return {status:"pending",via:t,reason:r.ok?void 0:r.error};await aS(o);}}};var lS={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},uS={Title:"Title",Platform:"Platform"},Sp=zod.z.object({UserID:zod.z.string(),PublicData:qe.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),Gi=zod.z.object({Friends:zod.z.array(Sp).nullish()}),cS=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),Fi=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:Sp.nullish(),Counters:cS.nullish()}),pS={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},dS={Like:"Like",Favorite:"Favorite"},hS={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},mS={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},fS={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},gS=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),yS=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(gS).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),OccurredAt:p.nullish(),OwnerImpact:M.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),xp=zod.z.object({Items:zod.z.array(yS).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:p.nullish()}).passthrough(),_i=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:p.nullish()}).passthrough(),RS=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(),Nt=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:RS.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),bp=zod.z.object({Items:zod.z.array(Nt).nullish()}).passthrough(),ma={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},CS=zod.z.object({UserID:zod.z.string(),PublicData:qe.nullish(),Mutual:zod.z.boolean().nullish(),Since:p.nullish()}).passthrough(),kr=zod.z.object({Items:zod.z.array(CS).nullish(),...ma}).passthrough(),SS=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:p.nullish()}).passthrough(),Dp=zod.z.object({Items:zod.z.array(SS).nullish(),...ma}).passthrough(),zr=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:qe.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:p.nullish(),EditedAt:p.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Ip=zod.z.object({Items:zod.z.array(zr).nullish(),...ma,TotalCount:zod.z.number().nullish()}).passthrough(),Pp=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),vp=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),Tp=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(),xS="FRIENDS_FROM_PLATFORM",bS={Off:"Off",Default:"Default",Always:"Always"},DS={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Ap=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:zod.z.boolean().nullish()}).passthrough(),xe={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report"};var fa={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Mr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fa,{schema:_i,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return a;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return u("client","TargetUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return u("client","FriendUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return a;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(fa,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(fa,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):a}async getEntityStates(e,t){if(!t?.length)return u("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):a}async addComment(e,t,i,n){let r=this.targetRequest(e,t);if("ok"in r)return r;if(!i?.trim())return u("client","Text is required.");r.Text=i,r.ParentCommentID=n;let o=await this.ctx.api.social.addComment(r);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return u("client","CommentID is required.");if(!t?.trim())return u("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return a;i.CommentID=e,i.Text=t;let n=await this.ctx.api.social.editComment(i);return n.ok&&this.ctx.emitter.emit("social:commentEdited",n.data),n}async deleteComment(e){if(!e)return u("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let n=this.targetRequest(e,t);return "ok"in n?n:(n.ParentCommentID=i.parentCommentID,this.applyPage(n,i.cursor,i.limit),this.ctx.api.social.getComments(n))}async report(e,t,i,n){let r=this.targetRequest(e,t);if("ok"in r)return r;if(!i)return u("client","ReportReason is required.");r.ReportReason=i,r.ReportComment=n;let o=await this.ctx.api.social.report(r);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,n){let r=this.targetRequest(t,i);if("ok"in r)return r;r.ReactionKind=n;let o=await this.ctx.api.social[e](r);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let n=this.ctx.authedRequest();return n?(this.applyPage(n,t,i),this.ctx.api.social[e](n)):a}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return u("client","EntityType is required.");if(!t)return u("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):a}};var wp="TimedBoost";function IS(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var Or=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(wp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.timedBoost.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(wp,n.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",n.data)),n}async getActive(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let i=e.trim();if(!IS(i))return u("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${i}_${G()}`},r=await this.ctx.api.timedBoost.activate(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;if(o.ActivatedBoost){let c=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,c);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return r}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var Et={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},PS={Client:"Client",Server:"Server",System:"System"},vS=zod.z.enum(["Client","Server","System"]).catch("Client"),TS=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:p.nullish(),Version:zod.z.number().nullish(),LastWriter:vS.nullish(),ExpiresAt:p.nullish()}).passthrough(),Er=zod.z.record(zod.z.string(),TS),kp=zod.z.object({Version:zod.z.number().nullish(),Private:Er.nullish(),Public:Er.nullish(),ReadOnly:Er.nullish()}),ga=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Er.nullish()}),ya=zod.z.object({ServerTimeUtc:p.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:p.nullish()}),AS=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:p.nullish()}),zp=zod.z.object({ServerTimeUtc:p.nullish(),Results:zod.z.array(AS).nullish()}),Mp=zod.z.object({ServerTimeUtc:p.nullish(),DeletedCount:zod.z.number().nullish()}),Op=zod.z.object({Results:zod.z.array(ga).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),wS={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},kS=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),zS=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:kS.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Ur=zod.z.object({Keys:zod.z.record(zod.z.string(),zS).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(),yt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var MS="UserCustomData";function Ep(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var qr=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(MS,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TargetUserID=t;let n=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return n.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",n.data),n}async setPrivateData(e,t){return this.setData(e,t,Et.Private)}async setPublicData(e,t){return this.setData(e,t,Et.Public)}async setData(e,t,i){let n=e.trim();if(!Ep(n))return u("client",'KeyID is required and must not contain "." or "$".');if(t==null)return u("client","Value is required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Value:t},c=await(i===Et.Private?this.ctx.api.userCustomData.setPrivateData(r):this.ctx.api.userCustomData.setPublicData(r));if(c.ok){let h=c.data;this.ctx.data.user.patchUserCustomDataKey(i,h.KeyID,t,h.Version??0,h.ExpiresAt),this.ctx.emitter.emit(i===Et.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",h);}return c}async deleteKey(e,t){let i=e.trim();if(!Ep(i))return u("client",'KeyID is required and must not contain "." or "$".');if(t!==Et.Private&&t!==Et.Public)return u("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},r=await this.ctx.api.userCustomData.deleteKey(n);return r.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),r}async batchSet(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let n of i.data.Results??[]){let r=n.Bucket??Et.Private,o=e.find(c=>c.Bucket===r&&c.KeyID===n.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(r,n.KeyID,o.Value,n.Version??0,n.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let n of e)this.ctx.data.user.removeUserCustomDataKey(n.Bucket,n.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return u("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var OS="TitleCustomDataDefinitions",Up=50;function ES(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}function Ra(s){if(s.ExpiresAt==null)return false;let e=Date.parse(s.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function US(s){let e={};for(let[t,i]of Object.entries(s))Ra(i)||(e[t]=i);return e}var Lr=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(OS,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return a;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(r=>r.trim()).filter(r=>r.length>0);if(!t.length)return u("client","At least one KeyID is required.");if(t.some(r=>!ES(r)))return u("client",'KeyID must not contain "." or "$".');if(t.length>Up)return u("client",`At most ${Up} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return a;i.KeyIDs=t;let n=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return n.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",n.data),n}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Ra(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Ra(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=US(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 Br=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var qS=15,LS="GameLoop",qp="BoardDefinition",Gr=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(LS,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(qp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),N(i);let n=this.ctx.authedRequest();if(!n)return a;let r=await this.ctx.api.gameLoop.getBoardDefinition(n,e);return r.ok&&(this.ctx.data.config.patchSection(qp,r.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",r.data)),r}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return u("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return a;i.StageLevel=e;let n=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return n.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",n.data),n}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return u("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopRoll(i);if(n.ok){let r=n.data,o=pu(new Date,qS);this.ctx.data.user.patchBoardState(c=>{c.Position=r.NewPosition,c.CyclesCompleted=(c.CyclesCompleted??0)+(r.CyclesCompletedDelta??0),c.LastRollAtUtc=new Date().toISOString(),r.ActionRequired&&r.ActionData?c.Pending={Type:r.ActionRequired,TargetUserID:r.ActionData.TargetUserID,TargetPublicData:r.ActionData.PublicData,TargetBuildingStates:r.ActionData.TargetBuildingStates??void 0,TargetHasShield:r.ActionData.TargetHasShield??void 0,RollMultiplier:r.UsedMultiplier??1,ExpiresAtUtc:o}:r.SpecialModeOffer&&(c.Pending={Type:"SPECIAL",RollMultiplier:r.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:r.SpecialModeOffer.ModeID??void 0,Choices:r.SpecialModeOffer.Choices??void 0}});}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),r.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",r);}return n}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopAttack(i);if(n.ok){let r=n.data;this.ctx.data.user.clearBoardPending(),r.IsBotTarget&&r.Operation?this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs):!r.IsBotTarget&&r.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(r.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",r);}else await this.getUserBoardState();return n}async boardLoopRaid(e,t){if(e<0||e>11)return u("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${G()}`},r=await this.ctx.api.gameLoop.boardLoopRaid(n);if(r.ok){let o=r.data;o.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(o.RaidLayout,o.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(o)),this.ctx.emitter.emit("gameLoop:boardRaided",o);}else await this.getUserBoardState();return r}async boardLoopRaidFast(e){if(!e.length)return u("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(n.ok){let r=n.data;r.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(r)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",r);}else await this.getUserBoardState();return n}async boardLoopBuild(e){if(e<0)return u("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopBuild(i);if(n.ok){let r=n.data;r.StageComplete?this.ctx.data.user.patchBoardState(o=>{o.StageLevel=(o.StageLevel??1)+1,o.Position=0,o.Pending=null,o.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(r.BuiltIndex,o=>{r.NewLevel!=null&&(o.Level=r.NewLevel),o.IsDamaged=false,r.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",r);}return n}async boardSpecialChoose(e,t,i){if(!e)return u("client","choiceID must not be empty.");let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:i,RelatedEntityID:`special_choose_${n.userID}_${G()}`},o=await this.ctx.api.gameLoop.boardSpecialChoose(r);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;c.Mode==="Instant"||c.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(y=>{y.ChoiceID=e,y.ChosenMode=c.Mode??"Timed",y.StartedAtUtc=c.StartedAtUtc??null,y.DurationSeconds=c.DurationSeconds??null,y.AdViewsUsed=0;}),c.Operation&&this.ctx.data.user.applyResourcesWithDelta(c.Operation,c.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",c);}return o}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(n.ok){let r=n.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=r.AdViewsUsed??0,o.AccumulatedMultiplier=r.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",r);}return n}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${G()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},n=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(n.ok){let r=n.data;this.ctx.data.user.clearBoardPending(),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",r);}return n}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return u("client","milestoneID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},n=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",n.data)),n}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var Fr=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,n){let r=e.trim();if(!r)return u("client","FunctionName is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:r,FunctionParameter:t,RevisionSelection:i,SpecificRevision:n},c=await this.ctx.api.cloudCode.execute(o);return c.ok&&this.ctx.emitter.emit("cloudCode:executed",c.data),c}};var Lp=zod.z.object({ServerTimeUtc:p,SourceType:hi,SourceID:zod.z.string(),TargetType:hi,TargetID:zod.z.string(),SourceSpent:W,FeeAmount:W,RateApplied:Y,TargetCredited:W}),Bp=zod.z.object({ServerTimeUtc:p,SourceType:hi,SourceID:zod.z.string(),TargetType:hi,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),Gp=zod.z.object({ServerTimeUtc:p,SpendID:zod.z.string(),Resources:M.nullish()}),Vi={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},BS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},Fp=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),GS={Automatic:"Automatic",Manual:"Manual"},FS=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),_S=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),VS=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),NS=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),jS=zod.z.object({TargetCurrencyType:hi.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),_p=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:FS.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(jS).nullish()}).passthrough(),Vp=zod.z.object({CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough(),WS=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:_S.nullish(),Recharge:VS.nullish(),Conversion:_p.nullish(),Permissions:NS.nullish(),Audit:Vp.nullish(),Status:Fp.nullish()}).passthrough(),KS=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),QS=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),HS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),$S=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(),Ca=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),DisplayDecimals:zod.z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:zod.z.array(KS).nullish(),Limits:QS.nullish(),Permissions:HS.nullish(),Conversion:_p.nullish(),Audit:Vp.nullish(),Status:Fp.nullish(),ServerGrantPolicy:$S.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),JS=zod.z.object({SpendID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),PriceOptions:zod.z.record(zod.z.string(),An).nullish()}).passthrough(),_r=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),WS).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),Ca).nullish(),Spends:zod.z.record(zod.z.string(),JS).nullish()}).passthrough();var ZS={EVM:"EVM",Solana:"Solana"},YS=zod.z.enum(["EVM","Solana"]).catch("EVM"),XS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},ex=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),tx={Token:"Token",Nft:"Nft"},Np=zod.z.enum(["Token","Nft"]).catch("Token"),ix={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},nx=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),rx={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},sx=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),ox={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Sa=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),jp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Vr(s){let e=s?.trim();return e||jp.GameTopUp}var ax={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},Wp=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),lx=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(),Kp=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),ux=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:YS.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:Kp.nullish(),NftCollections:zod.z.array(lx).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(),cx=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Kp.nullish()}).passthrough(),px=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),dx={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},hx=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Qp=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:hx.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),mx=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),fx={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Ni=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),gx=zod.z.object({Mode:Ni.nullish(),TokenGates:zod.z.array(Qp).nullish()}).passthrough(),xa=zod.z.object({SystemState:cx.nullish(),Networks:zod.z.record(zod.z.string(),ux).nullish(),AccountSafety:px.nullish(),WalletLogin:mx.nullish(),PlayAccess:gx.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),yx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:p.nullish(),LastUsedAt:p.nullish(),LinkType:ex.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),Hp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:Np.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),Rx=zod.z.object({Status:nx.nullish(),Tier:sx.nullish(),VerifiedAt:p.nullish(),ExpiresAt:p.nullish(),RejectedAt:p.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),Cx=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),Sx=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:zod.z.record(zod.z.string(),Cx).nullish()}).passthrough(),xx=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),bx=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(),xx).nullish()}).passthrough(),Dx=zod.z.object({Tokens:Sx.nullish(),Nfts:bx.nullish()}).passthrough(),ba=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),jt=zod.z.object({Granted:zod.z.boolean(),Mode:Ni.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:p.nullish(),Balances:zod.z.array(ba).nullish()}).passthrough(),Ix=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:p.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:p.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(ba).nullish()}).passthrough(),Px=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),$p=zod.z.object({Mode:Ni.nullish(),TokenGates:zod.z.array(Qp).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(Px).nullish(),Status:jt.nullish()}).passthrough(),vx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:p.nullish(),LoggedInAt:p.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(ba).nullish()}).passthrough(),Tx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:p.nullish()}).passthrough(),Ax=zod.z.object({Version:zod.z.number().nullish(),Stats:Dx.nullish(),LinkedWallets:zod.z.record(zod.z.string(),yx).nullish(),LastWalletLogin:vx.nullish(),PlayAccess:Ix.nullish(),PendingWithdrawals:zod.z.array(Hp).nullish(),Kyc:Rx.nullish(),FirstActivityAt:p.nullish(),LastActivityAt:p.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(Tx).nullish()}).passthrough(),wx=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:p}).passthrough(),Ii=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),wx).nullish(),PendingAdded:Hp.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),kx=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough().transform(s=>s),zx=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Wp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Sa.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:p.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:p.nullish(),RefundCheckedAt:p.nullish()}).passthrough(),Mx=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Wp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Sa.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:p.nullish()}).passthrough(),Jp=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Da=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(Jp).nullish(),Signature:zod.z.string().nullish()}).passthrough(),Ia=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(Jp).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(),Zp=zod.z.object({Blockchain:xa.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),Ca).nullish()}).passthrough(),Yp=zod.z.object({State:Ax.nullish(),CryptoBalances:zod.z.record(zod.z.string(),kx).nullish()}).passthrough(),Xp=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:Ii.nullish()}).passthrough(),ed=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}).passthrough(),td=zod.z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:p.nullish(),EvmSignature:Da.nullish(),SolanaSignature:Ia.nullish(),StateDelta:Ii.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),id=zod.z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish(),EvmSignature:Da.nullish(),SolanaSignature:Ia.nullish(),StateDelta:Ii.nullish(),Inventory:K.nullish()}).passthrough(),nd=zod.z.object({TokenTransactions:zod.z.array(zx).nullish(),NFTTransactions:zod.z.array(Mx).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Pa=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:zod.z.string().nullish()}).passthrough(),rd=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:Np.nullish(),EvmSignature:Da.nullish(),SolanaSignature:Ia.nullish()}).passthrough(),sd=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:Sa.nullish(),StateDelta:Ii.nullish()}).passthrough(),Je={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 Ox="Blockchain",od="Blockchain:Definitions",Nr=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(od,e);if(t)return N(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return a;let n=this.ctx.api.blockchain.getDefinitions(i).then(r=>(r.ok&&(this.ctx.data.config.patchSection(Ox,r.data.Blockchain),this.ctx.data.config.patchSection(od,r.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",r.data)),r)).finally(()=>{this.definitionsInflight===n&&(this.definitionsInflight=null);});return this.definitionsInflight=n,n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositToken(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",n.data)),n}async depositNFT(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositNFT(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",n.data)),n}async requestTokenWithdrawal(e,t,i,n,r){if(!e)return u("client","CurrencyID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!n)return u("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return a;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=n,o.Category=Vr(r);let c=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return c.ok&&(this.ctx.data.user.applyBlockchainStateDelta(c.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",c.data)),c}async requestNFTWithdrawal(e,t,i,n,r,o,c){if(!e)return u("client","ItemID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!n)return u("client","Amount is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.NetworkID=t,h.WalletAddress=i,h.Amount=n,h.Category=Vr(r),o!==void 0&&(h.Level=o),c&&(h.ItemInstanceID=c);let y=await this.ctx.api.blockchain.requestNFTWithdrawal(h);return y.ok&&(this.ctx.data.user.applyBlockchainStateDelta(y.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(y.data.Resources,y.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",y.data)),y}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return a;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return u("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return u("client","TitleTransactionID is required.");if(!t)return u("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TitleTransactionID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.confirmWithdrawal(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",n.data)),n}async donateToDeveloper(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToDeveloper(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",n.data),n}async donateToUsersPool(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToUsersPool(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",n.data),n}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var Ex={Head:"Head",Torso:"Torso",Legs:"Legs"},jr=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),Ux={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},va=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),ld=zod.z.object({AttackTarget:jr,DefenseTarget:jr});var qx=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),Lx=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:jr.nullish(),DefenseZone:jr.nullish(),HitType:qx.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),Bx=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(),Gx=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),ad=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:$o.nullish(),BattleStrategy:zod.z.array(ld).nullish(),UnstackableItems:zod.z.record(zod.z.string(),Gx).nullish(),Stats:Bx.nullish()}).passthrough(),Fx=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:pe.nullish(),NetReward:pe.nullish(),BattleLog:zod.z.array(Lx).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:ad.nullish(),P2BattleProfile:ad.nullish()}).passthrough(),ud=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:p.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(ld).nullish(),TargetUserID:zod.z.string().nullish(),Entry:pe.nullish(),CreationCostPaid:pe.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:p.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:p.nullish(),Status:va.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:p.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:p.nullish()}).passthrough(),cd=zod.z.object({Status:va,MatchID:zod.z.string(),Entry:pe.nullish(),Resources:M.nullish()}),pd=zod.z.object({Match:ud.nullish()}),dd=zod.z.object({MatchID:zod.z.string(),Status:va,Resources:M.nullish()}),hd=zod.z.object({Battle:Fx.nullish(),Resources:M.nullish(),ResourcesDual:Tt.nullish()}),Ta=zod.z.object({Matches:zod.z.array(ud).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),bt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var _x=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var Vx=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),Nx=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(),jx=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),Wx=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:jx.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),Kx=zod.z.object({Kind:Vx.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Ne.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),Qx=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(Kx).nullish()}).passthrough(),ei=zod.z.object({Terms:zod.z.array(Qx).nullish()}).passthrough(),Hx=zod.z.object({Health:ei.nullish(),Damage:ei.nullish(),Armor:ei.nullish(),AttackSpeed:ei.nullish(),CritChance:ei.nullish(),CritDamage:ei.nullish(),Dodge:ei.nullish()}).passthrough(),md=zod.z.object({StatMapping:Nx.nullish(),Combat:Wx.nullish(),Formula:Hx.nullish()}).passthrough(),$x=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),ji=zod.z.object({Kind:_x.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:en.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),fd=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(ji).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),gd=zod.z.object({PriceOptions:ce.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:Se.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),Jx=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:$x.nullish(),Entry:fd.nullish(),Creation:gd.nullish(),Settings:md.nullish()}).passthrough(),Zx=zod.z.object({Rules:zod.z.record(zod.z.string(),Jx).nullish(),Defaults:md.nullish(),EntryDefaults:fd.nullish(),CreationDefaults:gd.nullish()}).passthrough(),Aa=zod.z.object({InstantBattle:Zx.nullish()}).passthrough(),yd=Aa;var Yx={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},wa=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),Xx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},ka=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),eb={Burn:"Burn",Ledger:"Ledger"},tb=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Kr={Item:"Item",VirtualCurrency:"VirtualCurrency"},za=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),ib=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:W.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(ji).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Ma=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:W.nullish(),Sink:tb.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),ib).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),nb=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(),rb=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:Se.nullish(),BuyLimits:Se.nullish(),ListingFeeOptions:ce.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),sb=zod.z.object({Enabled:zod.z.boolean().nullish(),MinDurationHours:zod.z.number().nullish(),MaxDurationHours:zod.z.number().nullish(),AntiSnipeWindowSeconds:zod.z.number().nullish(),AntiSnipeExtensionSeconds:zod.z.number().nullish(),MaxAntiSnipeExtensions:zod.z.number().nullish(),MinBidStepPercent:zod.z.number().nullish(),MinBidStepAbsolute:W.nullish(),BidLimits:Se.nullish()}).passthrough(),ob=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:Se.nullish(),FillLimits:Se.nullish()}).passthrough(),ab=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:Se.nullish()}).passthrough(),lb=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Oa=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:Re.nullish(),PricePolicy:Qr.nullish(),Commission:Ma.nullish(),Tradability:nb.nullish(),Listings:rb.nullish(),Auctions:sb.nullish(),BuyOrders:ob.nullish(),DirectTrades:ab.nullish(),Matching:lb.nullish()}).passthrough(),Rd=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:W.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:p.nullish()}).passthrough(),ub=zod.z.object({BidAxisType:mi.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:W.nullish(),CurrentBid:W.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(Rd).nullish()}).passthrough(),Wr=zod.z.object({LastAt:p.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),cb=zod.z.object({Create:Wr.nullish(),Buy:Wr.nullish(),Sell:Wr.nullish(),Bid:Wr.nullish()}).passthrough(),pb=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),db=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:pb.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),Ut=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:wa.nullish(),Status:ka.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:qe.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:za.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:W.nullish(),GoodsInstances:zod.z.array(db).nullish(),Price:pe.nullish(),Auction:ub.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),hb=zod.z.object({GoodsType:za.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(wa,W).nullish()}).passthrough(),Cd=zod.z.object({Definitions:Oa.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),Ea=zod.z.object({Offers:zod.z.array(Ut).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Sd=zod.z.object({Groups:zod.z.array(hb).nullish()}).passthrough(),xd=zod.z.object({Offer:Ut.nullish()}).passthrough(),ct=zod.z.object({OfferID:zod.z.string().nullish(),Status:ka.nullish(),Settlement:Tt.nullish(),Resources:M.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Wi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:Ut.nullish(),Resources:M.nullish(),Matched:zod.z.boolean().nullish(),Settlement:ct.nullish()}).passthrough(),bd=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:W.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish()}).passthrough(),Hr=zod.z.object({MyOffers:zod.z.array(Ut).nullish(),MyBids:zod.z.array(Ut).nullish(),MyBuyOrders:zod.z.array(Ut).nullish(),IncomingTrades:zod.z.array(Ut).nullish(),OutgoingTrades:zod.z.array(Ut).nullish(),Claimables:zod.z.array(Ut).nullish(),DrainedRefunds:zod.z.array(Rd).nullish(),Limits:cb.nullish()}).passthrough(),mb=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:wa.nullish(),FinalStatus:ka.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:za.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:W.nullish(),PricePaid:pe.nullish(),CommissionTaken:pe.nullish(),CompletedAt:p.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),Dd=zod.z.object({Entries:zod.z.array(mb).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Oe={GetDefinitions:"GetDefinitions",GetGroupedOffers:"GetGroupedOffers",GetOffersByItem:"GetOffersByItem",GetOffer:"GetOffer",GetBuyOrders:"GetBuyOrders",GetMyState:"GetMyState",GetHistory:"GetHistory",CreateListing:"CreateListing",CancelListing:"CancelListing",Buy:"Buy",MarketBuy:"MarketBuy",MarketSell:"MarketSell",CreateAuction:"CreateAuction",PlaceBid:"PlaceBid",ClaimAuction:"ClaimAuction",CreateBuyOrder:"CreateBuyOrder",CancelBuyOrder:"CancelBuyOrder",FillBuyOrder:"FillBuyOrder",CreateDirectTrade:"CreateDirectTrade",RespondDirectTrade:"RespondDirectTrade",CancelDirectTrade:"CancelDirectTrade",ClaimBack:"ClaimBack"};var fb="Marketplace",Id={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"]},$r=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Id,{schema:Hr,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(fb,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,n=20){if(!e)return u("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return a;r.ItemID=e,r.OfferTypeFilter=t,r.ContinuationToken=i,r.PageSize=n;let o=await this.ctx.api.marketplace.getOffersByItem(r);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let n=this.ctx.authedRequest();if(!n)return a;n.ItemID=e,n.ContinuationToken=t,n.PageSize=i;let r=await this.ctx.api.marketplace.getBuyOrders(n);return r.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",r.data),r}getMyState(e,t){return this.ctx.cache.read(Id,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let n=this.ctx.authedRequest();if(!n)return a;i&&(n.HistoryFilter=i),n.ContinuationToken=e,n.PageSize=t;let r=await this.ctx.api.marketplace.getHistory(n);return r.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",r.data),r}async createListing(e,t,i,n,r,o,c){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!n)return u("client","PriceBundle is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.PriceBundle=n,h.DurationHours=r,h.ItemInstanceIDs=o,h.SelectedOptionID=c;let y=await this.ctx.api.marketplace.createListing(h);return this.applyCreateOfferResult(y,"marketplace:listingCreated"),y}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let n=this.ctx.authedRequest();if(!n)return a;let r=this.applyGoodsSelector(n,i);if(r)return r;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let n=this.ctx.authedRequest();if(!n)return a;let r=this.applyGoodsSelector(n,i);if(r)return r;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,n,r,o,c={}){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.BidAxisType=n,h.BidCurrencyID=c.bidCurrencyID,h.BidCatalogID=c.bidCatalogID,h.BidItemID=c.bidItemID,h.StartingBid=r,h.DurationHours=o,h.ItemInstanceIDs=c.itemInstanceIDs,h.SelectedOptionID=c.selectedOptionID;let y=await this.ctx.api.marketplace.createAuction(h);return this.applyCreateOfferResult(y,"marketplace:auctionCreated"),y}async placeBid(e,t){if(!e)return u("client","OfferID is required.");if(!t||t<=0)return u("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.BidAmount=t;let n=await this.ctx.api.marketplace.placeBid(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",n.data)),n}async claimAuction(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,n,r){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!n)return u("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return a;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=n,o.DurationHours=r;let c=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(c,"marketplace:buyOrderCreated"),c}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,n,r){if(!e)return u("client","TargetUserID is required.");if(!t)return u("client","CatalogID is required.");if(!i)return u("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return a;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=n,o.RequestedBundle=r;let c=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(c,"marketplace:directTradeCreated"),c}async respondDirectTrade(e,t){if(!e)return u("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.Accept=t;let n=await this.ctx.api.marketplace.respondDirectTrade(i);return n.ok&&(t&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",n.data)),n}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return u("client","OfferID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.OfferID=e;let r=await t(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,r.data)),r}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=Kr.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Kr.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):u("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var Jr=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return u("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let n=await this.ctx.api.multiplayer.createRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",n.data),n}async joinRoom(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.JoinCode=t;let n=await this.ctx.api.multiplayer.joinRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",n.data),n}async leaveRoom(e,t={}){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let n=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",n.data),n}async claimHost(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.TargetUserID=t,n.Ban=i;let r=await this.ctx.api.multiplayer.kickMember(n);return r.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",r.data),r}async unbanMember(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.TargetUserID=t;let n=await this.ctx.api.multiplayer.unbanMember(i);return n.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",n.data),n}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return a;i.Page=e,i.PageSize=t;let n=await this.ctx.api.multiplayer.listRooms(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",n.data),n}async getRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.LastSeq=t;let n=await this.ctx.api.multiplayer.poll(i);return n.ok&&this.ctx.emitter.emit("multiplayer:polled",n.data),n}async sendSignal(e,t,i,n){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");if(!i)return u("client","SignalKind is required.");let r=this.ctx.authedRequest();if(!r)return a;r.RoomID=e,r.TargetUserID=t,r.SignalKind=i,r.Payload=n;let o=await this.ctx.api.multiplayer.sendSignal(r);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.ChatText=t;let n=await this.ctx.api.multiplayer.sendChat(i);return n.ok&&this.ctx.emitter.emit("multiplayer:chatSent",n.data),n}async setMemberState(e,t,i){if(!e)return u("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.Ready=t,n.MemberState=i;let r=await this.ctx.api.multiplayer.setMemberState(n);return r.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",r.data),r}};var Pd=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Zr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.ParentContentID=e.parentContentID,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):a}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return u("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):a}async getCreatorProfile(e,t,i){if(!e)return u("client","CreatorUserID is required.");let n=this.ctx.authedRequest();return n?(n.CreatorUserID=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getCreatorProfile(n)):a}async publish(e){if(!e.files||e.files.length===0)return u("client","At least one file is required.");let t=new Map,i=e.files.map((h,y)=>{if("sourceAssetUrl"in h)return {Role:h.role,ContentType:h.contentType,SourceAssetUrl:h.sourceAssetUrl};let V=vd(h.data,h.contentType);return t.set(y,V),{Role:h.role,ContentType:h.contentType,Size:V.size}}),n=e.thumbnail?vd(e.thumbnail.data,e.thumbnail.contentType):null,r=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&n?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:n.size}:void 0});if(!r.ok)return r;let o=r.data.Uploads??[];for(let h=0;h<o.length;h++){let y=o[h];if(!y||y.ServerCopy||!y.Url)continue;let V=t.get(h);if(!V)return u("client",`No bytes for file #${h+1}.`);let oe=await this.putBytes(y.Url,V,y.ContentType??V.type);if(!oe.ok)return oe}let c=r.data.ThumbnailUpload;if(c?.Url&&n){let h=await this.putBytes(c.Url,n,c.ContentType??n.type);if(!h.ok)return h}return this.ctx.credits.pay(h=>this.publishUploaded({CreditsConfirmationID:h,ContentID:r.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID}),e.credits)}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):a}async publishUploaded(e){if(!e.ContentID)return u("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return a;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&!i.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let n=await this.ctx.api.workshop.updateContent(i);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let n=this.ctx.authedRequest();return n?(n.ContentType=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getMyContent(n)):a}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let n=await this.ctx.api.workshop.acquire(i);return n.ok&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",n.data)),n}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let n of t.data.Files??[])if(n.Url)try{let r=await this.ctx.fetchImpl(n.Url);if(!r.ok)return u("connection",`Download failed (HTTP ${r.status}).`);i.push({role:n.Role??"main",contentType:n.ContentType??"application/octet-stream",data:await r.arrayBuffer()});}catch(r){return u("connection",`Download failed: ${r instanceof Error?r.message:String(r)}${Pd}`)}return N({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):a}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):a}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?N(!0):u("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return u("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}${Pd}`)}}contentRequest(e){if(!e)return u("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):a}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function vd(s,e){return s instanceof Blob?s:typeof s=="string"?new Blob([new TextEncoder().encode(s)],{type:e}):s instanceof Uint8Array?new Blob([s.slice().buffer],{type:e}):new Blob([s],{type:e})}var gb={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},yb=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Rb={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Td=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),Cb={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Ad=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),Sb={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},xb=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),bb={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},Db=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),Ib={Count:"Count",Sum:"Sum"},Pb=zod.z.enum(["Count","Sum"]).catch("Count"),vb={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},Tb=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),Ab={Strict:"Strict",Loose:"Loose"},wb=zod.z.enum(["Strict","Loose"]).catch("Strict"),kb=zod.z.object({Kind:Db,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),zb=zod.z.object({Type:Td,ItemType:Td.nullish(),Ref:kb.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:Ad.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()}),Mb=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Yr=zod.z.object({Mode:xb,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),Ob=zod.z.object({Read:zod.z.array(Yr).nullish(),Create:zod.z.array(Yr).nullish(),Update:zod.z.array(Yr).nullish(),Delete:zod.z.array(Yr).nullish()}),Ua=zod.z.object({Cost:pe.nullish(),Grant:pe.nullish()}),Eb=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()}),Ub=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:yb,Mode:wb.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),zb).nullish(),SortKeys:zod.z.array(Mb).nullish(),Access:Ob.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:Tb.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:Pb,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:Ad.optional()})).nullish(),Economy:zod.z.object({OnCreate:Ua.nullish(),OnUpdate:Ua.nullish(),OnDelete:Ua.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:zod.z.array(Eb).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()}),wd=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),Ub).default({})}),qb=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),kd=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),Pi=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(),qb).nullish()}),qa=zod.z.object({Item:Pi}),zd=zod.z.object({Items:zod.z.array(Pi).default([]),Missing:zod.z.array(zod.z.string()).default([])}),La=zod.z.object({Items:zod.z.array(Pi).default([]),NextCursor:zod.z.string().nullish()}),Md=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),Ba=zod.z.object({Item:Pi,AlreadyExists:zod.z.boolean().optional(),Economy:M.nullish()}),Od=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:M.nullish()}),Ed=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),Ud=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:Pi.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),qd=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),Ld=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),Bd=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({})}),Gd=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(Pi).default([])}),Lb={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 Bb=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Vd=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Fa=100,Fd=25,_d=100;function Gb(s,e,t){return {Field:s,Op:e,Value:t}}var Xr=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(a)}get(e,t,i={}){let n=rt(e)??Ki(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.get({...r,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let n=rt(e);if(n)return Promise.resolve(n);let r=[...new Set(t.filter(o=>Vd.test(o)))];return r.length?r.length>_d?Promise.resolve(u("client",`At most ${_d} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:r,Expand:i.expand})):Promise.resolve(u("client","At least one valid item id is required."))}query(e,t={},i={}){let n=rt(e)??Ga(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.query({...r,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let n=Math.max(1,i.maxItems??500),r=[],o=t.Cursor;for(;;){let c=await this.query(e,{...t,Cursor:o,Limit:t.Limit??Fa},i);if(!c.ok)return c;if(r.push(...c.data.Items),o=c.data.NextCursor??void 0,!o||r.length>=n)return N(r.slice(0,n))}}count(e,t={}){let i=rt(e)??Ga(t);return i?Promise.resolve(i):this.call(n=>this.ctx.api.dataCollections.count({...n,Collection:e,Query:t}))}create(e,t,i={}){let n=rt(e)??(i.itemID?Ki(i.itemID):null);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.create({...r,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,n={}){let r=rt(e)??Ki(t);return r?Promise.resolve(r):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:n.expectedVersion}))}set(e,t,i,n={}){return this.update(e,t,{Set:i},n)}increment(e,t,i,n=1){return this.update(e,t,{Inc:{[i]:n}})}delete(e,t,i={}){let n=rt(e)??Ki(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.delete({...r,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(u("client","Operations are empty."));if(e.length>Fd)return Promise.resolve(u("client",`At most ${Fd} operations per batch.`));let t=e.map(i=>rt(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let n=rt(e);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.getCounter({...r,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,n){let r=rt(e);return r?Promise.resolve(r):t?n>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:n})):Promise.resolve(u("client","File size must be positive.")):Promise.resolve(u("client","Field is required."))}async uploadFile(e,t,i,n={}){let r=n.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,r,i.size);if(!o.ok)return o;let c=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||r);return c.ok?o:c}async getPublicViews(e){let t=rt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return N(i);let n=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return n.ok&&this.publicViews.set(e,n.data),n}async readPublicView(e,t,i={}){let n=await this.getPublicViews(e);if(!n.ok)return n;let r=n.data.Views[t];if(!r)return u("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(r,Bd);if(!o.ok)return o;let c=o.data.Partitions[i.partition??""],h=Math.max(1,i.page??1);if(!c||h>c.Pages)return N({pointer:o.data,page:{Page:h,HasMore:false,Items:[]}});let y=await this.fetchJson(`${o.data.BaseUrl}${c.Segment}/page-${h}.json`,Gd);return y.ok?N({pointer:o.data,page:y.data}):y}getPublic(e,t){let i=rt(e)??Ki(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=rt(e)??Ga(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(a)}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?N(!0):u("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return u("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return u("connection","Internet Connection Error")}if(!i.ok)return u("server",`CDN answered ${i.status}.`);let n;try{n=await i.json();}catch{return u("server","CDN answer is not JSON.")}let r=t.safeParse(n);return r.success?N(r.data):u("server","CDN answer has an unexpected shape.")}};function rt(s){return Bb.test(s??"")?null:u("client",`Collection id '${s}' is invalid (letters, digits, '_', '-', ':').`)}function Ki(s){return Vd.test(s??"")?null:u("client",`Item id '${s}' is invalid.`)}function Ga(s){return s.Limit!=null&&(s.Limit<1||s.Limit>Fa)?u("client",`Limit must be 1..${Fa}.`):(s.Where?.length??0)>8?u("client","At most 8 filters per query."):null}var _a={Open:"Open",Declared:"Declared"},Fb=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),_b=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),Nd=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Fb).nullish(),Dimensions:zod.z.array(_b).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),Wt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Dt={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},es=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Vb={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},Nb=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),jd=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(Nb).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Va={LogEvents:"LogEvents"};function Wd(s,e=0){let t=s??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let c=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:c==="iPad"?"tablet":"phone",deviceModel:c}}let n=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(n){let c=(n[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:n[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:c&&c!=="K"&&c!=="wv"?c:void 0}}let r=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(r)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(r[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let o=/\bWindows NT (\d+\.\d+)/.exec(t);return o?{osName:"Windows",osVersion:o[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function Kd(s){let e=typeof navigator>"u"?void 0:navigator,t=Wd(e?.userAgent??"",e?.maxTouchPoints??0),i={};s.appVersion&&(i.AppVersion=s.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let n=s.locale||e?.language;return n&&(i.Language=n),i}var jb=25,Wb=3e4,Qd=1800*1e3,Hd=500,Kb=5,Qb=1e3,Hb=3600*1e3,$d="idos_analytics_queue",Na="idos_analytics_pending",ja="idos_analytics_opt_out",Jd="idos_analytics_first_open",Zd="idos_analytics_last_activity",Yd="idos_analytics_last_context",Xd="idos_analytics_owner",ts=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!es.test(e)?u("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):$b(e)?u("client",`Event name "${e}" uses a reserved prefix (${Dt.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return u("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Wt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return N(null);if(this.config()?.Enabled===false)return this.clear(),N(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return N(null);this.pending={BatchID:G(),Events:this.queue.splice(0,Dt.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=Kb)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(ja);return}this.write(ja,"1"),this.clear();}get isEnabled(){return this.read(ja)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(Xd);e&&t&&t!==e&&this.clear(),e&&this.write(Xd,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Wb),typeof window<"u"&&(window.addEventListener("visibilitychange",this.onVisibilityChange),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,typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),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(Zd)??"0");this.read(Jd)||(this.write(Jd,new Date().toISOString()),this.enqueue(Wt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Yd);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Wt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Wt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Yd,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Qd)&&this.enqueue(Wt.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=Qd&&this.enqueue(Wt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,n){if(!this.isEnabled||this.disabledByServer)return N(null);let r=this.config();if(r?.Enabled===false)return N(null);if(n&&r?.AutomaticEvents===false)return N(null);if(r?.Events?.[e]?.Blocked)return u("client",`Event "${e}" is blocked by the title.`);if(!n&&r?.EventNaming?.toLowerCase()===_a.Declared.toLowerCase()&&!r.Events?.[e])return u("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return u("client","value must be a finite number.");let o=Jb(t);if(o.error)return u("client",o.error);this.restore();let c={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(c.Params=o.params),i!==void 0&&(c.Value=i),this.queue.push(c),this.queue.length>Hd&&this.queue.splice(0,this.queue.length-Hd),this.touch(),this.persist(),this.started&&this.queue.length>=jb&&this.flush(),N(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},Qb));}dropStale(){let e=Date.now()-(Dt.maxEventAgeMs-Hb);this.queue=this.queue.filter(t=>{let i=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(i)||i>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=Kd({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson($d);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(Na);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson($d,this.queue),this.pending?this.writeJson(Na,this.pending):this.remove(Na);}touch(){this.write(Zd,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.platform.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.platform.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.platform.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 $b(s){let e=s.toLowerCase();return Dt.reservedPrefixes.some(t=>e.startsWith(t))}function Jb(s){if(!s)return {};let e=Object.keys(s);if(e.length===0)return {};if(e.length>Dt.maxParams)return {error:`Too many parameters: ${e.length}, max ${Dt.maxParams}.`};let t={};for(let i of e){if(!es.test(i))return {error:`Invalid parameter name "${i}".`};let n=s[i];typeof n=="string"?t[i]=n.length>Dt.maxStringValueLength?n.slice(0,Dt.maxStringValueLength):n:typeof n=="number"?Number.isFinite(n)&&(t[i]=n):typeof n=="boolean"&&(t[i]=n);}return {params:t}}var Zb="idos_experiments",is=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let n=this.getParams(e)[t];if(n===void 0)return i;if(typeof i=="number"){let r=Number(n);return n.trim()!==""&&Number.isFinite(r)?r:i}if(typeof i=="boolean"){let r=n.trim().toLowerCase();return r==="true"||r==="1"?true:r==="false"||r==="0"?false:i}return n}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 n of e.Experiments??[])n?.ExperimentID&&t.set(n.ExperimentID,n);let i=[];for(let[n,r]of t){let o=this.views.get(n);(!o||o.VariantID!==r.VariantID||o.Status!==r.Status)&&i.push(r);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.platform.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.platform.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${Zb}:${this.ctx.settings.titleID}`}};function Kt(s,e,t,i){let r=`api/v2/${s&&s.length>0?s:"0"}/Client/${e}/${t}`;return i==null?r:`${r}/${i}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Kt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,n){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...n,ticket:t.ClientSessionTicket})}};var ns=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Va.LogEvents,e,jd,{silent:true})}};var Yb=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(),Xb={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},eD=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),tD=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:Re.nullish(),Gate:Z.nullish(),Variants:zod.z.array(Yb).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(eD).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),eh=zod.z.object({Experiments:zod.z.record(zod.z.string(),tD).nullish()}).passthrough(),iD={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},nD=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(),th=zod.z.object({Experiments:zod.z.array(nD).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),Wa={GetExperiments:"GetExperiments"};var rs=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Wa.GetExperiments,e,th)}};var ih=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:p.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:p,PlayAccess:jt.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:p.nullish()}),nh=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:p,RefreshToken:zod.z.string(),RefreshTokenExpiration:p.nullish(),PlayAccess:jt.nullish()}),rD=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),rh=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:Ni.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:rD.nullish()}).passthrough(),sh=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:p.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:jt.nullish()}).passthrough(),oh=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:p.nullish(),PlayAccess:jt.nullish()}).passthrough(),ah=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Ge=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:p.nullish()}),lh=zod.z.object({Message:zod.z.string(),ExpiresAt:p}),Le={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 ss=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Kt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,ih,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Le.RefreshSession),e,nh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Le.GetAuthOptions),e,rh,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Kt(this.ctx.settings.titleID,"Authentication",Le.LinkWallet,e.UserID??""),e,sh,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Kt(this.ctx.settings.titleID,"Authentication",Le.UnlinkWallet,e.UserID??""),e,oh,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Le.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Le.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Le.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Le.LoginWithGoogle,e)}loginWithApple(e){return this.login(Le.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Le.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(Le.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Le.RegisterWithEmail),e,ah,{ticket:null})}confirmEmailRegistration(e){return this.login(Le.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Le.ResendVerificationCode),e,Ge,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Le.RequestWalletChallenge),e,lh,{ticket:null})}loginWithWallet(e){return this.login(Le.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Le.ForgotPassword),e,Ge,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Le.ResetPassword),e,Ge,{ticket:null})}};var sD={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},uh=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),oD=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),ch=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),oD).nullish(),MissingKeyMode:uh.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),aD=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),ph=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:aD.nullish()}).passthrough(),os={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},lD=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),dh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:uh.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(lD).nullish()}).passthrough(),hh=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 Ka=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:ph.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(s=>s),mh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(s=>s),fh=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(s=>s),gh=zod.z.object({}).passthrough().transform(s=>s),yh=zod.z.object({}).passthrough().transform(s=>s),Rh=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:p.nullish(),LastActiveAt:p.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),Ch=zod.z.object({Username:zod.z.string()}),pt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var as=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(pt.GetClientState,e,Ka)}getClientStateExcept(e){return this.send(pt.GetClientStateExcept,e,Ka)}getStateVersions(e){return this.send(pt.GetStateVersions,e,mh)}getUserState(e){return this.send(pt.GetUserState,e,fh)}getInventory(e){return this.send(pt.GetInventory,e,gh)}getEventTokens(e){return this.send(pt.GetEventTokens,e,yh)}getUsageTime(e){return this.send(pt.GetUsageTime,e,Rh)}addUsageTime(e){return this.send(pt.AddUsageTime,e,Ge,{silent:true})}deleteUserAccount(e){return this.send(pt.DeleteUserAccount,e,Ge)}changeUsername(e){return this.send(pt.ChangeUsername,e,Ch)}};var ls=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(Vi.Convert,e,Lp)}spend(e){return this.send(Vi.Spend,e,Gp)}cryptoConvert(e){return this.send(Vi.CryptoConvert,e,Bp)}};var uD=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),Qa=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:M.nullish(),FodderConsumed:zod.z.array(uD).nullish()}),Sh=zod.z.array(we(Qa)),us={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},cD={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},pD=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),dD={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},hD=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),mD=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),fD=zod.z.object({Networks:zod.z.record(zod.z.string(),mD).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),gD=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(),yD=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(),RD=zod.z.object({ValuationMode:pD.nullish(),WeightCurve:Ne.nullish(),Selection:hD.nullish()}).passthrough(),CD=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:Ne.nullish(),FlatBonusCurve:Ne.nullish(),PercentBonusCurve:Ne.nullish(),PowerCurve:Ne.nullish(),Fodder:RD.nullish()}).passthrough(),SD=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),xD=zod.z.object({ItemID:zod.z.string(),CatalogID:zod.z.string(),ItemClass:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsStackable:zod.z.boolean().nullish(),IsTradable:zod.z.boolean().nullish(),Weight:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),NFT:fD.nullish(),Stats:gD.nullish(),Equipment:yD.nullish(),Upgrade:CD.nullish(),Metadata:SD.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),bD=zod.z.object({Items:zod.z.record(zod.z.string(),xD).nullish()}).passthrough(),cs=zod.z.object({Catalogs:zod.z.record(zod.z.string(),bD).nullish()}).passthrough();function Pe(s){return zod.z.unknown().transform((e,t)=>{let i=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(i!=null){let r=fe.safeParse(i);return r.success?{...e,CreditsConfirmation:r.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${r.error.message}`}),zod.z.NEVER)}let n=s.safeParse(e);return n.success?n.data:(t.addIssue({code:"custom",message:n.error.message}),zod.z.NEVER)})}var ps=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(us.UpgradeLevel,e,Pe(Qa))}upgradeLevelsBatch(e){return this.send(us.UpgradeLevelsBatch,e,Sh)}};var ds=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(zt.Purchase,e,Oo)}purchaseBatch(e){return this.send(zt.PurchaseBatch,e,bu)}getDefinitions(e){return this.send(zt.GetDefinitions,e,kn)}getUserState(e){return this.send(zt.GetUserState,e,Du)}getStorefront(e){return this.send(zt.GetStorefront,e,zn)}getCreditsConfirmation(e){return this.send(zt.GetCreditsConfirmation,e,fe)}getCreditsBalance(e){return this.send(zt.GetCreditsBalance,e,xu)}};var DD={Apple:"Apple",Google:"Google"},hs=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(),ms=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),hs).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(s=>s),ID=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:ce.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$a=zod.z.object({Definitions:zod.z.record(zod.z.string(),ID).nullish()}).passthrough(),xh=zod.z.object({Premium:$a.nullish()}),bh=zod.z.object({ServerTimeUtc:p.nullish(),Premium:ms.nullish()}),fs=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),Premium:ms.nullish(),Subscription:hs.nullish(),Resources:M.nullish()}),ti={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var PD={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},vD=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Dh=zod.z.object({StartUtc:p.nullish(),EndUtc:p.nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Ja=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),TD=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),AD=zod.z.object({Rewards:Q.nullish(),Rules:Q.nullish(),Refund:Q.nullish()}).passthrough(),wD=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:vD.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:Dh.nullish(),Refund:Ja.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:TD.nullish(),Presets:AD.nullish()}).passthrough(),kD=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(),zD=zod.z.object({Rewards:H.nullish()}).passthrough(),MD=zod.z.object({Rules:Dh.nullish()}).passthrough(),OD=zod.z.object({Refund:Ja.nullish()}).passthrough(),ED=zod.z.object({Rewards:zod.z.record(zod.z.string(),zD).nullish(),Rules:zod.z.record(zod.z.string(),MD).nullish(),Refund:zod.z.record(zod.z.string(),OD).nullish()}).passthrough(),UD=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(),qD=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),wD).nullish(),Stores:zod.z.record(zod.z.string(),kD).nullish(),Presets:ED.nullish(),Validation:UD.nullish(),Refund:Ja.nullish()}).passthrough(),Ih=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:p.nullish(),LastPurchasedAt:p.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Ph=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:p.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:p.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:p.nullish()}).passthrough(),LD=zod.z.object({Products:zod.z.record(zod.z.string(),Ih).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Ph).nullish(),LastRefundCheckAt:p.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:p.nullish(),LastPurchaseAt:p.nullish()}).passthrough(),BD=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(),vh=zod.z.object({ServerTimeUtc:p,Purchase:qD.nullish(),Availability:zod.z.array(BD).nullish()}),Th=zod.z.object({ServerTimeUtc:p,Purchase:LD.nullish()}),GD={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},FD=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Za=zod.z.object({ServerTimeUtc:p,Store:Xi.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:FD.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish(),ProductState:Ih.nullish(),Premium:ms.nullish(),Subscription:hs.nullish(),SubscriptionMirror:Ph.nullish()}).passthrough(),Ah=zod.z.object({ServerTimeUtc:p,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:p.nullish()}).passthrough(),wh=Ct(Za),ii={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var gs=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(ii.GetDefinitions,e,vh)}getUserState(e){return this.send(ii.GetUserState,e,Th)}validatePurchase(e){return this.send(ii.ValidatePurchase,e,Za)}validatePurchasesBatch(e){return this.send(ii.ValidatePurchasesBatch,e,wh)}createTelegramInvoice(e){return this.send(ii.CreateTelegramInvoice,e,Ah)}};var _D=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),kh=zod.z.object({Reward:H.nullish(),Weight:zod.z.number().nullish(),AmountRange:_D.nullish()}).passthrough(),vi=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(kh).nullish()}).passthrough(),Ti=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(kh).nullish()}).passthrough(),VD=zod.z.object({RewardSlots:zod.z.array(vi).nullish()}).passthrough(),ND=zod.z.object({PityRules:zod.z.array(Ti).nullish()}).passthrough(),ys=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),VD).nullish(),PityPresets:zod.z.record(zod.z.string(),ND).nullish()}).passthrough();var jD=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),zh=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish(),Results:zod.z.array(M).nullish(),TriggeredPity:zod.z.array(jD).nullish()}),WD=zod.z.object({RewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),KD=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:W.nullish()}).passthrough(),QD=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ce.nullish(),RewardSlots:zod.z.array(vi).nullish(),PityRules:zod.z.array(Ti).nullish(),Presets:WD.nullish(),RewardMultiplier:tn.nullish(),SupplyLimits:zod.z.array(KD).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),HD=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Ya=zod.z.object({Definitions:zod.z.record(zod.z.string(),QD).nullish(),RewardPools:ys.nullish(),Settings:HD.nullish()}).passthrough(),Mh=zod.z.object({LootboxDefinitions:Ya.nullish()}),Rs={GetDefinitions:"GetDefinitions",Open:"Open"};var Cs=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(Rs.GetDefinitions,e,Mh)}open(e){return this.send(Rs.Open,e,Pe(zh))}};var $D=zod.z.object({}).passthrough().transform(s=>s),JD=zod.z.object({}).passthrough().transform(s=>s),ZD=zod.z.object({}).passthrough().transform(s=>s),YD=zod.z.object({}).passthrough().transform(s=>s),XD=zod.z.object({}).passthrough().transform(s=>s),eI=zod.z.object({}).passthrough().transform(s=>s),Oh=zod.z.object({ServerTimeUtc:p,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:$D,Resources:M.nullish(),Inventory:K.nullish()}),Eh=zod.z.object({ServerTimeUtc:p,AccrualID:zod.z.string(),AccruedSeconds:W.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:JD,Resources:M.nullish(),Inventory:K.nullish()}),Uh=zod.z.object({ServerTimeUtc:p,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:ZD,Resources:M.nullish(),Inventory:K.nullish()}),qh=zod.z.object({ServerTimeUtc:p,ClaimID:zod.z.string(),ClaimState:YD,Resources:M.nullish(),Inventory:K.nullish()}),tI={None:"None",Ad:"Ad",Vip:"Vip"},Lh=zod.z.object({ServerTimeUtc:p,WindowID:zod.z.string(),Boost:zod.z.string().nullish(),BaseAmount:W.nullish(),Multiplier:zod.z.number().nullish(),Granted:W.nullish(),WindowState:XD,Resources:M.nullish(),Inventory:K.nullish()}),Bh=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:W.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),iI=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),nI=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:H.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Qi=zod.z.object({Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Xa=zod.z.object({Availability:Q.nullish()}).passthrough(),rI=zod.z.object({Availability:zod.z.record(zod.z.string(),Qi).nullish()}).passthrough(),sI=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(nI).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:Qi.nullish(),Presets:Xa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),oI=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),aI=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(oI).nullish()}).passthrough(),lI=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Qi.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),uI=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:aI.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:lI.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),cI=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:H.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),pI=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(cI).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Qi.nullish(),Presets:Xa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),dI=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(),hI=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:H.nullish(),PremiumLimitOverrides:zod.z.array(dI).nullish(),Availability:Qi.nullish(),Presets:Xa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),mI=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(),el=zod.z.object({TierRewards:iI.nullish(),MilestoneRewardMultiplier:tn.nullish(),DailyCalendars:zod.z.record(zod.z.string(),sI).nullish(),IdleAccruals:zod.z.record(zod.z.string(),uI).nullish(),Comebacks:zod.z.record(zod.z.string(),pI).nullish(),Claims:zod.z.record(zod.z.string(),hI).nullish(),Windows:zod.z.record(zod.z.string(),mI).nullish(),Presets:rI.nullish()}).passthrough(),Gh=zod.z.object({RewardDefinitions:el.nullish()}),Fh=zod.z.object({Rewards:eI.nullish()}),It={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var Ss=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(It.GetRewardDefinitions,e,Gh)}getUserRewardsState(e){return this.send(It.GetUserRewardsState,e,Fh)}getMilestoneRewardMultiplier(e){return this.send(It.GetMilestoneRewardMultiplier,e,Bh)}claimDailyReward(e){return this.send(It.ClaimDailyReward,e,Oh)}collectIdleAccrual(e){return this.send(It.CollectIdleAccrual,e,Eh)}claimComebackReward(e){return this.send(It.ClaimComebackReward,e,Uh)}claimReward(e){return this.send(It.ClaimReward,e,qh)}claimRewardWindow(e){return this.send(It.ClaimRewardWindow,e,Lh)}};var xs=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(at.GetTutorialDefinitions,e,Xl)}getUserTutorialState(e){return this.send(at.GetUserTutorialState,e,sn)}startFlow(e){return this.send(at.StartFlow,e,Lt)}reportStepShown(e){return this.send(at.ReportStepShown,e,Lt)}completeStep(e){return this.send(at.CompleteStep,e,Lt)}completeStepsBatch(e){return this.send(at.CompleteStepsBatch,e,iu)}skipStep(e){return this.send(at.SkipStep,e,Lt)}skipFlow(e){return this.send(at.SkipFlow,e,Lt)}claimFlowReward(e){return this.send(at.ClaimFlowReward,e,tu)}resetFlow(e){return this.send(at.ResetFlow,e,Lt)}};var fI={Open:"Open",Application:"Application"},gI=zod.z.enum(["Open","Application"]).catch("Open"),yI={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},_h=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),RI={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},tl=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),CI={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var ni={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},SI=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(),Vh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:gI.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:_h.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(SI).nullish()}).passthrough(),xI=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(),bI=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:tl.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(),xI).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),DI=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:tl.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),Nh=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(bI).nullish(),Payouts:zod.z.array(DI).nullish()}).passthrough(),jh=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:tl.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),II=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),PI=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(II).nullish()}).passthrough(),vI=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(),Wh=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:_h.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(vI).nullish()}).passthrough(),TI=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),AI=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(TI).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(),Kh=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:PI.nullish(),SolanaSignature:AI.nullish(),StateDelta:Ii.nullish()}).passthrough();var bs=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(ni.GetCommunityMarketingState,e,Vh)}getEarnings(e){return this.send(ni.GetEarnings,e,Nh)}claim(e){return this.send(ni.Claim,e,jh)}checkJoinEligibility(e){return this.send(ni.CheckJoinEligibility,e,Wh)}withdrawCryptoReward(e){return this.send(ni.WithdrawCryptoReward,e,Kh)}};var Ds=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send($e.GetChatDefinitions,e,Gu)}getChannels(e){return this.send($e.GetChannels,e,Nn)}poll(e){return this.send($e.Poll,e,Fu)}getHistory(e){return this.send($e.GetHistory,e,_u)}getConversations(e){return this.send($e.GetConversations,e,ju)}sendMessage(e){return this.send($e.SendMessage,e,Vu)}openDirectChannel(e){return this.send($e.OpenDirectChannel,e,Nu)}markRead(e){return this.send($e.MarkRead,e,xi)}joinChannel(e){return this.send($e.JoinChannel,e,xi)}leaveChannel(e){return this.send($e.LeaveChannel,e,xi)}reportMessage(e){return this.send($e.ReportMessage,e,Wu)}ignoreUser(e){return this.send($e.IgnoreUser,e,xi)}unignoreUser(e){return this.send($e.UnignoreUser,e,xi)}};var Is=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(bi.GetPushConfig,e,Hu)}subscribePush(e){return this.send(bi.SubscribePush,e,_o)}unsubscribePush(e){return this.send(bi.UnsubscribePush,e,Ge)}getPushSubscriptions(e){return this.send(bi.GetPushSubscriptions,e,$u)}};var Ps=class extends B{constructor(e){super(e,"Localization");}send(e,t,i,n){let r=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${r}:${t.Locale}`:r,...n})}getLocalizationManifest(e){return this.send(os.GetLocalizationManifest,e,dh)}getLocalizationTable(e){return this.send(os.GetLocalizationTable,e,hh)}};var vs=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(ft.GetQuestDefinitions,e,rn)}getUserQuestState(e){return this.send(ft.GetUserQuestState,e,_l)}refreshQuestCycles(e){return this.send(ft.RefreshQuestCycles,e,Ge)}claimQuestReward(e){return this.send(ft.ClaimQuestReward,e,go)}claimQuestRewardsBatch(e){return this.send(ft.ClaimQuestRewardsBatch,e,jl)}claimMilestoneReward(e){return this.send(ft.ClaimMilestoneReward,e,yo)}claimMilestoneRewardsBatch(e){return this.send(ft.ClaimMilestoneRewardsBatch,e,Wl)}claimGroupCompletionReward(e){return this.send(ft.ClaimGroupCompletionReward,e,Vl)}addQuestProgress(e){return this.send(ft.AddQuestProgress,e,Nl)}};var Ts=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ut.GetActiveEvents,e,Jn)}getDefinitions(e){return this.send(ut.GetDefinitions,e,$n)}getUserLteState(e){return this.send(ut.GetUserLteState,e,Xu)}grantTokens(e){return this.send(ut.GrantTokens,e,M)}spendTokens(e){return this.send(ut.SpendTokens,e,jo)}claimMilestone(e){return this.send(ut.ClaimMilestone,e,Wo)}claimMilestonesBatch(e){return this.send(ut.ClaimMilestonesBatch,e,Ko)}claimAllMilestones(e){return this.send(ut.ClaimAllMilestones,e,Ko)}spendTokensBatch(e){return this.send(ut.SpendTokensBatch,e,ec)}grantTokensBatch(e){return this.send(ut.GrantTokensBatch,e,tc)}};var As=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(je.GetDefinitions,e,nr)}getLeaderboard(e){return this.send(je.GetLeaderboard,e,Li)}getMyProgress(e){return this.send(je.GetMyProgress,e,Yn)}submitScore(e){return this.send(je.SubmitScore,e,Xn)}submitScoreFromSource(e){return this.send(je.SubmitScoreFromSource,e,Xn)}claimCycleReward(e){return this.send(je.ClaimCycleReward,e,er)}claimMilestone(e){return this.send(je.ClaimMilestone,e,tr)}getFriendsLeaderboard(e){return this.send(je.GetFriendsLeaderboard,e,Li)}getLeaderboardsBatch(e){return this.send(je.GetLeaderboardsBatch,e,rc)}getProgressBatch(e){return this.send(je.GetProgressBatch,e,ir)}claimCycleRewardsBatch(e){return this.send(je.ClaimCycleRewardsBatch,e,sc)}claimMilestonesBatch(e){return this.send(je.ClaimMilestonesBatch,e,oc)}submitScoresBatch(e){return this.send(je.SubmitScoresBatch,e,ac)}claimAllRewardsBatch(e){return this.send(je.ClaimAllRewardsBatch,e,lc)}getOverviewBatch(e){return this.send(je.GetOverviewBatch,e,uc)}};var ws=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Ft.GetDefinitions,e,or)}getActiveSeason(e){return this.send(Ft.GetActiveSeason,e,sr)}getUserState(e){return this.send(Ft.GetUserState,e,Qo)}grantStatusTokens(e){return this.send(Ft.GrantStatusTokens,e,hc)}claimTierReward(e){return this.send(Ft.ClaimTierReward,e,Ho)}claimTierRewardsBatch(e){return this.send(Ft.ClaimTierRewardsBatch,e,mc)}};var ks=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(ti.GetDefinitions,e,xh)}getUserState(e){return this.send(ti.GetUserState,e,bh)}activateTrial(e){return this.send(ti.ActivateTrial,e,fs)}purchaseItemOrCurrency(e){return this.send(ti.PurchaseWithResources,e,Pe(fs))}purchaseRealMoney(e){return this.send(ti.PurchaseRealMoney,e,fs)}};var zs=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(We.GetCharacterDefinitions,e,cr)}getUserCharacters(e){return this.send(We.GetUserCharacters,e,Sc)}unlockCharacter(e){return this.send(We.UnlockCharacter,e,Pe(Yo))}upgradeStatLevel(e){return this.send(We.UpgradeStatLevel,e,Pe(Jo))}upgradeCharacterLevel(e){return this.send(We.UpgradeCharacterLevel,e,Pe(Zo))}equipItems(e){return this.send(We.EquipItems,e,xc)}unequipItems(e){return this.send(We.UnequipItems,e,bc)}unequipAllCharacters(e){return this.send(We.UnequipAllCharacters,e,Dc)}unlockCharactersBatch(e){return this.send(We.UnlockCharactersBatch,e,Ac)}upgradeCharacterLevelsBatch(e){return this.send(We.UpgradeCharacterLevelsBatch,e,wc)}upgradeStatLevelsBatch(e){return this.send(We.UpgradeStatLevelsBatch,e,kc)}unlockSkin(e){return this.send(We.UnlockSkin,e,Pe(Ic))}equipSkin(e){return this.send(We.EquipSkin,e,Pc)}unequipSkin(e){return this.send(We.UnequipSkin,e,vc)}getCharacterSkins(e){return this.send(We.GetCharacterSkins,e,Tc)}};var Ms=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(bt.CreateMatch,e,cd)}updateMatch(e){return this.send(bt.UpdateMatch,e,pd)}cancelMatch(e){return this.send(bt.CancelMatch,e,dd)}instantBattle(e){return this.send(bt.InstantBattle,e,hd)}saveStrategy(e){return this.send(bt.SaveStrategy,e,Ge)}getMyMatches(e){return this.send(bt.GetMyMatches,e,Ta)}getAvailableMatches(e){return this.send(bt.GetAvailableMatches,e,Ta)}getDefinitions(e){return this.send(bt.GetDefinitions,e,yd)}};var wI={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Qh=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),kI={None:"None",Min:"Min",Average:"Average",Max:"Max"},zI=zod.z.enum(["None","Min","Average","Max"]).catch("None"),MI={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},OI=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),EI={Clamp:"Clamp",Reject:"Reject"},UI=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),qI=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),LI=zod.z.object({Index:zod.z.number().nullish(),BurnedItemIDs:zod.z.array(zod.z.string()).nullish(),RolledCollectionID:zod.z.string().nullish(),UsedCollections:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Output:ho.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(qI).nullish()}),Hh=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,Type:Qh.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:M.nullish(),Inventory:K.nullish(),Results:zod.z.array(LI).nullish()}),BI=zod.z.object({CraftID:zod.z.string().nullish(),Type:Qh.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:ce.nullish(),OutputLevelMode:zI.nullish(),InputSelection:OI.nullish(),OutputLevelOverflow:UI.nullish()}).passthrough(),il=zod.z.object({Definitions:zod.z.record(zod.z.string(),BI).nullish()}).passthrough(),$h=zod.z.object({ServerTimeUtc:p.nullish(),CraftDefinitions:il.nullish()}),Os={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Es=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Os.GetDefinitions,e,$h)}craft(e){return this.send(Os.Craft,e,Pe(Hh))}};var GI=2e5,Us=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,Pe(mr),{timeoutMs:GI,autoRetry:false})}readGeneration(e,t){return this.send(e,t,mr,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Be.GetDefinitions,e,Gc)}generateText(e){return this.generate(Be.GenerateText,e)}getText(e){return this.readGeneration(Be.GetText,e)}generateImage(e){return this.generate(Be.GenerateImage,e)}editImage(e){return this.generate(Be.EditImage,e)}getImage(e){return this.readGeneration(Be.GetImage,e)}generateVideo(e){return this.generate(Be.GenerateVideo,e)}getVideo(e){return this.readGeneration(Be.GetVideo,e)}generateAudio(e){return this.generate(Be.GenerateAudio,e)}getAudio(e){return this.readGeneration(Be.GetAudio,e)}generateMusic(e){return this.generate(Be.GenerateMusic,e)}getMusic(e){return this.readGeneration(Be.GetMusic,e)}generateFromTemplate(e){return this.generate(Be.GenerateFromTemplate,e)}generateThreeD(e){return this.generate(Be.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Be.GetThreeD,e)}listGenerations(e){return this.send(Be.ListGenerations,e,Bc)}getGeneration(e){return this.readGeneration(Be.GetGeneration,e)}};var FI={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},_I=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),Jh=zod.z.object({}).passthrough().transform(s=>s),Ai=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()}),Zh=zod.z.object({GrantedCollectibles:zod.z.array(Ai).nullish(),DuplicateCollectibles:zod.z.array(Ai).nullish(),CollectionCurrencyEarned:W.nullish()}),Yh=zod.z.object({CreditsConfirmation:fe.nullish(),OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(Zh).nullish(),GrantedCollectibles:zod.z.array(Ai).nullish(),DuplicateCollectibles:zod.z.array(Ai).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Xh=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(Zh).nullish(),GrantedCollectibles:zod.z.array(Ai).nullish(),DuplicateCollectibles:zod.z.array(Ai).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),em=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),nl=zod.z.object({SetID:zod.z.string(),Resources:M.nullish(),Inventory:K.nullish()}),tm=zod.z.array(we(nl)),im=zod.z.object({Resources:M.nullish(),Inventory:K.nullish()}),VI=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:qe.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:_I.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RespondedAtUtc:p.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),nm=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:p.nullish(),Resources:M.nullish()}),rm=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),sm=zod.z.object({OfferID:zod.z.string(),ReceivedCollectibleID:zod.z.string().nullish(),ReceivedIsSpecial:zod.z.boolean().nullish(),SentCollectibleID:zod.z.string().nullish(),SentCollectibleIsSpecial:zod.z.boolean().nullish(),Transfer:zod.z.unknown().nullish()}),om=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),rl=zod.z.object({Offers:zod.z.array(VI).nullish()}),NI=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(),jI=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(NI).nullish(),SetCompletionReward:H.nullish()}).passthrough(),WI=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(jI).nullish(),GrandPrize:H.nullish()}).passthrough(),am=zod.z.object({BonusRewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),KI=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:ce.nullish(),BonusRewardSlots:zod.z.array(vi).nullish(),PityRules:zod.z.array(Ti).nullish(),Presets:am.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(),QI=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),HI=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(vi).nullish(),PityRules:zod.z.array(Ti).nullish(),Presets:am.nullish(),Tier:zod.z.number().nullish()}).passthrough(),$I=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),JI=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),qs=zod.z.object({Collections:zod.z.record(zod.z.string(),WI).nullish(),PackTypes:zod.z.record(zod.z.string(),KI).nullish(),CollectionChests:zod.z.array(HI).nullish(),DuplicateConversions:zod.z.array(QI).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array($I).nullish(),RewardPools:ys.nullish(),Settings:JI.nullish()}).passthrough(),Ke={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var Ls=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ke.GetDefinitions,e,qs)}getUserState(e){return this.send(Ke.GetUserState,e,Jh)}openPack(e){return this.send(Ke.OpenPack,e,Pe(Yh))}openCollectionChest(e){return this.send(Ke.OpenCollectionChest,e,Xh)}useCollectibleJoker(e){return this.send(Ke.UseCollectibleJoker,e,em)}claimSetReward(e){return this.send(Ke.ClaimSetReward,e,nl)}claimSetRewardsBatch(e){return this.send(Ke.ClaimSetRewardsBatch,e,tm)}claimGrandPrize(e){return this.send(Ke.ClaimGrandPrize,e,im)}sendTradeOffer(e){return this.send(Ke.SendTradeOffer,e,nm)}cancelTradeOffer(e){return this.send(Ke.CancelTradeOffer,e,rm)}acceptTradeOffer(e){return this.send(Ke.AcceptTradeOffer,e,sm)}declineTradeOffer(e){return this.send(Ke.DeclineTradeOffer,e,om)}getMyTradeOffers(e){return this.send(Ke.GetMyTradeOffers,e,rl)}getIncomingTradeOffers(e){return this.send(Ke.GetIncomingTradeOffers,e,rl)}};var Bs=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(gt.GetDefinitions,e,Rr)}getActiveEvent(e){return this.send(gt.GetActiveEvent,e,Vc)}getUserState(e){return this.send(gt.GetUserState,e,yr)}getGroupState(e){return this.send(gt.GetGroupState,e,ra)}joinOrCreateGroup(e){return this.send(gt.JoinOrCreateGroup,e,ra)}spin(e){return this.send(gt.Spin,e,Pe(jc))}claimObjectReward(e){return this.send(gt.ClaimObjectReward,e,sa)}claimGrandPrize(e){return this.send(gt.ClaimGrandPrize,e,sa)}leaveGroup(e){return this.send(gt.LeaveGroup,e,Wc)}};var Gs=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(xt.GetDefinition,e,ip)}getUserState(e){return this.send(xt.GetUserState,e,np)}getActiveDeals(e){return this.send(xt.GetActiveDeals,e,xr)}dismissDeal(e){return this.send(xt.DismissDeal,e,sp)}executeNode(e){return this.send(xt.ExecuteNode,e,Pe(rp))}recordShow(e){return this.send(xt.RecordShow,e,op)}claimMilestone(e){return this.send(xt.ClaimMilestone,e,ap)}claimMilestonesBatch(e){return this.send(xt.ClaimMilestonesBatch,e,lp)}};var ZI=zod.z.object({}).passthrough().transform(s=>s),YI=zod.z.object({FeatureKey:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Rate:zod.z.number().nullish(),Basis:zod.z.string().nullish(),SourceCurrencyID:zod.z.string().nullish(),TargetCurrencyID:zod.z.string().nullish(),MinSourceAmount:zod.z.number().nullish(),MaxRewardPerOperation:zod.z.number().nullish(),Limits:Se.nullish()}).passthrough(),sl=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:zod.z.record(zod.z.string(),_e).nullish(),SpendRewards:zod.z.array(YI).nullish(),Qualification:zod.z.object({}).passthrough().transform(s=>s).nullish()}).passthrough(),ol=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(),lm=zod.z.object({ReferralDefinitions:sl.nullish()}).passthrough(),um=zod.z.object({Referral:ZI.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:ol.nullish()}).passthrough(),cm=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:ol.nullish()}).passthrough(),pm=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),QualificationPending:zod.z.boolean().nullish(),Qualification:ol.nullish()}).passthrough(),al=zod.z.object({RewardID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}).passthrough(),dm=Ct(al),Qt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var Fs=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Qt.GetDefinitions,e,lm)}getUserState(e){return this.send(Qt.GetUserState,e,um)}activateReferralCode(e){return this.send(Qt.ActivateReferralCode,e,pm)}claimInviteReward(e){return this.send(Qt.ClaimInviteReward,e,al)}claimInviteRewardsBatch(e){return this.send(Qt.ClaimInviteRewardsBatch,e,dm)}checkQualification(e){return this.send(Qt.CheckQualification,e,cm)}};var _s=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(nt.GetDefinitions,e,hp)}getMessages(e){return this.send(nt.GetMessages,e,mp)}getUnreadCount(e){return this.send(nt.GetUnreadCount,e,Ir)}readMessages(e){return this.send(nt.ReadMessages,e,la)}claimReward(e){return this.send(nt.ClaimReward,e,Pr)}claimRewardsBatch(e){return this.send(nt.ClaimRewardsBatch,e,Pr)}claimAll(e){return this.send(nt.ClaimAll,e,Pr)}deleteMessages(e){return this.send(nt.DeleteMessages,e,la)}sendGift(e){return this.send(nt.SendGift,e,fp)}sendTransfer(e){return this.send(nt.SendTransfer,e,gp)}getGiftStatus(e){return this.send(nt.GetGiftStatus,e,yp)}};var Vs=class extends B{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Tr.RequestAdPermit,e,Rp)}completeView(e){return this.send(Tr.CompleteView,e,Cp)}};var Ns=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(xe.GetFriendsList,e,Gi)}getIncomingRequests(e){return this.send(xe.GetIncomingRequests,e,Gi)}getOutgoingRequests(e){return this.send(xe.GetOutgoingRequests,e,Gi)}getRecommendedFriends(e){return this.send(xe.GetRecommendedFriends,e,Gi)}sendFriendRequest(e){return this.send(xe.SendFriendRequest,e,Fi)}acceptFriendRequest(e){return this.send(xe.AcceptFriendRequest,e,Fi)}declineFriendRequest(e){return this.send(xe.DeclineFriendRequest,e,Fi)}removeFriend(e){return this.send(xe.RemoveFriend,e,Fi)}getInbox(e){return this.send(xe.GetInbox,e,xp)}markInboxSeen(e){return this.send(xe.MarkInboxSeen,e,_i)}getInboxUnread(e){return this.send(xe.GetInboxUnread,e,_i)}follow(e){return this.send(xe.Follow,e,Nt)}unfollow(e){return this.send(xe.Unfollow,e,Nt)}getFollowers(e){return this.send(xe.GetFollowers,e,kr)}getFollowing(e){return this.send(xe.GetFollowing,e,kr)}block(e){return this.send(xe.Block,e,Nt)}unblock(e){return this.send(xe.Unblock,e,Nt)}getBlocked(e){return this.send(xe.GetBlocked,e,kr)}react(e){return this.send(xe.React,e,Nt)}unreact(e){return this.send(xe.Unreact,e,Nt)}getMyReactions(e){return this.send(xe.GetMyReactions,e,Dp)}getEntityStates(e){return this.send(xe.GetEntityStates,e,bp)}addComment(e){return this.send(xe.AddComment,e,zr)}editComment(e){return this.send(xe.EditComment,e,zr)}deleteComment(e){return this.send(xe.DeleteComment,e,Pp)}getComments(e){return this.send(xe.GetComments,e,Ip)}report(e){return this.send(xe.Report,e,vp)}};var XI={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var ri=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),eP=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:ce.nullish(),Effect:ri.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(),js=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),ll=zod.z.object({Availability:Q.nullish(),Effects:Q.nullish()}).passthrough(),tP=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(ri).nullish(),Availability:js.nullish(),Presets:ll.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),iP=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(ri).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),nP=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(iP).nullish(),Availability:js.nullish(),Presets:ll.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rP=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(ot).nullish(),Effects:zod.z.array(ri).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:js.nullish(),Presets:ll.nullish()}).passthrough(),sP=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),oP=zod.z.object({Effects:zod.z.array(ri).nullish()}).passthrough(),aP=zod.z.object({Availability:zod.z.record(zod.z.string(),js).nullish(),Effects:zod.z.record(zod.z.string(),oP).nullish()}).passthrough(),lP=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),sP).nullish()}).passthrough(),Ws=zod.z.object({Definitions:zod.z.record(zod.z.string(),eP).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),tP).nullish(),BoostChains:zod.z.record(zod.z.string(),nP).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),rP).nullish(),Settings:lP.nullish(),Presets:aP.nullish()}).passthrough(),hm=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:ri.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:p.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:p.nullish()}).passthrough();var mm=zod.z.object({ServerTimeUtc:p.nullish(),Active:zod.z.record(zod.z.string(),hm).nullish()}),fm=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:hm.nullish(),Resources:M.nullish()}),uP={Scheduled:"Scheduled",Chain:"Chain"},cP=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),Effects:zod.z.array(ri).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),gm=zod.z.object({ServerTimeUtc:p.nullish(),Windows:zod.z.array(cP).nullish()}),si={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Ks=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(si.GetDefinitions,e,Ws)}getActive(e){return this.send(si.GetActive,e,mm)}getActiveWindows(e){return this.send(si.GetActiveWindows,e,gm)}activate(e){return this.send(si.Activate,e,Pe(fm))}cleanupExpired(e){return this.send(si.CleanupExpired,e,Ge)}};var Qs=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(yt.GetUserCustomDataDefinitions,e,Ur)}getMyUserCustomData(e){return this.send(yt.GetMyUserCustomData,e,kp)}getPublicUserCustomDataOf(e){return this.send(yt.GetPublicUserCustomDataOf,e,ga)}setPrivateData(e){return this.send(yt.SetPrivateData,e,ya)}setPublicData(e){return this.send(yt.SetPublicData,e,ya)}deleteKey(e){return this.send(yt.DeleteKey,e,Ge)}batchSet(e){return this.send(yt.BatchSet,e,zp)}batchDelete(e){return this.send(yt.BatchDelete,e,Mp)}batchGetPublicUserCustomDataOf(e){return this.send(yt.BatchGetPublicUserCustomDataOf,e,Op)}};var pP={Static:"Static",Runtime:"Runtime"},dP={Public:"Public",Private:"Private"},hP=zod.z.enum(["Client","Server","System"]).catch("Client"),mP=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),fP=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:p.nullish(),Version:zod.z.number().nullish(),LastWriter:hP.nullish(),ExpiresAt:p.nullish()}).passthrough(),ym=zod.z.record(zod.z.string(),fP),ul=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:ym.nullish(),Runtime:ym.nullish(),NotModified:zod.z.boolean().nullish()}),gP=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:mP.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Hs=zod.z.object({Keys:zod.z.record(zod.z.string(),gP).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(),Hi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var $s=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Hi.GetTitleCustomDataDefinitions,e,Hs)}getPublicTitleData(e){return this.send(Hi.GetPublicTitleData,e,ul)}getPublicTitleDataKeys(e){return this.send(Hi.GetPublicTitleDataKeys,e,ul)}};var Rm=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 yP={Fast:"Fast",Sequential:"Sequential"},RP={Instant:"Instant",Timed:"Timed"};var CP={Hit:"Hit",Blocked:"Blocked"},SP=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),xP=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:H.nullish()}).passthrough();var bP=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:H.nullish()}).passthrough(),DP=zod.z.object({Reward:H.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(bP).nullish(),Rate:DP.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 Cm=zod.z.object({}).passthrough().transform(s=>s),Sm=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Qe=zod.z.object({Operation:M.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),IP=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),PP=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(),vP=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(),TP=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(),xm=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:H.nullish()}).passthrough(),AP=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(),wP=zod.z.object({Tiles:zod.z.record(zod.z.string(),AP).nullish()}).passthrough(),kP=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Qe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),zP=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(kP).nullish(),GuaranteedBonus:Qe.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),MP=zod.z.object({Variants:zod.z.array(zP).nullish()}).passthrough(),OP=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:Qe.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),EP=zod.z.object({Outcomes:zod.z.array(OP).nullish()}).passthrough(),bm=zod.z.object({PerAdMultiplierRange:Sm.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),UP=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Qe.nullish()}).passthrough(),qP=zod.z.object({Tiers:zod.z.array(UP).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Qe.nullish()}).passthrough(),LP=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Qe.nullish()}).passthrough(),BP=zod.z.object({Reward:Qe.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),GP=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(LP).nullish(),Rate:BP.nullish()}).passthrough(),Dm=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),GP).nullish()}).passthrough(),FP=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ce.nullish(),Multipliers:bm.nullish(),Gradation:qP.nullish(),RunStats:Dm.nullish()}).passthrough(),_P=zod.z.object({Choices:zod.z.array(FP).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),VP=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Qe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),NP=zod.z.object({OnPassStart:Qe.nullish(),OnTileLanding:zod.z.record(zod.z.string(),Qe).nullish(),OnAttack:zod.z.record(zod.z.string(),Qe).nullish(),OnRaid:zod.z.record(zod.z.string(),Qe).nullish(),OnBuild:Qe.nullish(),OnStageComplete:Qe.nullish(),OnAttackBonusDrops:zod.z.array(VP).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),EP).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),_P).nullish()}).passthrough(),Im=zod.z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(xm).nullish(),HeistGridBonusConfig:MP.nullish(),StageOperations:NP.nullish(),TileLandingMultiplier:Sm.nullish(),EconomyOverride:TP.nullish()}).passthrough(),jP=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(xm).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:Im.nullish()}).passthrough(),WP=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(),KP=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(),Js=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(),wP).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),Im).nullish(),StagesByLevel:zod.z.record(zod.z.string(),jP).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:vP.nullish(),Dice:IP.nullish(),Bots:PP.nullish(),Targeting:WP.nullish(),BotRaids:KP.nullish()}).passthrough(),QP=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:p.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),GrandPrize:H.nullish()}).passthrough(),Zs=zod.z.object({Board:Js.nullish(),CommunityChest:QP.nullish()}).passthrough(),Pm=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),pe).nullish()}).passthrough(),HP=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:qe.nullish(),TargetBuildingStates:zod.z.array(SP).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:Pm.nullish()}).passthrough(),$P=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ce.nullish(),Multipliers:bm.nullish(),RunStats:Dm.nullish()}).passthrough(),JP=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array($P).nullish()}).passthrough(),ZP=zod.z.object({GroupID:zod.z.string().nullish(),Delta:W.nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),vm=zod.z.object({UsedMultiplier:zod.z.number().nullish(),Steps:zod.z.number().nullish(),DiceValues:zod.z.array(zod.z.number()).nullish(),OldPosition:zod.z.number().nullish(),NewPosition:zod.z.number(),CyclesCompletedDelta:W.nullish(),LandedTileType:zod.z.string().nullish(),Operation:M.nullish(),Inventory:K.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:HP.nullish(),SpecialModeOffer:JP.nullish(),CommunityChestContribution:ZP.nullish()}).passthrough(),Tm=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:Tt.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:H.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(xP).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:Tt.nullish(),RaidRewardPreview:Pm.nullish()}).passthrough(),Am=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish()}).passthrough(),wm=zod.z.object({CreditsConfirmation:fe.nullish(),Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:M.nullish(),Inventory:K.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish()}).passthrough(),km=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),YP=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),zm=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:M.nullish(),Inventory:K.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(YP).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),XP={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Mm=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),ev={Active:"Active",Left:"Left",Replaced:"Replaced"},tv=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),iv=zod.z.object({CurrentProgress:W.nullish(),MaxProgress:W.nullish()}).passthrough(),nv=zod.z.object({UserID:zod.z.string().nullish(),PublicData:qe.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:W.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),Bl).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:tv.nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),Om=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(nv).nullish(),SharedProgress:iv.nullish(),Status:Mm.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:zod.z.number().nullish()}).passthrough(),rv=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:Mm.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:p.nullish()}).passthrough(),sv=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(rv).nullish()}).passthrough(),Em=zod.z.object({ServerTimeUtc:p.nullish(),UserState:sv.nullish(),ActiveGroup:Om.nullish(),SecondsRemaining:W.nullish()}),Um=zod.z.object({ServerTimeUtc:p.nullish(),Group:Om.nullish(),SecondsRemaining:W.nullish()}),pl=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),qm=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Fe={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var ov={Mesh:"Mesh",Host:"Host"},dl=zod.z.enum(["Mesh","Host"]).catch("Mesh"),av={ServerRelay:"ServerRelay",P2P:"P2P"},hl=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),lv={Public:"Public",Private:"Private"},uv=zod.z.enum(["Public","Private"]).catch("Public"),cv={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},pv=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Lm=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),dv=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Bm=zod.z.object({SystemState:dv.nullish(),DefaultTopology:dl.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:hl.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(Lm).nullish()}).passthrough(),hv=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(),mv=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:dl.nullish(),ChatMode:hl.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),fv=zod.z.object({Seq:zod.z.number().nullish(),Type:pv.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(),$i=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:dl.nullish(),ChatMode:hl.nullish(),Visibility:uv.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(hv).nullish(),IceServers:zod.z.array(Lm).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Gm=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),Fm=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),ml=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),_m=zod.z.object({Rooms:zod.z.array(mv).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Vm=zod.z.object({Envelopes:zod.z.array(fv).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Ys=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),Ze={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 fl=zod.z.object({TitleCustomData:Hs.nullish(),Character:cr.nullish(),Item:cs.nullish(),Currency:_r.nullish(),Store:kn.nullish(),Lootbox:Ya.nullish(),Quest:rn.nullish(),TimedEvent:$n.nullish(),Leaderboard:nr.nullish(),Season:or.nullish(),Reward:el.nullish(),Collection:qs.nullish(),Craft:il.nullish(),DealOffer:oa.nullish(),Premium:$a.nullish(),TimedBoost:Ws.nullish(),CoopEvent:Rr.nullish(),GameLoop:Zs.nullish(),Match:Aa.nullish(),Experiment:eh.nullish(),Blockchain:xa.nullish(),Marketplace:Oa.nullish(),Multiplayer:Bm.nullish(),UserCustomData:Ur.nullish(),Referral:sl.nullish(),Localization:ch.nullish(),Analytics:Nd.nullish(),Social:Tp.nullish(),PlatformBridge:Ap.nullish(),GameSpec:zod.z.string().nullish(),Look:Rm.nullish()}).passthrough();var oi={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Xs=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(oi.GetTitlePublicConfiguration,e,fl)}getTitlePublicConfigurationExcept(e){return this.send(oi.GetTitlePublicConfigurationExcept,e,fl)}getCurrencyDefinitions(e){return this.send(oi.GetCurrencyDefinitions,e,_r)}getItemDefinitions(e){return this.send(oi.GetItemDefinitions,e,cs)}getServerTime(e){return this.send(oi.GetServerTime,e,Ge)}};var eo=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Fe.GetGameLoops,e,Zs)}getBoardDefinition(e,t=false){return this.send(Fe.GetBoardDefinition,e,Js,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Fe.GetBoardDefinitionForLevel,e,Js,{silent:t})}getUserBoardState(e){return this.send(Fe.GetUserBoardState,e,Cm)}boardLoopRoll(e){return this.send(Fe.BoardLoopRoll,e,vm)}boardLoopAttack(e){return this.send(Fe.BoardLoopAttack,e,Tm)}boardLoopRaid(e){return this.send(Fe.BoardLoopRaid,e,cl)}boardLoopRaidFast(e){return this.send(Fe.BoardLoopRaidFast,e,cl)}boardLoopBuild(e){return this.send(Fe.BoardLoopBuild,e,Am)}boardSpecialChoose(e){return this.send(Fe.BoardSpecialChoose,e,Pe(wm))}boardSpecialApplyMultiplier(e){return this.send(Fe.BoardSpecialApplyMultiplier,e,km)}boardSpecialClaim(e){return this.send(Fe.BoardSpecialClaim,e,zm)}getCommunityChestState(e){return this.send(Fe.GetCommunityChestState,e,Em)}joinOrCreateCommunityChest(e){return this.send(Fe.JoinOrCreateCommunityChest,e,Um)}claimCommunityChestMilestone(e){return this.send(Fe.ClaimCommunityChestMilestone,e,pl)}claimCommunityChestGrandPrize(e){return this.send(Fe.ClaimCommunityChestGrandPrize,e,pl)}leaveCommunityChest(e){return this.send(Fe.LeaveCommunityChest,e,qm)}};var gv={Live:"Live",Latest:"Latest",Specific:"Specific"},yv={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},Rv=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),Cv={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"},Sv=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),xv=zod.z.object({Level:Rv,Message:zod.z.string().nullish(),Data:_t.nullish()}),bv=zod.z.object({Error:Sv,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),jm=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:_t.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(xv).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:bv.nullish()}),gl={Execute:"Execute"};var to=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(gl.Execute,e,jm)}};var io=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Je.GetDefinitions,e,Zp)}getUserState(e){return this.send(Je.GetUserState,e,Yp)}depositToken(e){return this.send(Je.DepositToken,e,Xp)}depositNFT(e){return this.send(Je.DepositNFT,e,ed)}requestTokenWithdrawal(e){return this.send(Je.RequestTokenWithdrawal,e,td)}requestNFTWithdrawal(e){return this.send(Je.RequestNFTWithdrawal,e,id)}getTransactionHistory(e){return this.send(Je.GetTransactionHistory,e,nd)}retryWithdrawal(e){return this.send(Je.RetryWithdrawal,e,rd)}confirmWithdrawal(e){return this.send(Je.ConfirmWithdrawal,e,sd)}donateToDeveloper(e){return this.send(Je.DonateToDeveloper,e,Pa)}donateToUsersPool(e){return this.send(Je.DonateToUsersPool,e,Pa)}getPlayAccess(e){return this.send(Je.GetPlayAccess,e,$p)}confirmPlayAccess(e){return this.send(Je.ConfirmPlayAccess,e,jt)}};var no=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Oe.GetDefinitions,e,Cd)}getGroupedOffers(e){return this.send(Oe.GetGroupedOffers,e,Sd)}getOffersByItem(e){return this.send(Oe.GetOffersByItem,e,Ea)}getOffer(e){return this.send(Oe.GetOffer,e,xd)}getBuyOrders(e){return this.send(Oe.GetBuyOrders,e,Ea)}getMyState(e){return this.send(Oe.GetMyState,e,Hr)}getHistory(e){return this.send(Oe.GetHistory,e,Dd)}createListing(e){return this.send(Oe.CreateListing,e,Wi)}cancelListing(e){return this.send(Oe.CancelListing,e,ct)}buy(e){return this.send(Oe.Buy,e,ct)}marketBuy(e){return this.send(Oe.MarketBuy,e,ct)}marketSell(e){return this.send(Oe.MarketSell,e,ct)}createAuction(e){return this.send(Oe.CreateAuction,e,Wi)}placeBid(e){return this.send(Oe.PlaceBid,e,bd)}claimAuction(e){return this.send(Oe.ClaimAuction,e,ct)}createBuyOrder(e){return this.send(Oe.CreateBuyOrder,e,Wi)}cancelBuyOrder(e){return this.send(Oe.CancelBuyOrder,e,ct)}fillBuyOrder(e){return this.send(Oe.FillBuyOrder,e,ct)}createDirectTrade(e){return this.send(Oe.CreateDirectTrade,e,Wi)}respondDirectTrade(e){return this.send(Oe.RespondDirectTrade,e,ct)}cancelDirectTrade(e){return this.send(Oe.CancelDirectTrade,e,ct)}claimBack(e){return this.send(Oe.ClaimBack,e,ct)}};var ro=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(Ze.CreateRoom,e,$i)}joinRoom(e){return this.send(Ze.JoinRoom,e,$i)}leaveRoom(e,t=false){return this.send(Ze.LeaveRoom,e,ml,{keepalive:t})}listRooms(e){return this.send(Ze.ListRooms,e,_m)}getRoom(e){return this.send(Ze.GetRoom,e,$i)}closeRoom(e){return this.send(Ze.CloseRoom,e,ml)}poll(e){return this.send(Ze.Poll,e,Vm)}sendSignal(e){return this.send(Ze.SendSignal,e,Ys,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(Ze.ClaimHost,e,$i)}kickMember(e){return this.send(Ze.KickMember,e,Gm)}unbanMember(e){return this.send(Ze.UnbanMember,e,Fm)}sendChat(e){return this.send(Ze.SendChat,e,Ys)}setMemberState(e){return this.send(Ze.SetMemberState,e,Ys)}};var Dv={Free:"Free",Price:"Price",Holding:"Holding"},yl=zod.z.enum(["Free","Price","Holding"]).catch("Free"),Iv={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},Pv=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),vv={All:"All",Any:"Any"},Tv=zod.z.enum(["All","Any"]).catch("All"),Av={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},wv=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),kv={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},zv=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),Mv={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Km=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),Ov={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},Ev={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},Uv=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),qv=zod.z.object({Type:mi.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(),Lv=zod.z.object({Requirements:zod.z.array(qv).nullish(),Match:Tv.nullish(),Mode:Pv.nullish()}).passthrough(),Bv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:yl.nullish(),Price:pe.nullish(),Holding:Lv.nullish()}).passthrough(),Gv=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(),Fv=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),Gv).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(yl).nullish(),PricePolicy:Qr.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ce.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),_v=zod.z.object({Allowed:zod.z.array(ji).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),Vv=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),Nv=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(),jv=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Schedule:Re.nullish(),Gate:Z.nullish(),Order:zod.z.number().nullish()}).passthrough(),Wv=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:Re.nullish(),ContentTypes:zod.z.record(zod.z.string(),Fv).nullish(),PricePolicy:Qr.nullish(),Commission:Ma.nullish(),HoldingPolicy:_v.nullish(),Moderation:Vv.nullish(),Limits:Nv.nullish(),Featured:zod.z.array(jv).nullish()}).passthrough(),Kv=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(),ai=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:qe.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:wv.nullish(),Access:zod.z.array(Bv).nullish(),Status:zv.nullish(),ModerationNote:zod.z.string().nullish(),Stats:Kv.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),PublishedAt:p.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),Qv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:yl.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),Qm=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(),Hm=zod.z.object({Definitions:Wv.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(Qm).nullish()}).passthrough(),so=zod.z.object({Items:zod.z.array(ai).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),$m=zod.z.object({Content:ai.nullish(),AccessState:zod.z.array(Qv).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Jm=zod.z.object({Collection:Qm.nullish(),Items:zod.z.array(ai).nullish()}).passthrough(),Zm=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:qe.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(ai).nullish()}).passthrough(),Wm=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(),Ym=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(Wm).nullish(),ThumbnailUpload:Wm.nullish(),ExpiresAt:p.nullish()}).passthrough(),Xm=zod.z.object({CreditsConfirmation:fe.nullish(),Content:ai.nullish(),Resources:M.nullish()}).passthrough(),Rl=zod.z.object({Content:ai.nullish()}).passthrough(),ef=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Km.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:Tt.nullish(),Resources:M.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Hv=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),tf=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:Uv.nullish(),Files:zod.z.array(Hv).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:p.nullish()}).passthrough(),$v=zod.z.object({ContentID:zod.z.string().nullish(),Source:Km.nullish(),OptionID:zod.z.string().nullish(),PricePaid:pe.nullish(),AcquiredAt:p.nullish(),Content:ai.nullish()}).passthrough(),nf=zod.z.object({Licenses:zod.z.array($v).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),He={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 oo=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(He.GetDefinitions,e,Hm)}browse(e){return this.send(He.Browse,e,so)}getContent(e){return this.send(He.GetContent,e,$m)}getCollection(e){return this.send(He.GetCollection,e,Jm)}getCreatorProfile(e){return this.send(He.GetCreatorProfile,e,Zm)}beginUpload(e){return this.send(He.BeginUpload,e,Ym)}publish(e){return this.send(He.Publish,e,Pe(Xm))}updateContent(e){return this.send(He.UpdateContent,e,Rl)}unpublish(e){return this.send(He.Unpublish,e,Rl)}getMyContent(e){return this.send(He.GetMyContent,e,so)}acquire(e){return this.send(He.Acquire,e,ef)}getDownload(e){return this.send(He.GetDownload,e,tf)}getMyLicenses(e){return this.send(He.GetMyLicenses,e,nf)}getMyFavorites(e){return this.send(He.GetMyFavorites,e,so)}};var ao=class extends B{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,n){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${n}`})}sendPublic(e,t,i,n){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${n}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,wd,"defs")}get(e){return this.sendKeyed("Get",e,qa,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,zd,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,La,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Md,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,Ba,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,Ba,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Od,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,Ud,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Ed,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,qd,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,kd,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Ld,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,qa,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,La,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var lo=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;credits;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.settings=Dl(e),this.emitter=new zi,this.platform=e.platform??new pi,this.clientPlatform=e.clientPlatform??ql(),this.acquisition=new $t(this.platform),this.acquisition.capture(),this.playtime=new Mi(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new pn({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 fn(this.emitter),this.cache=new yn(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new Rn(this.platform.storage,this.settings.titleID),this.api={authentication:new ss(this),user:new as(this),currency:new ls(this),item:new ps(this),store:new ds(this),purchase:new gs(this),lootbox:new Cs(this),reward:new Ss(this),quest:new vs(this),tutorial:new xs(this),communityMarketing:new bs(this),chat:new Ds(this),push:new Is(this),localization:new Ps(this),timedEvent:new Ts(this),leaderboard:new As(this),season:new ws(this),premium:new ks(this),character:new zs(this),match:new Ms(this),craft:new Es(this),ai:new Us(this),collection:new Ls(this),coopEvent:new Bs(this),dealOffer:new Gs(this),referral:new Fs(this),mailbox:new _s(this),advertising:new Vs(this),social:new Ns(this),timedBoost:new Ks(this),userCustomData:new Qs(this),titleCustomData:new $s(this),title:new Xs(this),gameLoop:new eo(this),cloudCode:new to(this),blockchain:new io(this),marketplace:new no(this),multiplayer:new ro(this),workshop:new oo(this),dataCollections:new ao(this),analytics:new ns(this),experiment:new rs(this)},this.userService=new In(this),this.cache.attachState(this.userService),this.auth=new Sn(this),this.currency=new vn(this),this.item=new Tn(this),this.store=new Mn(this),this.credits=new On(this),this.purchase=new En(this),this.checkout=new Un(this),this.lootbox=new qn(this),this.reward=new Bn(this),this.quest=new Hn(this),this.tutorial=new Fn(this),this.communityMarketing=new _n(this),this.chat=new jn(this),this.push=new Wn(this),this.localization=new Qn(this),this.timedEvent=new Zn(this),this.leaderboard=new rr(this),this.season=new ar(this),this.premium=new lr(this),this.character=new pr(this),this.match=new dr(this),this.craft=new hr(this),this.ai=new fr(this),this.collection=new gr(this),this.coopEvent=new Cr(this),this.dealOffer=new br(this),this.referral=new Dr(this),this.mailbox=new vr(this),this.ads=new wr(this),this.social=new Mr(this),this.timedBoost=new Or(this),this.userCustomData=new qr(this),this.titleCustomData=new Lr(this),this.title=new Br(this),this.gameLoop=new Gr(this),this.cloudCode=new Fr(this),this.blockchain=new Nr(this),this.marketplace=new $r(this),this.multiplayer=new Jr(this),this.workshop=new Zr(this),this.dataCollections=new Xr(this),this.analytics=new ts(this),this.experiments=new is(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.platform.getFullURL(),RelatedEntityID:G()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var uo=class{ctx;constructor(e){this.ctx=new lo(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let n=this.ctx.buildAuthedBaseRequest(),r=Kt(this.ctx.settings.titleID,e,t,n.UserID??"");return this.ctx.transport.post(r,{...n,...i},zod.z.unknown(),{ticket:n.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get platform(){return this.ctx.platform}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 Zv(s){return new uo(s)}var rf="idos_sso",sf="state",Cl="idos:sso:state",Yv="https://idosgames.com/sso/",Xv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],eT=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function tT(){if(typeof window>"u")return false;let{origin:s}=window.location;return Xv.includes(s)||eT.test(s)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function iT(){if(typeof window>"u")return null;let s=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!s)return null;let e=new URLSearchParams(s),t=e.get(rf);if(!t)return null;let i=e.get(sf)??"",n=aT();return uT(e),lT(),n&&i!==n?null:{code:t,state:i}}function nT(s){if(typeof window>"u")return;let e=s.returnTo??rT(),t=sT();oT(t);let i=new URL(s.ssoUrl??Yv);i.searchParams.set("title",s.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function rT(){let{origin:s,pathname:e,search:t}=window.location;return `${s}${e}${t}`}function sT(){let s=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(s);else for(let e=0;e<s.length;e++)s[e]=Math.floor(Math.random()*256);return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}function oT(s){try{window.sessionStorage.setItem(Cl,s);}catch{}}function aT(){try{return window.sessionStorage.getItem(Cl)}catch{return null}}function lT(){try{window.sessionStorage.removeItem(Cl);}catch{}}function uT(s){s.delete(rf),s.delete(sf);let e=s.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var cT={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 pT(s,e="Something went wrong. Please try again."){return s?cT[s]??s:e}function dT(s,e){return !!s?.Claims?.[e]?.ClaimedAt}function hT(s){let e=s?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function mT(s,e){return s?.Claims?.[e]?.PremiumTiers??[]}function af(s,e,t,i=1){if(!s)return e;let n=s.Base??e,r=Math.max(0,t-i),o;switch(s.Shape??"Flat"){case "PerStep":o=n+(s.PerStep??0)*r;break;case "PerStepRate":o=n*(1+(s.PerStepRate??0)*r);break;case "Geometric":o=n*Math.pow(1+(s.GrowthRate??0),r);break;case "Table":o=n*of(s,t,1);break;case "TableAbsolute":o=of(s,t,n);break;default:o=n;break}return Number.isNaN(o)?n:(s.MinResult!=null&&o<s.MinResult&&(o=s.MinResult),s.MaxResult!=null&&o>s.MaxResult&&(o=s.MaxResult),o)}function fT(s,e,t=1){return af(s,1,e,t)}function gT(s){if(!s)return false;switch(s.Shape??"Flat"){case "PerStep":return (s.PerStep??0)!==0;case "PerStepRate":return (s.PerStepRate??0)!==0;case "Geometric":return (s.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return lf(s.Points).length>0;default:return s.MinResult!=null||s.MaxResult!=null}}function yT(s){if(Number.isNaN(s)||s<=0)return 0;if(!Number.isFinite(s))return Number.MAX_SAFE_INTEGER;let e=Math.round(s);return Math.abs(s-e)<=1e-9*Math.max(1,Math.abs(s))?e:Math.ceil(s)}function lf(s){if(!s)return [];let e=[];for(let t of s)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function of(s,e,t){let i=lf(s.Points);if(i.length===0)return t;let n=null,r=null,o=null;for(let c of i)(o===null||c.AtStep>o.AtStep)&&(o=c),c.AtStep<=e&&(n===null||c.AtStep>=n.AtStep)&&(n=c),c.AtStep>e&&(r===null||c.AtStep<r.AtStep)&&(r=c);if(n===null)return t;if(r===null){let c=s.TailGrowthRate??0;return c===0?o.Value:o.Value*Math.pow(1+c,e-o.AtStep)}switch(s.Interpolation??"Step"){case "Linear":{let c=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value+c*(r.Value-n.Value)}case "Geometric":{if(n.Value<=0||r.Value<=0){let h=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value+h*(r.Value-n.Value)}let c=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value*Math.pow(r.Value/n.Value,c)}default:return n.Value}}var RT={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Sl=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),CT={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},ST=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),xT=zod.z.object({PlacementID:zod.z.string().nullish(),Type:Sl.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(),bT=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(),DT=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),IT=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:ST.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),PT=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),vT=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),TT=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(),AT=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(),wT=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),kT=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:Sl.nullish()}).passthrough(),zT={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},MT=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),OT=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:MT.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(),kT).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),xT).nullish(),Providers:zod.z.record(zod.z.string(),OT).nullish(),RewardedVideo:bT.nullish(),Interstitial:DT.nullish(),Banner:IT.nullish(),AppOpen:PT.nullish(),FrequencyCapping:vT.nullish(),PremiumAdReductions:zod.z.array(TT).nullish(),Consent:AT.nullish(),Verification:wT.nullish()}).passthrough();var ET=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),UT=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:p.nullish(),LastCompletedAt:p.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),qT=zod.z.object({Date:p.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),LT=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:p.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),BT=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:p.nullish(),ConsentRevokedAt:p.nullish()}).passthrough(),GT=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:Sl.nullish(),IssuedAt:p.nullish(),ExpiresAt:p.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),FT=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:p.nullish()}).passthrough();zod.z.object({Credits:ET.nullish(),Placements:zod.z.record(zod.z.string(),UT).nullish(),Daily:qT.nullish(),Session:LT.nullish(),LastImpressionAt:p.nullish(),LastInterstitialAt:p.nullish(),LastRewardedAt:p.nullish(),LastAppOpenAt:p.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:p.nullish(),Consent:BT.nullish(),PendingRequests:zod.z.record(zod.z.string(),GT).nullish(),FraudFlags:FT.nullish(),UpdatedAt:p.nullish()}).passthrough();var uf="idos_device_id",co=class{storage;constructor(e=new ui){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(uf);return e||(e="noop-device",this.storage.setString(uf,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};
|
|
2
|
+
exports.AIAction=Be;exports.AIErrorCode=KR;exports.AIGenerationStatus=Xt;exports.AIModality=Vt;exports.AcquisitionCapture=$t;exports.AdProviderKind=zT;exports.AdType=RT;exports.AdvertisingAction=Tr;exports.AnalyticsAction=Va;exports.AnalyticsDropReason=Vb;exports.AnalyticsEventNaming=_a;exports.AnalyticsLimits=Dt;exports.AttackOutcome=CP;exports.AuthType=ze;exports.AuthenticationAction=Le;exports.AutomaticEvent=Wt;exports.BannerPosition=CT;exports.BlockchainAction=Je;exports.BlockchainNetworkType=ZS;exports.BlockchainOperationCategory=jp;exports.BlockchainTransactionStatus=ox;exports.BlockchainTransactionType=tx;exports.BodyPart=Ex;exports.BoostWindowKind=uP;exports.BrowserPlatformAdapter=pi;exports.BrowserStorage=li;exports.CharacterAction=We;exports.ChatAction=$e;exports.ChatAuthorType=qy;exports.ChatBlockedTermAction=Ey;exports.ChatChannelType=wy;exports.ChatDirectAudience=My;exports.ChatPartitioning=ky;exports.ChatReportReason=By;exports.ClientPlatform=Rt;exports.CloudCodeAction=gl;exports.CloudCodeErrorCode=Cv;exports.CloudCodeLogLevel=yv;exports.CloudCodeRevisionSelection=gv;exports.CollectionAction=Ke;exports.CommissionSink=eb;exports.CommunityChestMemberStatus=ev;exports.CommunityChestStatus=XP;exports.CommunityCreatorStatus=yI;exports.CommunityMarketingAction=ni;exports.CommunityMetricKind=CI;exports.CommunityParticipationMode=fI;exports.CommunityPayoutCurrencyKind=RI;exports.ConversionRateMode=GS;exports.CoopEventAction=gt;exports.CoopGroupStatus=aC;exports.CoopMemberStatus=lC;exports.CraftAction=Os;exports.CraftInputSelectionMode=MI;exports.CraftOutputLevelMode=kI;exports.CraftOutputLevelOverflow=EI;exports.CraftType=wI;exports.CreditsConfirmationStatus=qi;exports.CreditsError=ny;exports.CurrencyAction=Vi;exports.CurrencyStatus=BS;exports.CurrencyType=ht;exports.CurveInterpolation=Uf;exports.CurveShape=Of;exports.CustomDataBucket=Et;exports.CustomDataValueType=wS;exports.CustomDataWriter=PS;exports.DEFAULT_BASE_URL=bl;exports.DataAccessMode=Sb;exports.DataCollectionKind=gb;exports.DataCollectionSchemaMode=Ab;exports.DataCollectionsAction=Lb;exports.DataCounterKind=Ib;exports.DataFieldType=Rb;exports.DataFieldVisibility=Cb;exports.DataOwnerDeletedPolicy=vb;exports.DataRefKind=bb;exports.DealComparisonOperator=vC;exports.DealNodeRuntimeStatus=RC;exports.DealNodeType=PC;exports.DealOfferAction=xt;exports.DealOfferActivationStatus=yC;exports.EVENT_NAME_PATTERN=es;exports.EnvelopeType=cv;exports.EventTokenType=Sf;exports.ExperimentAction=Wa;exports.ExperimentGoalKind=Xb;exports.FRIENDS_FROM_PLATFORM=xS;exports.FodderSelectionMode=dD;exports.FodderValuationMode=cD;exports.FriendActionStatus=lS;exports.FriendSource=uS;exports.GameLoopAction=Fe;exports.IDosGamesClient=uo;exports.IapProductType=PD;exports.IapPurchaseStatus=GD;exports.IapStoreValues=Cf;exports.ItemAction=us;exports.KycStatus=ix;exports.KycTier=rx;exports.LeaderboardAction=je;exports.LocalizationAction=os;exports.LocalizationMissingKeyMode=sD;exports.LootboxAction=Rs;exports.MAILBOX_COUNTER_CAP=$C;exports.MailboxAction=nt;exports.MailboxCategory=NC;exports.MailboxErrors=HC;exports.MailboxLetterSource=jC;exports.MailboxRewardModule=KC;exports.MarketGoodsType=Kr;exports.MarketOfferStatus=Xx;exports.MarketOfferType=Yx;exports.MarketplaceAction=Oe;exports.MatchAction=bt;exports.MatchStatus=Ux;exports.MemoryStorage=ui;exports.MultiplayerAction=Ze;exports.MultiplayerChatMode=av;exports.MultiplayerTopology=ov;exports.NoopPlatformAdapter=co;exports.OFFER_NOT_IN_ROTATION=Dy;exports.PLATFORM_AD_MESSAGES=da;exports.PLATFORM_AD_PROVIDER=pa;exports.PLATFORM_BRIDGE_ACK=fu;exports.PLATFORM_CREDITS_CONFIRM_MESSAGES=qo;exports.PLATFORM_ORIGINS=At;exports.PLATFORM_PAGE_UNAVAILABLE=gu;exports.PLATFORM_SIGN_IN_MESSAGES=Ao;exports.PLATFORM_TOPUP_MESSAGES=Eo;exports.PlatformFriendsMode=DS;exports.PlatformProfileMode=bS;exports.PlayAccessMode=fx;exports.PlayerExperimentStatus=iD;exports.PlaytimeTracker=Mi;exports.PremiumAction=ti;exports.PurchaseAction=ii;exports.PushAction=bi;exports.PushPermissionState=Mt;exports.PushTopic=Yy;exports.PushTransport=Jy;exports.QuestAction=ft;exports.QuestObjectiveSource=Kf;exports.QuestPrerequisiteMode=Hf;exports.QuestStatus=Nf;exports.RaidMode=yP;exports.ReferralAction=Qt;exports.ResourceEntryType=Zi;exports.RewardAction=It;exports.RewardWindowBoost=tI;exports.RoomVisibility=lv;exports.SKIN_ALREADY_OWNED=WR;exports.SKIN_SLOT=ea;exports.ScheduleMode=xf;exports.SeasonAction=Ft;exports.SocialAction=xe;exports.SocialContentStatus=mS;exports.SocialEntityType=pS;exports.SocialInboxVerb=fS;exports.SocialReactionKind=dS;exports.SocialReportReason=hS;exports.SpecialChoiceMode=RP;exports.StoreAction=zt;exports.StoreRotationMode=oy;exports.StoreType=DD;exports.TimedBoostAction=si;exports.TimedBoostStackingPolicy=XI;exports.TimedEventAction=ut;exports.TitleAction=oi;exports.TitleCustomDataAction=Hi;exports.TitleDataBucket=dP;exports.TitleDataScope=pP;exports.TradeOfferStatus=FI;exports.TransactionDirection=ax;exports.TutorialAction=at;exports.TutorialBoardAction=ug;exports.TutorialFlowStatus=og;exports.TutorialGateMode=Tf;exports.TutorialRestartPolicy=rg;exports.TutorialScriptModule=lg;exports.TutorialStepCompletionMode=ig;exports.TypedEmitter=zi;exports.UserAction=pt;exports.UserCustomDataAction=yt;exports.WalletGateBalanceSource=dx;exports.WalletLinkType=XS;exports.WorkshopAccessMode=Dv;exports.WorkshopAccessVia=Ev;exports.WorkshopAction=He;exports.WorkshopContentStatus=kv;exports.WorkshopHoldingMatch=vv;exports.WorkshopHoldingMode=Iv;exports.WorkshopLicenseSource=Mv;exports.WorkshopSort=Ov;exports.WorkshopVisibility=Av;exports.askPlatformPage=wt;exports.authErrorText=pT;exports.beginSsoRedirect=nT;exports.canPayWithPlatformCredits=Ty;exports.canUsePlatformAds=Ar;exports.canUsePlatformCreditsConfirm=Lo;exports.canUsePlatformSignIn=Vg;exports.canUsePlatformTopUp=Yt;exports.canUsePreviewSignIn=Ng;exports.claimedMilestoneIDs=hT;exports.clearPlatformSignInDeclined=Wg;exports.createIDosGamesClient=Zv;exports.cryptoShortfallFromError=yi;exports.curveMultiplier=fT;exports.defineView=Mg;exports.describeUserAgent=Wd;exports.evaluateCurve=af;exports.grantedPremiumTiers=mT;exports.isAIGenerationTerminal=Bi;exports.isCurveConfigured=gT;exports.isFail=Df;exports.isMilestoneClaimed=dT;exports.isOk=bf;exports.isPlatformParentOrigin=Ui;exports.isPlatformSignInDeclined=Kg;exports.isReservedSlot=ER;exports.isSsoAvailable=tT;exports.markPlatformSignInDeclined=jg;exports.normalizeBlockchainCategory=Vr;exports.parseAIErrorCode=QR;exports.readSsoCodeFromUrl=iT;exports.requestPlatformAd=ha;exports.requestPlatformCreditsConfirm=Bo;exports.requestPlatformSignIn=ko;exports.requestPlatformTopUp=Uo;exports.roundAmount=yT;exports.where=Gb;exports.zPaymentProof=iy;exports.zPriceOption=An;exports.zPriceOptions=ce;
|