@idosgames/core 0.25.0 → 0.26.0

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/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {s,j as j$1,e,d,n,v,w,t,f}from'./chunk-YSPGQWAB.js';export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,x as NoopPlatformAdapter,h as PLATFORM_BRIDGE_ACK,u as PLATFORM_CREDITS_CONFIRM_MESSAGES,f as PLATFORM_ORIGINS,i as PLATFORM_PAGE_UNAVAILABLE,k as PLATFORM_SIGN_IN_MESSAGES,r as PLATFORM_TOPUP_MESSAGES,j as askPlatformPage,v as canUsePlatformCreditsConfirm,l as canUsePlatformSignIn,s as canUsePlatformTopUp,m as canUsePreviewSignIn,p as clearPlatformSignInDeclined,g as isPlatformParentOrigin,q as isPlatformSignInDeclined,o as markPlatformSignInDeclined,w as requestPlatformCreditsConfirm,n as requestPlatformSignIn,t as requestPlatformTopUp}from'./chunk-YSPGQWAB.js';import {b,a,c as c$1}from'./chunk-CS7ACWDY.js';export{e as isFail,d as isOk}from'./chunk-CS7ACWDY.js';import {z}from'zod';import Qt from'decimal.js';var xi=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,s=>{i(),t(s);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let s of [...i])s(t);}removeAllListeners(){this.listeners.clear();}};function Xm(){let o=new Map;return {get:e=>o.get(e)??null,set:(e,t)=>{o.set(e,t);},remove:e=>{o.delete(e);}}}function sl(){return ef()??Xm()}function ef(){try{let o=globalThis.localStorage;if(!o)return null;let e="__idos_probe__";return o.setItem(e,"1"),o.removeItem(e),{get:t=>{try{return o.getItem(t)}catch{return null}},set:(t,i)=>{try{o.setItem(t,i);}catch{try{o.removeItem(t);}catch{}}},remove:t=>{try{o.removeItem(t);}catch{}}}}catch{return null}}var nl="https://api.idosgames.com";function rl(o){return {titleID:o.titleID,titleTemplateID:o.titleTemplateID??"default",buildKey:o.buildKey??"",baseUrl:(o.baseUrl??nl).replace(/\/+$/,""),devBuild:o.devBuild??false,debugLogging:o.debugLogging??false,configStorage:o.configStorage??sl(),locale:o.locale??tf(),appVersion:o.appVersion??""}}function tf(){try{return globalThis.navigator?.language??""}catch{return ""}}var io="idos_acq",ol=["gclid","fbclid","ttclid","msclkid","yclid"],sf=["ref","r"],nf=["ref_","ref-","ref=","r_","r-"];var jt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();rf(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=lf(this.platform.getDeviceModel());return s&&(i.OsVersion=s),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(io);}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=ul(ll(t));if(i)return i}return Gi(t)}readFromEnvironment(){let e={},t=ll(this.platform.getFullURL());_t(e,"UtmSource",t.get("utm_source")),_t(e,"UtmMedium",t.get("utm_medium")),_t(e,"UtmCampaign",t.get("utm_campaign")),_t(e,"UtmTerm",t.get("utm_term")),_t(e,"UtmContent",t.get("utm_content")),_t(e,"ClaimToken",t.get("idos_click"));for(let R of ol){let V=t.get(R);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",s=af(i);if(s){for(let R of of)_t(e,R,s.get(cl[R])??null);for(let R of ol){let V=s.get(R);if(V){e.ClickID=V;break}}}let n=Gi(s?s.get("ref")??s.get("r")??"":i),r=ul(t),p=n||r;p&&(e.ReferralCode=p,e.ChannelHint=n?"telegram":"query");let d=this.platform.getReferrer?.();return d&&(e.Referrer=d),e}read(){try{let e=this.platform.storage.getString(io);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(io,JSON.stringify(e));}catch{}}};function rf(o){return !!(o.UtmSource||o.UtmMedium||o.UtmCampaign||o.ClickID||o.Referrer||o.ReferralCode||o.ClaimToken)}function _t(o,e,t){t&&(o[e]=t);}var al="a1_",cl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},of=Object.keys(cl);function af(o){let e=(o||"").trim();if(!e.startsWith(al))return null;let t=e.slice(al.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),n=Uint8Array.from(s,d=>d.charCodeAt(0)),r=new TextDecoder().decode(n),p=new URLSearchParams(r);return [...p.keys()].length>0?p:null}catch{return null}}function ll(o){try{let e=o.indexOf("?");return new URLSearchParams(e>=0?o.slice(e):"")}catch{return new URLSearchParams}}function ul(o){for(let e of sf){let t=o.get(e);if(t)return Gi(t)}return null}function Gi(o){let e=(o||"").trim();if(!e)return null;for(let t of nf)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function lf(o){let e=o||"",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 pl="idos_usage_pending",hl="idos_usage_session",dl="idos_usage_closed_session",ml="idos_usage_new_session",fl="idos_usage_last_activity",bi=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(pl),this.currentSessionSeconds=this.readNumber(hl),this.pendingClosedSessionSeconds=this.readNumber(dl),this.isNewSessionPending=this.readNumber(ml)!==0;let e=this.readNumber(fl);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(pl,this.pendingSeconds),this.writeNumber(hl,this.currentSessionSeconds),this.writeNumber(dl,this.pendingClosedSessionSeconds),this.writeNumber(ml,this.isNewSessionPending?1:0),this.writeNumber(fl,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 ct={Virtual:"Virtual",Crypto:"Crypto"},si=z.enum(["Virtual","Crypto"]).catch("Virtual"),Fi={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},ni=z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),ft={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Vi=z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),uf={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Ni=z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),cf={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},_i=z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),pf={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},Di=z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),Ae={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function yl(){let o=globalThis,e=o.Capacitor?.getPlatform?.();if(e)return gl(e);let t=o.cordova?.platformId;return t?gl(t):o.navigator?.userAgent??""?ft.Web:ft.Unknown}function gl(o){let e=o.toLowerCase();return e==="android"?ft.Android:e==="ios"?ft.Ios:e==="web"?ft.Web:ft.Unknown}var j=z.union([z.number(),z.string()]).transform((o,e)=>{let t=typeof o=="string"?Number(o):o;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(o)}`}),z.NEVER)}),Y=z.union([z.number(),z.string()]).transform((o,e)=>{let t=typeof o=="number"?String(o):o.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid decimal: ${String(o)}`}),z.NEVER):t}),c=z.string();var so=z.object({Type:ni.nullish(),CurrencyID:z.string().nullish(),Amount:j.nullish(),AmountUsd:z.number().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ProductID:z.string().nullish()}),hf=z.object({Type:_i.nullish(),EntityID:z.string()}),df=z.object({Address:hf.nullish(),Amount:j.nullish(),Source:z.string().nullish()}),ce=z.object({Entries:z.array(so).nullish(),EventTokens:z.array(df).nullish()}),Rl=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Resources:ce.nullish()}),H=z.object({Standard:ce.nullish(),PremiumBonuses:z.array(z.unknown()).nullish(),PremiumTiers:z.array(Rl).nullish()}),bt=z.object({Standard:ce.nullish(),PremiumDiscounts:z.array(z.unknown()).nullish(),PremiumTiers:z.array(Rl).nullish()}),M=z.object({Grant:H.nullish(),Consume:bt.nullish()}),Dt=z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Transferred:ce.nullish()});var mf=z.object({ExperimentID:z.string().nullish(),Variants:z.array(z.string()).nullish()}).passthrough(),ff={Completed:"Completed",Started:"Started",StepReached:"StepReached"},gf=z.object({FlowIDs:z.array(z.string()).nullish(),Mode:z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:z.string().nullish(),Negate:z.boolean().nullish(),SkippedCountsAsCompleted:z.boolean().nullish()}).passthrough(),Z=z.object({Segments:z.array(z.string()).nullish(),MinPremiumTier:z.number().nullish(),RequiredPremiumIDs:z.array(z.string()).nullish(),MinLevel:z.number().nullish(),MaxLevel:z.number().nullish(),Countries:z.array(z.string()).nullish(),RegisteredWithinDays:z.number().nullish(),ActiveWithinDays:z.number().nullish(),Experiment:mf.nullish(),Tutorial:gf.nullish(),Platforms:z.array(Vi).nullish()}).passthrough();var Re=z.object({TotalCap:z.number().nullish(),DailyCap:z.number().nullish(),DailyWeightCap:z.number().nullish(),PerActivationCap:z.number().nullish(),CooldownSeconds:z.number().nullish(),MaxPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish()}).passthrough();var yf=z.object({OffsetSecondsFromParentStart:z.number().nullish(),DurationSeconds:z.number().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Rf=z.object({StartUtc:z.string().nullish(),EndUtc:z.string().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Cf=z.object({AnchorUtc:z.string().nullish(),MaxCycles:z.number().nullish(),PauseBetweenPhasesSec:z.number().nullish(),PauseBetweenCyclesSec:z.number().nullish()}).passthrough();z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();var Sf=z.object({Reset:z.string().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:z.string().nullish(),PauseBetweenCyclesSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();z.object({SourceType:z.string().nullish(),TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),Outcome:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough();var nt=z.object({SourceType:z.string().nullish(),BaseWeight:z.number().nullish(),ScaleWithRollMultiplier:z.boolean().nullish(),TileTypeFilter:z.array(z.string()).nullish(),TileIndexFilter:z.array(z.number()).nullish(),ChanceOutcomeFilter:z.array(z.string()).nullish(),OutcomeFilter:z.array(z.string()).nullish(),Params:z.record(z.string(),z.string()).nullish(),Limits:Re.nullish()}).passthrough(),fe=z.object({Mode:z.string().nullish(),IsActive:z.boolean().nullish(),Scheduled:Rf.nullish(),Chain:Cf.nullish(),Cyclic:Sf.nullish(),ActivationTriggers:z.array(nt).nullish(),Relative:yf.nullish()}).passthrough();var xf={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},bf=z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Df={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Pf=z.enum(["Step","Linear","Geometric"]).catch("Step"),If=z.object({AtStep:z.number().nullish(),Value:z.number().nullish()}).passthrough(),Ve=z.object({Base:z.number().nullish(),Shape:bf.nullish(),PerStep:z.number().nullish(),PerStepRate:z.number().nullish(),GrowthRate:z.number().nullish(),Points:z.array(If).nullish(),Interpolation:Pf.nullish(),TailGrowthRate:z.number().nullish(),MinResult:z.number().nullish(),MaxResult:z.number().nullish()}).passthrough();var vf=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Rewards:H.nullish()}).passthrough(),Tf=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Multiplier:z.number().nullish()}).passthrough(),no=z.object({Bundles:z.array(vf).nullish(),Multipliers:z.array(Tf).nullish()}).passthrough();var Af=z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),ji=z.object({Source:Af.nullish(),SourceKey:z.string().nullish(),Curve:Ve.nullish(),Anchor:z.number().nullish(),IncludeRewards:ce.nullish(),ExcludeRewards:ce.nullish()}).passthrough(),Cl=z.object({ClaimedAt:z.string().nullish(),PremiumTiers:z.array(z.string()).nullish(),Unlocked:z.boolean().nullish()}).passthrough(),Le=z.object({MilestoneID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredProgress:z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:no.nullish(),SortOrder:z.number().nullish(),IsFeatured:z.boolean().nullish()}).passthrough(),ri=z.object({Milestones:z.record(z.string(),Le).nullish()}).passthrough();var Q=z.object({PresetID:z.string().nullish(),Remove:z.array(z.string()).nullish()}).passthrough();var kf=z.object({TargetCurrencyID:z.string().nullish(),Rate:z.number().nullish(),MaxConvertAmount:z.number().nullish()}).passthrough(),Wt=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxBalance:z.number().nullish(),MaxPerGrant:z.number().nullish(),DailyEarnCap:z.number().nullish(),BurnOnEventEnd:z.boolean().nullish(),BurnConversion:kf.nullish()}).passthrough();var zf=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),Sl=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:zf.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),K=z.object({ChangedInstances:z.record(z.string(),Sl).nullish(),RemovedInstanceIDs:z.array(z.string()).nullish()});var Ie=o=>z.object({Id:z.string(),Success:z.boolean(),Error:z.string().nullish(),Data:o.nullish()}),gt=o=>z.object({ServerTimeUtc:c,Items:z.array(Ie(o)),Resources:M.nullish(),Inventory:K.nullish()});var wf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},xl=z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Mf=z.object({}).passthrough().transform(o=>o),Of=z.object({CycleID:z.string(),InstanceKey:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),CycleStartUtc:c.nullish(),CycleEndUtc:c.nullish(),PointsTotalEarned:j.nullish(),PointsCurrent:j.nullish(),ClaimedPointMilestoneIDs:z.array(z.string()).nullish(),NextMilestone:Le.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),ro=z.object({QuestID:z.string(),CycleID:z.string().nullish(),ObjectiveID:z.string().nullish(),NewValue:j.nullish(),ObjectiveCompleted:z.boolean().nullish(),Status:xl}),bl=z.object({State:Mf.nullish(),PointsTracks:z.record(z.string(),Of).nullish()}),oo=z.object({ServerTimeUtc:c,QuestID:z.string(),CycleID:z.string().nullish(),NewStatus:xl.nullish(),Resources:M.nullish(),Inventory:K.nullish()}),ao=z.object({ServerTimeUtc:c,CycleID:z.string(),MilestoneID:z.string(),PointsTotalEarned:j.nullish(),Resources:M.nullish(),Inventory:K.nullish(),NextMilestone:Le.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),Dl=z.object({ServerTimeUtc:c,CycleID:z.string(),GroupCompletionID:z.string(),GroupID:z.string().nullish(),CompletedGroupQuests:z.number().nullish(),RequiredGroupQuests:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Pl=z.object({MetricID:z.string(),Updates:z.array(ro).nullish()}),Il=z.array(Ie(oo)),vl=z.array(Ie(ao)),Ef={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Uf=z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),qf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Bf=z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),Tl=z.object({ObjectiveID:z.string().nullish(),Source:Uf.nullish(),MaxProgressPerCall:z.number().nullish(),MetricID:z.string().nullish(),Triggers:z.array(nt).nullish(),TargetValue:z.number().nullish(),AggregationMethod:z.string().nullish()}).passthrough(),lo=z.object({Milestones:Q.nullish(),Linking:Q.nullish(),Availability:Q.nullish(),Reward:Q.nullish(),Objectives:Q.nullish()}).passthrough(),Lf=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Al=z.object({CycleIDs:z.array(z.string()).nullish(),GroupID:z.string().nullish(),PhaseIDs:z.array(z.string()).nullish(),RequiredQuestIDs:z.array(z.string()).nullish(),PrerequisiteMode:Bf.nullish()}).passthrough(),kl=z.object({Schedule:fe.nullish(),AccrueProgressWhenLocked:z.boolean().nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),zl=z.object({Grant:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),Gf=z.object({QuestID:z.string().nullish(),Identity:Lf.nullish(),Linking:Al.nullish(),Availability:kl.nullish(),Objectives:z.record(z.string(),Tl).nullish(),Reward:zl.nullish(),Presets:lo.nullish()}).passthrough(),Ff=z.object({CompletionID:z.string().nullish(),GroupID:z.string().nullish(),RequiredCompletedQuests:z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),Vf=z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Gate:Z.nullish(),Milestones:z.record(z.string(),Le).nullish(),Presets:lo.nullish(),PointsToken:Wt.nullish()}).passthrough(),Nf=z.object({Milestones:z.record(z.string(),ri).nullish(),Linking:z.record(z.string(),Al).nullish(),Availability:z.record(z.string(),kl).nullish(),Reward:z.record(z.string(),zl).nullish(),Objectives:z.record(z.string(),z.record(z.string(),Tl)).nullish()}).passthrough(),_f=z.object({CycleID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:fe.nullish(),Milestones:z.record(z.string(),Le).nullish(),Gate:Z.nullish(),PointsToken:Wt.nullish(),GroupCompletions:z.record(z.string(),Ff).nullish(),Phases:z.record(z.string(),Vf).nullish(),Presets:lo.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Qi=z.object({Cycles:z.record(z.string(),_f).nullish(),Quests:z.record(z.string(),Gf).nullish(),Presets:Nf.nullish()}).passthrough(),ht={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var jf={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},Wf=z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),Qf={Never:"Never",OnRequest:"OnRequest",Always:"Always"},Kf=z.enum(["Never","OnRequest","Always"]).catch("Never"),Hf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},$f=z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),Jf={GameLoop:"GameLoop"},Zf={Raid:"Raid",Attack:"Attack"},Yf=z.object({Title:z.string().nullish(),TitleKey:z.string().nullish(),Body:z.string().nullish(),BodyKey:z.string().nullish(),AnchorID:z.string().nullish(),HighlightTarget:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),UiHint:z.record(z.string(),z.string()).nullish()}).passthrough(),Xf=z.object({Mode:Wf.nullish(),Triggers:z.array(nt).nullish(),TargetValue:z.number().nullish(),RequireAllTriggers:z.boolean().nullish()}).passthrough(),eg=z.object({Grant:H.nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),tg=z.object({TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),RandomActionType:z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),ig=z.object({Module:z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:tg.nullish(),MaxUses:z.number().nullish()}).passthrough(),sg=z.object({Skippable:z.boolean().nullish(),TimeoutSeconds:z.number().nullish()}).passthrough(),uo=z.object({StepID:z.string().nullish(),Order:z.number().nullish(),Identity:Yf.nullish(),Completion:Xf.nullish(),Effects:eg.nullish(),Script:ig.nullish(),Policy:sg.nullish()}).passthrough(),ng=z.object({DisplayName:z.string().nullish(),DisplayNameKey:z.string().nullish(),Description:z.string().nullish(),DescriptionKey:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),wl=z.object({Schedule:fe.nullish(),Gate:Z.nullish(),RequiredFlowIDs:z.array(z.string()).nullish(),AutoStart:z.boolean().nullish(),StartTrigger:nt.nullish()}).passthrough(),Ml=z.object({Skippable:z.boolean().nullish(),SkippableFromOrder:z.number().nullish(),RestartPolicy:Kf.nullish(),ExpireAfterSeconds:z.number().nullish(),IsBlocking:z.boolean().nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),Ol=z.object({Grant:H.nullish(),AutoClaim:z.boolean().nullish()}).passthrough(),rg=z.object({Availability:Q.nullish(),Policy:Q.nullish(),Reward:Q.nullish(),Steps:Q.nullish()}).passthrough(),og=z.object({FlowID:z.string().nullish(),Identity:ng.nullish(),Availability:wl.nullish(),Policy:Ml.nullish(),Steps:z.record(z.string(),uo).nullish(),Reward:Ol.nullish(),Presets:rg.nullish()}).passthrough(),ag=z.object({BlockingFlowIDs:z.array(z.string()).nullish(),BlockedModules:z.array(z.string()).nullish(),BlockedActions:z.record(z.string(),z.array(z.string())).nullish(),BlockBeforeStart:z.boolean().nullish(),SkipLiftsBlock:z.boolean().nullish()}).passthrough(),lg=z.object({IsEnabled:z.boolean().nullish(),MaxActiveFlows:z.number().nullish(),Blocking:ag.nullish()}).passthrough(),ug=z.object({Availability:z.record(z.string(),wl).nullish(),Policy:z.record(z.string(),Ml).nullish(),Reward:z.record(z.string(),Ol).nullish(),Steps:z.record(z.string(),z.record(z.string(),uo)).nullish()}).passthrough(),El=z.object({Flows:z.record(z.string(),og).nullish(),Settings:lg.nullish(),Presets:ug.nullish()}).passthrough(),cg=z.object({}).passthrough().transform(o=>o),Ul=z.object({FlowID:z.string(),Status:$f,CurrentStepID:z.string().nullish(),CurrentStep:uo.nullish(),TotalSteps:z.number(),CompletedSteps:z.number(),CanSkip:z.boolean(),RewardClaimed:z.boolean(),RewardPending:z.boolean(),VariantID:z.string().nullish()}).passthrough(),Ki=z.object({State:cg.nullish(),Flows:z.array(Ul).nullish(),UnlockedFeatures:z.array(z.string()).nullish()}).passthrough(),Mt=z.object({Flow:Ul.nullish()}).passthrough(),ql=z.object({FlowID:z.string().nullish(),Granted:M.nullish()}).passthrough(),Bl=z.array(Ie(Mt)),Ll=z.object({FlowID:z.string(),StepID:z.string(),Progress:z.number(),Target:z.number(),Completed:z.boolean()}).passthrough(),rt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Hi(o){return Array.isArray(o)?o.filter(e=>e!==null).map(Hi):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).filter(([,e])=>e!==null).map(([e,t])=>[e,Hi(t)])):o}var $i=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),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 Ji=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Gl(o){return o===429||o>=500&&o<=599}function Zi(o,e=Math.random){let t=Math.min(500*Math.pow(2,o-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Ot(o){return new Promise(e=>setTimeout(e,o))}var Fl=15e3;async function Vl(o){try{let t=JSON.parse(await o.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(o.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Nl(o,e=Math.random){return o+10+Math.min(250,o*.2)*e()}function _l(o,e=Math.random){let t=o<=1?1500:o===2?4e3:6e3;return t+t*.1*e()}var co=15,jl=1e3,Yi=class{constructor(e=co,t=()=>Date.now(),i=Ot){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]>=jl;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(jl-(e-this.starts[0])+5);}}};var pg=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function ai(o){if(!o)return null;let e=pg.exec(o);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new Qt(i),r=new Qt(s),p=r.minus(Qt.max(n,0));return p.lte(0)?null:{currencyID:t,required:r.toNumber(),available:n.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var hg=12e3,dg=new Set(["RelatedEntityID"]);function mg(o,e){if(e===null||typeof e!="object"||Array.isArray(e))return o;let t={};for(let[i,s]of Object.entries(e))dg.has(i)||(t[i]=s);try{return `${o}|${JSON.stringify(t)}`}catch{return o}}var fg=z.object({Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().optional(),QuestProgress:z.array(ro).nullish(),TutorialProgress:z.array(Ll).nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish()}).passthrough(),Xi=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Ji;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new $i(e.throttleMs),this.pacer=new Yi(e.maxRequestsPerSecond??co),this.clientPlatform=e.clientPlatform??ft.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,s={}){let n=s.throttleKey??mg(e,t);if(!this.throttler.tryAcquire(n))return b("throttled","Throttled");if(!this.inflight.add(n))return b("throttled","Duplicate request skipped");this.raiseBusy();try{let r=`${this.baseUrl}/${e}`,p=JSON.stringify(t),d=s.ticket??null,R=s.silent??!1,V=s.timeoutMs??hg,ae=s.autoRetry??!0,ve=!1,ye=!1,Oe=0;for(;;){let xt;s.keepalive||await this.pacer.take();try{xt=await this.doFetch(r,p,d,V,s.keepalive??!1);}catch{if(ae&&Oe<3){Oe++,await Ot(Zi(Oe));continue}return this.connectionFailure("Internet Connection Error",R)}let Ze=xt.status;if(Ze>=200&&Ze<300){let re=!ye&&this.cryptoTopUpHandler!==null,Pe=await this.parseSuccess(xt,i,R,e,re);if(!Pe.ok&&re){let pe=ai(Pe.error);if(pe){if(ye=!0,await this.runTopUp(pe))continue;R||this.emitter.emit("error:global",Pe.error);}}return Pe}if(Ze===401){if(!ve&&this.sessionRefreshHandler){ve=!0;let re=null;try{re=await this.sessionRefreshHandler();}catch{re=null;}if(re){d=re;continue}}return this.emitter.emit("auth:unauthorized",void 0),b("unauthorized","Unauthorized")}if(Gl(Ze)){let re=Ze===429?await Vl(xt):null;if(re!==null&&re>Fl)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(re/1e3)} s`,R);if(ae&&Oe<3){Oe++,await Ot(re!==null?Nl(re):Ze===429?_l(Oe):Zi(Oe));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Ze})`,R)}let Ri="";try{Ri=await xt.text();}catch{}if(Ze===409&&/operation in progress/i.test(Ri)&&ae&&Oe<3){Oe++,await Ot(Zi(Oe));continue}return this.handleWebError(Ri,Ze,R)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let r=new AbortController,p=setTimeout(()=>{r.abort();},s);try{let d={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(d.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:d,signal:r.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,i,s,n=false){let r;try{r=await e.text();}catch{return this.globalError("Failed to read response body",i)}let p;try{p=JSON.parse(r);}catch{return this.globalError("JSON Parse Error",i)}let d=fg.safeParse(p);if(!d.success)return this.globalError("Malformed response envelope",i);if(!d.data.Success){let ye=d.data.Error??"Server returned Success=false",Oe=n&&ai(ye);return !i&&!Oe&&this.emitter.emit("error:global",ye),b("server",ye)}let R=d.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:d.data.StateEpoch??null,versions:R});let V=d.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);let ae=d.data.TutorialProgress;ae&&ae.length>0&&this.emitter.emit("tutorial:systemProgress",ae);let ve=t.safeParse(d.data.Data);if(!ve.success){let ye=t.safeParse(Hi(d.data.Data));ye.success&&(ve=ye);}if(!ve.success){let ye=`Validation error (${s}): ${ve.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",ye),i||this.emitter.emit("error:global",ye),b("validation",ye)}return a(ve.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let r=JSON.parse(e)?.Error;if(t===403&&r==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),b("server","PLAY_ACCESS_REQUIRED");s=typeof r=="string"&&r.length>0?`HTTP ${t}: ${r}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),b("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),b("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),b("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 li(o){return (typeof o=="string"?o:o.toISOString()).slice(0,10)}function Pi(o){return `${li(o)}T00:00:00.000Z`}function Wl(o){let e=new Date(o);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Ql(o,e){return new Date(o.getTime()+e*6e4).toISOString()}function mo(o,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;o.InventoryV2??={};let n=o.InventoryV2,r=i.toISOString(),p=new Map,d$1=new Map,R=new Map,V=new Map,ae=new Map,ve=new Map,ye=new Map,Oe=new Map,xt=e.Grant?.PremiumTiers??[],Ze=xt.length;for(let re=0;;re++){let Pe,pe;if(re===0)Pe=e.Grant?.Standard?.Entries,pe=false;else if(re-1<Ze)Pe=xt[re-1]?.Resources?.Entries,pe=false;else if(re===1+Ze)Pe=e.Consume?.Standard?.Entries,pe=true;else break;if(Pe)for(let le of Pe){if(le.Type==null)continue;let he=Math.max(0,le.Amount??0);if(!(he<=0))switch(le.Type){case "VirtualCurrency":{if(!le.CurrencyID)continue;let de=pe?d$1:p;de.set(le.CurrencyID,(de.get(le.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!le.CurrencyID)continue;let de=pe?V:R;de.set(le.CurrencyID,(de.get(le.CurrencyID)??new Qt(0)).plus(he));break}case "Item":{if(!le.ItemID)continue;let de=yg(t,le.CatalogID,le.ItemID),xe=(de?de.IsStackable??true:true)?pe?ve:ae:pe?Oe:ye;xe.set(le.ItemID,(xe.get(le.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||d$1.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let re of new Set([...p.keys(),...d$1.keys()])){let Pe=p.get(re)??0,pe=d$1.get(re)??0,le=Pe-pe,he=n.VirtualCurrencies[re];he?(he.Amount+=le,he.UpdatedAt=r,he.Daily&&li(he.Daily.PeriodStartUtc)===li(i)?(he.Daily.Earned+=Pe,he.Daily.Spent+=pe):he.Daily={PeriodStartUtc:Pi(i),Earned:Pe,Spent:pe}):n.VirtualCurrencies[re]={Amount:le,CreatedAt:r,UpdatedAt:r,Daily:{PeriodStartUtc:Pi(i),Earned:Pe,Spent:pe}};}}if(s.ccChanged=R.size>0||V.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let re of new Set([...R.keys(),...V.keys()])){let Pe=R.get(re)??new Qt(0),pe=V.get(re)??new Qt(0),le=Pe.minus(pe),he=n.CryptoCurrencies[re];he?(he.Amount=new Qt(he.Amount).plus(le).toString(),he.UpdatedAt=r):n.CryptoCurrencies[re]={Amount:le.toString(),Frozen:"0",CreatedAt:r,UpdatedAt:r};}}if(s.itemsChanged=ae.size>0||ve.size>0||ye.size>0||Oe.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let re=n.UnstackableItems,Pe=new Set([...ae.keys(),...ve.keys(),...ye.keys(),...Oe.keys()]);for(let pe of Pe){let le=(ae.get(pe)??0)-(ve.get(pe)??0),he=(ye.get(pe)??0)-(Oe.get(pe)??0),de=le+he,st=n.Items[pe];st?(le!==0&&(st.StackableAmount+=le),he!==0&&(st.UnstackableAmount+=he),de!==0&&(st.TotalAmount+=de)):n.Items[pe]={StackableAmount:Math.max(0,le),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,de)};}for(let[pe,le]of Oe){if(le<=0)continue;let he=Object.values(re).filter(de=>de.ItemID===pe&&de.EquippedSlot==null&&(de.ExpiresAt==null||new Date(de.ExpiresAt)>i)).sort(gg).slice(0,le).map(de=>de.ItemInstanceID);for(let de of he)delete re[de];}for(let[pe,le]of ye){let he=Rg(t,pe);for(let de=0;de<le;de++){let st=d();re[st]={ItemInstanceID:st,ItemID:pe,CatalogID:he,RemainingUses:1,AcquiredAt:r};}}}o.EventToken??={};let Ri=o.EventToken;for(let re=0;;re++){let Pe,pe;if(re===0)Pe=e.Grant?.Standard?.EventTokens,pe=false;else if(re-1<Ze)Pe=xt[re-1]?.Resources?.EventTokens,pe=false;else if(re===1+Ze)Pe=e.Consume?.Standard?.EventTokens,pe=true;else break;if(!(!Pe||Pe.length===0))for(let le of Pe){let he=le.Address;if(!he||he.Type==null)continue;let de=le.Amount??0;if(de<=0)continue;let st=Cg(Ri,he.Type);if(!st)continue;let xe=st[he.EntityID];xe||(xe={},st[he.EntityID]=xe),xe.Balance??={Current:0,TotalEarned:0,TotalSpent:0},xe.Daily??={Date:Pi(i),TotalEarned:0},xe.Meta??={};let Ci=le.Source&&le.Source.length>0?le.Source:"CustomAction";pe?(xe.Balance.Current-=de,xe.Balance.TotalSpent+=de):(xe.Balance.Current+=de,xe.Balance.TotalEarned+=de,li(xe.Daily.Date)!==li(i)&&(xe.Daily={Date:Pi(i),TotalEarned:0}),xe.Daily.TotalEarned+=de,xe.Daily.EarnedBySource??={},xe.Daily.EarnedBySource[Ci]=(xe.Daily.EarnedBySource[Ci]??0)+de,xe.Daily.TriggersBySource??={},xe.Daily.TriggersBySource[Ci]=(xe.Daily.TriggersBySource[Ci]??0)+1,xe.Daily.LastTriggerBySource??={},xe.Daily.LastTriggerBySource[Ci]=r,xe.Meta.JoinedAtUtc||(xe.Meta.JoinedAtUtc=r),xe.Meta.LastEarnedAtUtc=r),s.tokensChanged=true;}}return s}function gg(o,e){return o.AcquiredAt!==e.AcquiredAt?o.AcquiredAt<e.AcquiredAt?-1:1:o.ItemInstanceID===e.ItemInstanceID?0:o.ItemInstanceID<e.ItemInstanceID?-1:1}function yg(o,e,t){let i=o?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let n=s.Items?.[t];if(n)return n}}}function Rg(o,e){let t=o?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function Cg(o,e){switch(e){case "TimedEvent":return o.TimedEvent??={};case "Quest":return o.Quest??={};case "Leaderboard":return o.Leaderboard??={};case "CoopEvent":return o.CoopEvent??={};case "Season":return o.Season??={};default:return null}}function Kl(o,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},n=new Set(t.RemovedInstanceIDs??[]),r=new Set;for(let d of Object.values(s))d?.ItemID&&r.add(d.ItemID);for(let d of n){let R=o[d]?.ItemID;R&&r.add(R);}if(r.size===0)return i;let p=d=>n.has(d)||d in s;if(e){for(let[d,R]of Object.entries(e))d in o||p(d)||R&&r.has(R.ItemID)&&i.drop.push(d);for(let[d,R]of Object.entries(o))d in e||p(d)||R&&r.has(R.ItemID)&&(i.restore[d]=R);}return i}function fo(o,e){return o===e||o.startsWith(`${e}:`)}var ts=class o{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){o.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];o.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){o.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let s=mo(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let n=this.currentState,r={...n.InventoryV2?.UnstackableItems??{}},p=mo(n,e,i,s),d=Kl(r,n.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],ae=d.drop.length>0||Object.keys(d.restore).length>0||R.length>0||V.length>0;if(ae){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let ve=n.InventoryV2.UnstackableItems;for(let ye of d.drop)delete ve[ye];for(let[ye,Oe]of Object.entries(d.restore))ve[ye]=Oe;for(let[ye,Oe]of R)ve[ye]=Oe;for(let ye of V)delete ve[ye];}this.emitResourceChanges(p,ae);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,r=t instanceof Qt?t:new Qt(t),p=s===void 0?new Qt(0):s instanceof Qt?s:new Qt(s),d=i??new Date().toISOString(),R=n[e];R?(R.Amount=new Qt(R.Amount).plus(r).toString(),p.isZero()||(R.Frozen=new Qt(R.Frozen??0).plus(p).toString()),R.UpdatedAt=d):n[e]={Amount:r.toString(),Frozen:p.toString(),CreatedAt:d,UpdatedAt:d},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,n=s[e];n||(n={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=n),n.TotalPurchases+=t,n.LastPurchasedAt=i,i>=n.DailyResetUtc?(n.DailyPurchases=t,n.DailyResetUtc=Wl(i)):n.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let n=new Date().toISOString();for(let r of t)r.RuleID&&(s.Pity[`${e}:${r.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:n});}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));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let n=s.Cycles[t];if(!n)return;n.Quests??={};let r=n.Quests[e]??={QuestID:e,Status:i};r.Status=i,i==="Claimed"&&(r.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let n=s.PermanentQuests[e]??={QuestID:e,Status:i};n.Status=i,i==="Claimed"&&(n.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,n=t[s]??={};n.Balance??={Current:0,TotalEarned:0,TotalSpent:0},n.Balance.Current=i.PointsCurrent??0,n.Balance.TotalEarned=i.PointsTotalEarned??0,n.Milestone??={};for(let r of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(n.Milestone,r);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let n=s.Steps[i.StepID]??={StepID:i.StepID};n.Progress=i.Progress,i.Completed&&(n.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let n=t.Cycles[i.CycleID];if(!n)continue;n.Quests??={},s=n.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let n=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};n.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(n.Completed=true,n.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(fo(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[n,r]of Object.entries(this.currentState.EventToken.TimedEvent))r&&((s?n!==s:!fo(n,t))||this.markMilestoneClaimed(r.Milestone??(r.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let n=this.activeEventsCache?.ActiveEvents;if(n)for(let r of n)r.Type!==e||r.TimedEventID!==t||s&&r.TokenEntityID&&r.TokenEntityID!==s||(r.Progress??={},this.markMilestoneClaimed(r.Progress.Milestone??(r.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,s){if(!e)return;let n=this.ensureLeaderboardProgress(e);(n.ScoreCycleVersion??0)<s&&(n.ScoreEarnedThisCycle=0,n.ClaimedMilestoneIDs=[],n.BracketID=null),n.CurrentScore=t,n.ScoreEarnedThisCycle=(n.ScoreEarnedThisCycle??0)+i,n.ScoreCycleVersion=s,n.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let s=false;for(let n of Object.values(i))for(let r of Object.values(n.Equipment??{}))r?.ItemInstanceID===e&&(r.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[s,n]of Object.entries(e.ChangedInstances??{}))t[s]=n,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(i)){let n=i[s];n&&n.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,s,n){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let r=this.currentState.CustomData,p={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")r.Private??={},r.Private[t]=p;else if(e==="Public")r.Public??={},r.Public[t]=p;else return;r.Version=(r.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let s=i.BuildingStates.find(n=>n.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},n=s.PendingWithdrawals??[];t.size>0&&(n=n.filter(r=>!r.TitleTransactionID||!t.has(r.TitleTransactionID))),i&&!n.some(r=>r.TitleTransactionID===i.TitleTransactionID)&&(n=[...n,i]),s.PendingWithdrawals=n;}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 is=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 ss=class{user;config;constructor(e){this.user=new ts(e),this.config=new is;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Sg(o){return o}var xg=0,bg=1500,Dg=3,rs=class{constructor(e,t,i=null,s="",n="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=s;this.loginMode=n;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 a(void 0);let i=Date.now(),s=[],n=[];for(let d of new Set(e)){let R=this.rules.get(d);if(R&&(t?.force||R.needsServer(i))){s.push(this.runRule(d,R));continue}(t?.force||!this.state.isStateFresh(d,t?.maxAgeMs))&&n.push(d);}let p=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(a(void 0))])).find(d=>!d.ok);return p&&!p.ok?p:a(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},xg),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(s=>i=s);try{let s=this.state?await this.state.readStateSlice(e):a(void 0),n=s.ok?a(void 0):s;for(let r of t)r(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=ns(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let R=this.fresh(s,i?.maxAgeMs);if(R)return a(R.data);let V=this.loginFailures.get(s);if(V)return this.loginFailures.delete(s),V;let ae=this.inflight.get(s);if(ae)return ae}let n=this.generation.get(s)??0,r=Date.now(),d=t().then(R=>{if(!R.ok)return R;let V=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:go(e,R.data,V)}),R;let ae=this.entries.get(s);if(ae&&ae.storedAt>=r)return R;let ve=go(e,R.data,V);return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:Math.min(ve??1/0,V+bg)}),R}).finally(()=>{this.inflight.get(s)===d&&this.inflight.delete(s);});return this.inflight.set(s,d),d}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let s=t.Key?t.Key:void 0,n=ns(i.view,s);if(!t.Success){this.loginFailures.set(n,b("server",t.Error??"View failed."));continue}let r=i.schema.safeParse(t.Data);r.success&&(this.loginFailures.delete(n),i.apply(r.data,s),this.put(i.view,r.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let n=Hl({Name:s,Key:t});this.used.get(n)?.n!==this.session&&(this.used.set(n,{Name:s,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>Dg||this.used.set(Hl(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(ns(e,t))?.data}put(e,t,i){this.register(e);let s=ns(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:go(e,t,n)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===i||s.startsWith(`${i}|`))&&this.drop(s);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let s=Date.now();if(!(i.expiresAt!==null&&s>=i.expiresAt)&&!(t!==void 0&&s-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(s=>t.has(s))&&this.invalidate(i);}};function ns(o,e){return e===void 0?o.key:`${o.key}|${e}`}function Hl(o){return o.Key?`${o.Name}|${o.Key}`:o.Name}function go(o,e,t){let i=o.expiresAt?.(e)??null,s=o.ttlMs!==void 0?t+o.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var os=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 Pg(e)?e:Ae.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 Pg(o){return o!==null&&Object.values(Ae).includes(o)}var Ig=8,vg=100,Tg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,$l=["GameLoop"];function Ag(o){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(o)}var as=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=Ae.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let s=this.authContext;if(!s)return c$1;let n=this.baseRequest();n.UserID=s.userID,n.ClientSessionTicket=s.clientSessionTicket,n.WalletAddress=e,n.NetworkID=t,i&&(n.WalletSignature=i);let r=await this.ctx.api.authentication.linkWallet(n);return r.ok&&r.data.PlayAccess&&this.setPlayAccess(r.data.PlayAccess),r}async unlinkWallet(e){let t=this.authContext;if(!t)return c$1;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(i);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.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(Ae.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return b("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(Ae.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let s=await this.ctx.api.authentication.loginWithEmail(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(Ae.Email);return n.ok&&this.keepEmailCredentials(e,t),n}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 s=await this.ctx.api.authentication.registerWithEmail(i);return s.ok?(this.pendingRegistration={email:e,password:t},a({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(Ae.Email);return n.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,n}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?a(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(Ae.Google)):i}async loginWithApple(e,t){if(!e?.trim())return b("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(Ae.Apple)):s}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=i,s.Platform=this.ctx.platform.getPlatform(),s.Device=this.ctx.platform.getDeviceModel(),s.DeviceID=this.ctx.platform.getDeviceID();let n=await this.ctx.api.authentication.loginWithWallet(s);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Ae.Wallet)):n}async loginWithSsoCode(e){if(!e)return b("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(Ae.iDosGames)):i}async loginWithPlatformGameTicket(e){if(!e)return b("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(Ae.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 s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=i,this.ctx.api.authentication.resetPassword(s)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==Ae.None?e:Ae.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let s=await this.ctx.api.authentication.refreshSession(i);return s.ok?(this.applyRefresh(s.data),"ok"):(Ag(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case Ae.Email:return this.loginWithEmail(t,i);case Ae.Device:case Ae.None:return this.loginWithDeviceID();case Ae.Telegram:return this.loginWithTelegram();default:return Promise.resolve(b("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 n(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let s=await this.ctx.api.authentication.resolvePlatformGameSession(i);return s.ok?(this.applyAuthContext(s.data),this.platformGameSession=!0,s.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==Ae.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===Ae.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&&Tg.test(e)}static isValidPasswordLength(e){return e.length>=Ig&&e.length<=vg}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=Ae.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($l,$l);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 kg="idos:cfg",ui=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Jl(t)}`:e&&e.length>0?`f:${Jl(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${kg}:${this.titleId}:${e}`}};function Jl(o){return [...o].map(e=>e.toLowerCase()).sort().join(",")}var Zl="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 s={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[s,n]of Object.entries(t))typeof n=="number"&&n>0&&(i[s]=n);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 `${Zl}:${this.titleId}:${e}`}versionsKey(){return `${Zl}:${this.titleId}:versions`}};var zg="idos:sec",ls=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 `${zg}:${this.titleId}`}};var wg="idos:state",us=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,s){if(!(!e||!t))try{let n={e:t,v:i,s};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}keyOf(e){return `${wg}:${this.titleId}:${e}`}};function Mg(o,e){if(!o)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return o;let i={};for(let[s,n]of Object.entries(o))t.has(s.toLowerCase())||(i[s]=n);return i}function yo(o,e,t,i){let s={...o??{}};if(!e||!t||!i)return s;for(let[n,r]of Object.entries(t))i[n]===r&&n in e&&(s[n]=e[n]);return s}function Og(o){return {...o??{}}}function Ro(o){return typeof o.StateEpoch=="string"&&o.StateEpoch.length>0?o.StateEpoch:null}var cs=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let s=this.confirmedAt[e];return s===void 0?false:t===void 0||i-s<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=Mg(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 n=Object.keys(this.versions);this.reset(e),this.notify(n);}return}let i=Date.now(),s=[];for(let[n,r]of Object.entries(t)){let p=this.versions[n];p!==r&&(p!==void 0&&r===p+1?(this.versions[n]=r,this.confirmedAt[n]=i):(delete this.versions[n],delete this.confirmedAt[n]),s.push(n),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=Og(t);let s=Date.now();this.confirmedAt={};for(let r of Object.keys(this.versions))this.confirmedAt[r]=s;this.dirty=true;let n=new Set;for(let r of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[r]!==this.versions[r]&&n.add(r);this.notify([...n]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[n,r]of Object.entries(t??{}))this.versions[n]!==r&&s.push(n),this.versions[n]=r,this.confirmedAt[n]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Yl=b("server","Title configuration is unavailable (CDN and API both failed)."),ps=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:d()}:null}get configCache(){return this.cache??=new ui(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 ls(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new cs(new us(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 c$1;let t=ui.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let n=await this.ctx.api.user.getClientState(e);if(!n.ok)return n;let r=await this.resolveTitleConfig(n.data,t,i,{Fields:e.TitleFields});return r==null?Yl:(this.finishStateHandshake(n.data,s),await this.restoreSections(n.data.TitleConfigVersion,r),await this.applyClientState(n.data,r,void 0,void 0),this.ctx.cache.acceptLoginViews(n.data.Views),await this.applyLocalization(n.data.Localization),await this.flushState(s),n)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let n=this.stateStore.currentEpoch;n&&(e.KnownStateEpoch=n);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=yo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=Ro(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,i,s){let n=e.TitleConfigVersion;if(i&&n&&i.v===n)return i.c;if(e.TitleConfigUrl){let p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return n&&await this.configCache.write(t,n,p),p}let r=await this.fetchConfigFromApi(s);return r!=null?(n&&await this.configCache.write(t,n,r),r):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return c$1;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=ui.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let r=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let p=await this.ctx.api.user.getClientStateExcept(i);if(!p.ok)return p;let d=await this.resolveTitleConfig(p.data,s,n,{ExcludeFields:t??[]});return d==null?Yl:(this.finishStateHandshake(p.data,r),await this.restoreSections(p.data.TitleConfigVersion,d),await this.applyClientState(p.data,d,e,t),this.ctx.cache.acceptLoginViews(p.data.Views),await this.applyLocalization(p.data.Localization),await this.flushState(r),p)}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let i=t,s={};for(let[n,r]of Object.entries(await this.sectionCache.read(e)))i[n]==null&&(s[n]=r);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((n,r)=>{i[n]!=null||r==null||(s[n]=r,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let r=await this.fetchLocalizationFromCdn(e.Url);if(r!=null)return await this.localizationCache.write(t,i,r),r}let n=await this.fetchLocalizationFromApi(t,s?.v??0);return n??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let n=s.data;if(n.NotModified)return null;let r=n.Entries??{},p=n.Version??0,d=n.Locale??e;return p>0&&await this.localizationCache.write(d,p,r),r}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):c$1}async getUserState(e){let t=this.baseRequest();if(!t)return c$1;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let n=yo(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let r=i.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([R,V])=>r[R]!==V||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(n,p);let d=Ro(s.data);return d&&(this.stateStore.afterSliceRead(d,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return c$1;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 c$1;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 c$1;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let s=this.baseRequest();if(!s)return c$1;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=i;let n=await this.ctx.api.user.addUsageTime(s);return n.ok&&this.ctx.emitter.emit("user:usageTimeAdded",n.data),n}async deleteUserAccount(){let e=this.baseRequest();if(!e)return c$1;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 c$1;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,s){let n=i?.includes("GameLoop")===true,r=s?.includes("GameLoop")===true,p=n?this.ctx.data.user.state?.GameLoop:void 0,d=r?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let R=this.ctx.data.user.state;n&&R&&R.GameLoop==null&&(R.GameLoop=p);let V=this.ctx.data.config.titlePublicConfiguration;r&&V&&V.GameLoop==null&&(V.GameLoop=d),this.ctx.emitter.emit("user:clientStateReceived",e);}};var ds=class{constructor(e){this.ctx=e;}ctx;async convert(e,t,i,s,n,r){if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(n<=0)return b("client","Amount must be positive.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===ct.Crypto||i===ct.Crypto)return b("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(n)),TransactionID:r&&r.length>0?r:`convert_${e}_${t}_to_${i}_${s}_${d()}`},d$1=await this.ctx.api.currency.convert(p);if(d$1.ok){let R=d$1.data,V={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.SourceID,Amount:R.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.TargetID,Amount:R.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return d$1}async cryptoConvert(e,t,i,s,n,r){let p=n instanceof Qt?n:new Qt(n);if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(p.lte(0))return b("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===ct.Virtual&&i===ct.Virtual)return b("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ct.Virtual&&!p.isInteger())return b("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:p.toString(),TransactionID:r&&r.length>0?r:`crypto_convert_${e}_${t}_to_${i}_${s}_${d()}`},R=await this.ctx.api.currency.cryptoConvert(d$1);if(R.ok){let V=R.data,ae=[],ve=[];if(V.SourceType===ct.Virtual&&ae.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===ct.Virtual&&ve.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),ae.length>0||ve.length>0){let ye={Consume:ae.length>0?{Standard:{Entries:ae}}:null,Grant:ve.length>0?{Standard:{Entries:ve}}:null};this.ctx.data.user.applyResourceOperation(ye,this.ctx.data.config.itemDefinitions);}V.SourceType===ct.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new Qt(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===ct.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new Qt(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return R}};var ms=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let s=e.trim();if(!s)return b("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${s}_${d()}`};t&&t.length>0&&(n.FodderInstanceIDs=[...t]);let r=await this.ctx.api.item.upgradeLevel(n);return r.ok&&(this.ctx.data.user.patchEquippedItemLevel(r.data.ItemInstanceID??s,r.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",r.data)),r}async upgradeLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let s of i.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var Xl=z.object({OptionID:z.string().nullish(),Name:z.string().nullish(),Cost:bt.nullish(),AllowedPlatforms:z.array(Vi).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),ue=z.record(z.string(),Xl),Eg=z.object({Store:Ni,Receipt:z.string(),Signature:z.string().nullish()}).passthrough();var Ii={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},Co=z.object({ConfirmationID:z.string(),Url:z.string(),Status:z.string(),PriceCredits:z.number(),ExpiresAt:c}).passthrough(),eu=z.object({Linked:z.boolean(),Credits:z.number(),TopUpUrl:z.string().nullish()}).passthrough(),Ug={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"},So=z.object({ServerTimeUtc:c,OfferID:z.string(),Count:z.number(),Resources:M.nullish(),Inventory:K.nullish(),CreditsConfirmation:Co.nullish()}),tu=z.array(Ie(So)),qg=z.object({OfferID:z.string(),TotalPurchases:z.number(),DailyPurchases:z.number(),DailyResetUtc:c,LastPurchasedAt:c}),Bg=z.object({SlotKey:z.string(),InstanceKey:z.string(),OfferID:z.string().nullish(),Purchases:z.number(),LastPurchasedAt:c}),iu=z.object({Purchases:z.record(z.string(),qg).nullish(),Rotations:z.record(z.string(),Bg).nullish()}).passthrough().transform(o=>o),Pt=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),fs=z.object({Schedule:fe.nullish(),Gate:Z.nullish()}).passthrough(),Lg={Fixed:"Fixed",Title:"Title",Player:"Player"},Gg=z.object({OfferID:z.string().nullish(),Weight:z.number().nullish(),Gate:Z.nullish()}).passthrough(),su=z.object({Mode:z.string().nullish(),OfferID:z.string().nullish(),Pool:z.array(Gg).nullish(),Salt:z.string().nullish(),PerInstanceCap:z.number().nullish()}).passthrough(),Fg=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Rotation:Q.nullish()}).passthrough(),Vg=z.object({SlotID:z.string().nullish(),Identity:Pt.nullish(),Availability:fs.nullish(),Rotation:su.nullish(),Presets:Fg.nullish()}).passthrough(),Ng=z.object({Identity:Q.nullish(),Availability:Q.nullish()}).passthrough(),_g=z.object({SectionID:z.string().nullish(),Identity:Pt.nullish(),Availability:fs.nullish(),Slots:z.record(z.string(),Vg).nullish(),UniqueOffersInSection:z.boolean().nullish(),Presets:Ng.nullish()}).passthrough(),nu=z.object({Sections:z.record(z.string(),_g).nullish()}).passthrough(),jg=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Layout:Q.nullish()}).passthrough(),Wg=z.object({StoreID:z.string().nullish(),Identity:Pt.nullish(),Availability:fs.nullish(),Layout:nu.nullish(),Presets:jg.nullish()}).passthrough(),ru=z.object({Options:ue.nullish(),CompareAt:z.record(z.string(),bt).nullish()}).passthrough(),ou=z.object({Grant:H.nullish()}).passthrough(),au=z.object({Schedule:fe.nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Qg=z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish(),Availability:Q.nullish()}).passthrough(),Kg=z.object({OfferID:z.string().nullish(),Identity:Pt.nullish(),Pricing:ru.nullish(),Reward:ou.nullish(),Availability:au.nullish(),Presets:Qg.nullish()}).passthrough(),Hg=z.object({Identity:z.record(z.string(),Pt).nullish(),Availability:z.record(z.string(),fs).nullish(),Layout:z.record(z.string(),nu).nullish(),Rotation:z.record(z.string(),su).nullish(),Pricing:z.record(z.string(),ru).nullish(),Reward:z.record(z.string(),ou).nullish(),OfferAvailability:z.record(z.string(),au).nullish()}).passthrough(),gs=z.object({Stores:z.record(z.string(),Wg).nullish(),StoreOffers:z.record(z.string(),Kg).nullish(),Presets:Hg.nullish()}).passthrough(),$g=z.object({PurchasedTotal:z.number(),PurchasedToday:z.number(),PurchasedThisRotation:z.number(),RemainingTotal:z.number().nullish(),RemainingToday:z.number().nullish(),IsFirstPurchaseAvailable:z.boolean(),SoldOut:z.boolean(),AvailableAtUtc:c.nullish()}).passthrough(),Jg=z.object({OptionID:z.string(),Name:z.string().nullish(),Cost:bt.nullish(),CompareAtCost:bt.nullish(),DiscountPercent:z.number().nullish(),IsFree:z.boolean(),IsAdPaid:z.boolean(),IsStorePaid:z.boolean(),IsCreditsPaid:z.boolean().nullish(),CreditsPrice:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Zg=z.object({OfferID:z.string(),Identity:Pt.nullish(),PriceOptions:z.array(Jg).nullish(),Rewards:H.nullish(),State:$g.nullish()}).passthrough(),Yg=z.object({SlotID:z.string(),Identity:Pt.nullish(),SortOrder:z.number(),RotationMode:z.string().nullish(),RotationInstanceKey:z.string().nullish(),RefreshesAtUtc:c.nullish(),RemainingThisRotation:z.number().nullish(),Offer:Zg.nullish()}).passthrough(),Xg=z.object({SectionID:z.string(),Identity:Pt.nullish(),SortOrder:z.number(),Slots:z.array(Yg).nullish()}).passthrough(),ey=z.object({StoreID:z.string(),Identity:Pt.nullish(),SortOrder:z.number(),ScheduleInstanceKey:z.string().nullish(),ExpiresAtUtc:c.nullish(),Sections:z.array(Xg).nullish()}).passthrough(),ys=z.object({ServerTimeUtc:c,Stores:z.array(ey).nullish(),AdCreditBalance:z.number()}).passthrough(),It={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},ty="OFFER_NOT_IN_ROTATION";var lu="Store",uu={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:o=>{let e=null;for(let t of o.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},Rs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(uu,{schema:ys,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return b("client","OfferID is required.");if(t<1)return b("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${s.userID}_${d()}`},r=await this.ctx.api.store.purchase(n);if(r.ok&&!r.data.CreditsConfirmation){let p=r.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return r}async purchaseWithCredits(e,t=1,i={}){let s=await this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot});if(!s.ok||!s.data.CreditsConfirmation)return s;let n=s.data.CreditsConfirmation,r=()=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:n.ConfirmationID});if(v()){let R=await w({titleID:this.ctx.settings.titleID,confirmationID:n.ConfirmationID});if(R.ok)return await r();if(R.error==="DECLINED")return b("server","CREDITS_CONFIRMATION_DECLINED");if(R.error==="NOT_ENOUGH_CREDITS")return b("server","NOT_ENOUGH_CREDITS")}i.onConfirmation?.(n);let p=Math.max(1e3,i.pollMs??2500),d=Date.parse(n.ExpiresAt)+6e4;for(;;){if(i.signal?.aborted)return b("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>d)return b("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(ae=>setTimeout(ae,p));let R=await this.getCreditsConfirmation(n.ConfirmationID);if(!R.ok)continue;let V=R.data.Status;if(V!==Ii.Pending)return V===Ii.Declined?b("server","CREDITS_CONFIRMATION_DECLINED"):V===Ii.Expired?b("server","CREDITS_CONFIRMATION_EXPIRED"):await r()}}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):c$1}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):c$1}async purchaseBatch(e){if(!e||e.length===0)return b("client","purchases is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||!n.Data.OfferID||(this.ctx.data.user.patchStorePurchase(n.Data.OfferID,n.Data.Count,n.Data.ServerTimeUtc),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(lu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(lu,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(uu,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=s.RefreshesAtUtc;n&&(e===null||Date.parse(n)<Date.parse(e))&&(e=n);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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 Cs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return c$1;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return c$1;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?a(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return b("client","Receipt is required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},n=await this.ctx.api.purchase.validatePurchase(s);return n.ok&&this.applyValidation(n.data),n}async buyWithTelegramStars(e,t){if(!e)return b("client","productID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(i);return s.ok&&t?.open!==false&&this.ctx.platform.openInvoice(s.data.InvoiceLink),s}async validatePurchasesBatch(e){if(!e||e.length===0)return b("client","receipts is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let s of i.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var cu=3,iy=700,Ss=class{constructor(e){this.ctx=e;s()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return ai(e)}platformTopUp=async e=>{let t$1=this.ctx.auth.context?.userID;if(!t$1)return false;let i=await t({titleID:this.ctx.settings.titleID,userID:t$1,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<=cu;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===cu)break;await Ot(iy);}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===Fi.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!==Fi.CryptoCurrency||!i.CurrencyID)continue;let s=Number(i.Amount??0);if(!(s>0))continue;let n=this.cryptoBalance(i.CurrencyID);return n>=s?null:{currencyID:i.CurrencyID,required:s,available:n,missing:s-n}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var pu="Lootbox",xs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(pu,e);if(t){let n={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection(pu,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s){if(!e)return b("client","LootboxID is required.");if(t<1)return b("client","Count must be at least 1.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,RelatedEntityID:`lootbox_${e}_${i??"default"}_${d()}`},r=await this.ctx.api.lootbox.open(n);if(r.ok){let p=r.data;p.TriggeredPity&&p.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,p.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",p);}return r}};var xo="Reward";function bo(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var bs=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(xo)?.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(xo,e);if(t){let n={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(xo,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return c$1;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 c$1;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 c$1;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${d()}`},s=await this.ctx.api.reward.claimDailyReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchDailyCalendarState(n.CalendarID,n.DailyState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",n);}return s}async collectIdleAccrual(e){if(!bo(e))return b("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${d()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let s=i.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return i}async claimComebackReward(e){if(!bo(e))return b("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${d()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return i}async claimReward(e){if(!bo(e))return b("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${d()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return i}};var Ds="Tutorial",hu={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"]},Ps=class{constructor(e){this.ctx=e;e.cache.bindLoginView(hu,{schema:Ki,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(Ds)?.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(Ds,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ds,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(hu,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return c$1;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}_${d()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return b("client","FlowID is required.");if(!t||t.length===0)return b("client","stepIDs is required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${d()}`},n=await this.ctx.api.tutorial.completeStepsBatch(s);return n.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",n.data)),n}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 b("client","FlowID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${d()}`},s=await this.ctx.api.tutorial.claimFlowReward(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let s=e?.trim();if(!s)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:s},r=await t(n);return r.ok&&(this.applyFlowView(r.data),this.ctx.emitter.emit(i.event,r.data)),r}async stepCall(e,t,i,s){let n=e?.trim(),r=t?.trim();if(!n)return b("client","FlowID is required.");if(!r)return b("client","StepID is required.");if(!this.ctx.auth.context)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:r};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let d=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,R=await i(p);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(n,r,d,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Ds)?.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 Is=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return c$1;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 c$1;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 b("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","campaignID is required.");if(!t)return b("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.CampaignID=e,s.WalletAddress=t,i&&(s.Amount=i);let n=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return n.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",n.data),n}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Ee=z.object({Username:z.string().nullish(),Country:z.string().nullish(),AvatarUrl:z.string().nullish(),Premium:z.boolean().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),BoardRank:z.number().nullish()}).passthrough();var sy={Global:"Global",Announcement:"Announcement",Group:"Group"},mu=z.enum(["Global","Announcement","Group"]).catch("Global"),ny={None:"None",Language:"Language",Region:"Region"},ry=z.enum(["None","Language","Region"]).catch("None"),oy={Anyone:"Anyone",Friends:"Friends"},ay=z.enum(["Anyone","Friends"]).catch("Anyone"),ly={Reject:"Reject",Mask:"Mask"},uy=z.enum(["Reject","Mask"]).catch("Reject"),cy={Player:"Player",Publisher:"Publisher",System:"System"},py=z.enum(["Player","Publisher","System"]).catch("Player"),hy={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var dy=z.object({DisplayNameKey:z.string().nullish(),SortOrder:z.number().nullish(),IconPath:z.string().nullish(),JoinedByDefault:z.boolean().nullish()}).passthrough(),fu=z.object({Gate:Z.nullish(),Schedule:fe.nullish()}).passthrough(),gu=z.object({Gate:Z.nullish(),Limits:Re.nullish(),MaxLength:z.number().nullish()}).passthrough(),yu=z.object({HotTailSize:z.number().nullish(),HistoryHours:z.number().nullish()}).passthrough(),my=z.object({Availability:Q.nullish(),Write:Q.nullish(),Retention:Q.nullish()}).passthrough(),fy=z.object({ChannelID:z.string().nullish(),Identity:dy.nullish(),Type:mu.nullish(),GroupSource:z.string().nullish(),Partitioning:ry.nullish(),Capacity:z.number().nullish(),Availability:fu.nullish(),Write:gu.nullish(),Retention:yu.nullish(),Presets:my.nullish()}).passthrough(),gy=z.object({IsEnabled:z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:ay.nullish(),Limits:Re.nullish(),MaxLength:z.number().nullish(),HistoryHours:z.number().nullish(),MaxConversations:z.number().nullish()}).passthrough(),yy=z.object({BlockedTerms:z.array(z.string()).nullish(),BlockedTermAction:uy.nullish(),MaxIgnoreListSize:z.number().nullish(),ReportsEnabled:z.boolean().nullish(),ReportLimits:Re.nullish()}).passthrough(),Ry=z.object({MinIntervalSeconds:z.number().nullish(),MaxMessagesPerPoll:z.number().nullish(),MaxHistoryPageSize:z.number().nullish()}).passthrough(),Cy=z.object({Availability:z.record(z.string(),fu).nullish(),Write:z.record(z.string(),gu).nullish(),Retention:z.record(z.string(),yu).nullish()}).passthrough(),Ru=z.object({IsEnabled:z.boolean().nullish(),Channels:z.record(z.string(),fy).nullish(),Direct:gy.nullish(),Moderation:yy.nullish(),Polling:Ry.nullish(),Presets:Cy.nullish()}).passthrough(),Sy=z.object({LastReadAt:z.string().nullish(),LastReadMessageID:z.string().nullish(),Left:z.boolean().nullish()}).passthrough(),du=z.object({LastAt:z.string().nullish(),DailyCount:z.number().nullish(),DailyResetUtc:z.string().nullish(),TotalCount:z.number().nullish(),LastTextHash:z.string().nullish()}).passthrough();z.object({MutedUntil:z.string().nullish(),MuteReason:z.string().nullish(),Ignored:z.array(z.string()).nullish(),Channels:z.record(z.string(),Sy).nullish(),Limits:z.record(z.string(),du).nullish(),ReportLimits:du.nullish()}).passthrough();var Do=z.object({RoomID:z.string().nullish(),SentAt:z.string().nullish(),MessageID:z.string().nullish()}).passthrough(),vs=z.object({RoomID:z.string().nullish(),ChannelID:z.string().nullish(),MessageID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderProfile:Ee.nullish(),AuthorType:py.nullish(),Text:z.string().nullish(),SentAt:z.string().nullish()}).passthrough(),xy=z.object({ChannelID:z.string().nullish(),RoomID:z.string().nullish(),DisplayNameKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),Type:mu.nullish(),CanWrite:z.boolean().nullish(),WriteBlockedReason:z.string().nullish(),SlowModeSeconds:z.number().nullish(),MaxLength:z.number().nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),Ts=z.object({Channels:z.array(xy).nullish(),PollIntervalSeconds:z.number().nullish(),MutedUntil:z.string().nullish(),MuteReason:z.string().nullish()}).passthrough(),by=z.object({RoomID:z.string().nullish(),Messages:z.array(vs).nullish(),NextCursor:Do.nullish(),UnreadCount:z.number().nullish(),ServedFromDatabase:z.boolean().nullish()}).passthrough(),Cu=z.object({Rooms:z.array(by).nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),Su=z.object({RoomID:z.string().nullish(),Messages:z.array(vs).nullish(),NextBefore:Do.nullish()}).passthrough(),xu=z.object({Message:vs.nullish(),Moderated:z.boolean().nullish()}).passthrough(),bu=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Ee.nullish(),MaxLength:z.number().nullish()}).passthrough(),Dy=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Ee.nullish(),LastMessage:vs.nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),Du=z.object({Conversations:z.array(Dy).nullish()}).passthrough(),pi=z.object({Ignored:z.array(z.string()).nullish(),Cursor:Do.nullish(),Joined:z.boolean().nullish()}).passthrough(),Pu=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish()}).passthrough(),Ke={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 Iu="Chat",vu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},As=class{constructor(e){this.ctx=e;e.cache.bindLoginView(vu,{schema:Ts,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(Iu,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Iu,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(vu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return c$1;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 c$1;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let s of i.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return i}async getHistory(e,t,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),i&&(s.Limit=i),this.ctx.api.chat.getHistory(s)):c$1}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return c$1;s.ChannelID=e,s.Text=t,i&&(s.Locale=i);let n=await this.ctx.api.chat.sendMessage(s);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.Text=t;let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):c$1}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):c$1}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(i);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):c$1}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):c$1}async reportMessage(e,t,i,s){let n=this.ctx.authedRequest();return n?(n.RoomID=e,n.MessageID=t,n.Reason=i,s&&(n.Comment=s),this.ctx.api.chat.reportMessage(n)):c$1}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):c$1}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):c$1}resetCursors(){this.cursors.clear();}};var Py={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},Iy=z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),vy={Player:"player",Title:"title",Creator:"creator"},hi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Tu=z.object({Configured:z.boolean().nullish(),PublicKey:z.string().nullish()}).passthrough(),Ty=z.object({TitleID:z.string().nullish(),Topic:z.string().nullish()}).passthrough(),Po=z.object({EndpointHash:z.string().nullish(),Transport:Iy.nullish(),Locale:z.string().nullish(),Topics:z.array(Ty).nullish()}).passthrough(),Au=z.object({Configured:z.boolean().nullish(),Subscriptions:z.array(Po).nullish()}).passthrough(),vt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var Ay="IDOS_PLATFORM_PUSH_REQUEST",ky="IDOS_PLATFORM_PUSH_RESPONSE",zy=12e4;function ku(o){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let s=false,n=d=>{s||(s=true,window.removeEventListener("message",r),clearTimeout(p),i(d));},r=d=>{let R=d?.data;!R||R.type!==ky||R.requestId!==t||f.includes(d.origin)&&n(R.ok===true);},p=setTimeout(()=>n(false),zy);window.addEventListener("message",r);for(let d of f)try{e.postMessage({type:Ay,requestId:t,titleID:o},d);}catch{}})}var ks=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),s=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,i.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return vt.Unsupported;if(this.isEmbedded())return vt.Embedded;if(!this.isSupported())return vt.Unsupported;let t=Notification.permission;return t==="denied"?vt.Blocked:t!=="granted"?vt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?vt.Subscribed:vt.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return b("client","Push notifications are not available for this title.");if(this.isEmbedded())return await ku(this.ctx.settings.titleID)?a({Where:"portal",Subscription:null}):b("client","The portal did not complete the subscription.");if(!this.isSupported())return b("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return b("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let r=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:wy(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return c$1;let d=r.toJSON();p.PushEndpoint=d.endpoint,p.PushP256dh=d.keys?.p256dh,p.PushAuth=d.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(p);return R.ok?(this.ctx.emitter.emit("push:subscribed",R.data),a({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return c$1;if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return b("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):c$1}async unsubscribeByHash(e){if(!e)return b("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 wy(o){let e=o.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(o.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return i}var zs=Object.freeze({}),ws=class{constructor(e){this.ctx=e;}ctx;table={...zs};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),s=this.lookup(i)??this.lookup(e);return s===void 0?this.onMissing(e):t?My(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...zs},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 c$1;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:r}=i.data,p=null;if(r){let d=await this.loadTableFromApi(r);d.ok&&(p=d.data.table);}return this.table=n,this.fallbackTable=p,this.currentFallbackLocale=r,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:r,entryCount:Object.keys(n).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):c$1}reset(){this.table={...zs},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:d()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return c$1;t.Locale=e;let i=await this.cache.read(zu(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let n=s.data,r=n.Locale??zu(e),p=n.Version??0;if(n.NotModified){let R=i??await this.cache.read(r);return {ok:true,data:{locale:r,table:R?.t??{...zs},fallbackLocale:n.FallbackLocale??null}}}let d=n.Entries??{};return p>0&&await this.cache.write(r,p,d),{ok:true,data:{locale:r,table:d,fallbackLocale:n.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let s=this.pluralCategory(i),n=`${e}.${s}`;if(this.lookup(n)!==void 0)return n;let r=`${e}.other`;return this.lookup(r)!==void 0?r: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 My(o,e){return o.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function zu(o){return o.trim().replace(/_/g,"-").toLowerCase()}var Io="Quest",Oy={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:o=>{let e=Date.now(),t=null,i=[...Object.values(o.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(o.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let n=Date.parse(s??"");!Number.isNaN(n)&&n>e&&(t===null||n<t)&&(t=n);}return t}},Ms=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let s=e.cache.configSection(Io)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let r of Object.keys(s)){let p=Date.parse(n[r]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=i&&t<p)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(Io,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Io,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(Oy,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let s=i.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return c$1;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 b("client","QuestID is required.");if(!this.ctx.auth.context)return c$1;let s=t&&t.trim().length>0?t.trim():void 0,n={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${d()}`},r=await this.ctx.api.quest.claimQuestReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return r}async claimQuestRewardsBatch(e){if(!e||e.length===0)return b("client","quests is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchQuestStatus(n.Data.QuestID,n.Data.CycleID,"Claimed"),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${d()}`},r=await this.ctx.api.quest.claimMilestoneReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return r}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchMilestoneClaimed(n.Data.CycleID,n.Data.MilestoneID),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${d()}`},r=await this.ctx.api.quest.claimGroupCompletionReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return r}async addQuestProgress(e,t){let i=e.trim();if(!i)return b("client","MetricID is required.");if(t<0)return b("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},n=await this.ctx.api.quest.addQuestProgress(s);return n.ok&&(this.ctx.data.user.patchQuestProgressUpdates(n.data.Updates),this.ctx.emitter.emit("quest:progressAdded",n.data)),n}};var wu=z.object({}).passthrough().transform(o=>o);var Ey=z.object({Order:z.number().nullish(),Type:z.string().nullish(),DurationSec:z.number().nullish(),BonusMultiplier:z.number().nullish()}).passthrough(),Uy=z.object({Schedule:z.array(Ey).nullish(),RepeatCycle:z.boolean().nullish(),MaxCycles:z.number().nullish()}).passthrough(),qy=z.object({IsActive:z.boolean().nullish(),CurrentPhaseEndUtc:c.nullish(),NextBonusStartUtc:c.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentPhaseIndex:z.number().nullish(),ActiveBonusMultiplier:z.number().nullish()}).passthrough(),By=z.object({Milestones:Q.nullish()}).passthrough(),vo=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Category:z.string().nullish(),Token:Wt.nullish(),TokenSources:z.array(nt).nullish(),ClaimMode:z.string().nullish(),Milestones:z.record(z.string(),Le).nullish(),Presets:By.nullish(),BonusWindow:Uy.nullish()}).passthrough(),Ly=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Content:vo.nullish(),ClaimGraceHours:z.number().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Gy=z.object({TimedEventID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:fe.nullish(),Content:vo.nullish(),Events:z.array(Ly).nullish(),Gate:Z.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Fy=z.object({MaxConcurrentEvents:z.number().nullish()}).passthrough(),Vy=z.object({Milestones:z.record(z.string(),ri).nullish()}).passthrough(),Os=z.object({Definitions:z.record(z.string(),Gy).nullish(),Settings:Fy.nullish(),Presets:Vy.nullish()}).passthrough(),Ny=z.object({Type:Di,TimedEventID:z.string(),CurrentChainedEventID:z.string().nullish(),Content:vo.nullish(),Progress:wu.nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),NextMilestone:Le.nullish(),BonusWindow:qy.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentEventOrder:z.number().nullish(),TotalEventsInChain:z.number().nullish(),TokenEntityID:z.string().nullish()}).passthrough(),Es=z.object({ActiveEvents:z.array(Ny).nullish()}).passthrough(),Mu=z.object({Tokens:z.record(z.string(),wu).nullish()}),To=z.object({Type:Di.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),Ao=z.object({Type:Di.nullish(),LteID:z.string().nullish(),MilestoneID:z.string().nullish(),TokenEntityID:z.string().nullish(),Rewards:M.nullish(),Inventory:K.nullish()}),_y=z.object({Type:Di.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),ko=z.array(Ie(Ao)),Ou=z.array(Ie(To)),Eu=z.array(Ie(_y)),at={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Uu="TimedEvent",qu={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:o=>{let e=null;for(let t of o.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Us=class{constructor(e){this.ctx=e;e.cache.bindLoginView(qu,{schema:Es,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(qu,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return c$1;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(Uu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Uu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,s,n,r,p=1){if(!t)return b("client","LteID is required.");if(!i)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c$1;let d={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:r,RollMultiplier:p},R=await this.ctx.api.timedEvent.grantTokens(d);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",R.data)),R}async spendTokens(e,t,i){if(!t)return b("client","LteID is required.");if(i<=0)return b("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},n=await this.ctx.api.timedEvent.spendTokens(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",n.data)),n}async claimMilestone(e,t,i){if(!t||!i)return b("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},n=await this.ctx.api.timedEvent.claimMilestone(s);if(n.ok){let r=n.data;this.ctx.data.user.applyResourcesWithDelta(r.Rewards,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,r.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",r);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;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 c$1;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 b("client","spends is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return b("client","grants is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let s=i.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var jy=z.object({UserID:z.string(),Score:j.nullish(),Rank:z.number().nullish(),LastScoreUpdateUtc:c.nullish(),IpHash:z.string().nullish(),PublicProfile:Ee.nullish(),SeasonTierAtCycleEnd:z.number().nullish()}).passthrough(),vi=z.object({LeaderboardID:z.string(),CycleVersion:z.number().nullish(),TotalParticipants:j.nullish(),CycleEndUtc:c.nullish(),TopUsers:z.array(jy).nullish(),BracketID:z.string().nullish()}),Wy=z.object({CycleKey:z.string().nullish(),CycleEndUtc:c.nullish(),ClaimDeadlineUtc:c.nullish(),MilestoneTokensEarned:j.nullish(),ClaimableMilestoneIDs:z.array(z.string()).nullish(),CycleIndex:z.number().nullish(),ChainedEventID:z.string().nullish()}).passthrough(),qs=z.object({LeaderboardID:z.string(),CurrentScore:j.nullish(),LastKnownRank:z.number().nullish(),HasUnclaimedReward:z.boolean().nullish(),UnclaimedRewardRank:z.number().nullish(),ScoreEarnedThisCycle:j.nullish(),MilestoneTokensEarned:j.nullish(),TokenEntityID:z.string().nullish(),NextMilestone:Le.nullish(),HasUnclaimedMilestone:z.boolean().nullish(),GrantedPremiumTiers:z.record(z.string(),z.array(z.string())).nullish(),ClaimableGraceCycles:z.array(Wy).nullish()}),Bs=z.object({LeaderboardID:z.string(),NewScore:j,CycleVersion:z.number()}),Ls=z.object({ServerTimeUtc:c,LeaderboardID:z.string(),Rank:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Gs=z.object({ServerTimeUtc:c,LeaderboardID:z.string(),MilestoneID:z.string(),Resources:M.nullish(),Inventory:K.nullish()}),Bu=z.array(Ie(vi)),Fs=z.array(Ie(qs)),Lu=z.array(Ie(Ls)),Gu=z.array(Ie(Gs)),Fu=z.array(Ie(Bs)),Qy=z.object({LeaderboardID:z.string(),CycleReward:Ie(Ls).nullish(),Milestones:z.array(Ie(Gs)).nullish()}),Vu=z.array(Qy),Ky=z.object({LeaderboardID:z.string(),Leaderboard:Ie(vi).nullish(),Progress:Ie(qs).nullish()}),Nu=z.array(Ky),Hy=z.string(),_u=z.object({Rank:z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:no.nullish()}).passthrough(),$y=z.object({RankRewards:z.array(_u).nullish()}).passthrough(),Jy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Zy=z.object({Milestones:Q.nullish(),RankRewards:Q.nullish()}).passthrough(),Yy=z.object({LeaderboardID:z.string(),DisplayName:z.string().nullish(),ScoreDisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),IsEnabled:z.boolean().nullish(),ScoreAggregation:Hy.nullish(),Schedule:fe.nullish(),ChainEvents:z.array(Jy).nullish(),Gate:Z.nullish(),TopUsersLimit:z.number().nullish(),MinScoreToEnterTop:z.number().nullish(),BracketSize:z.number().nullish(),LinkedSeasonChainID:z.string().nullish(),RankRewards:z.array(_u).nullish(),Milestones:z.record(z.string(),Le).nullish(),Presets:Zy.nullish(),MilestoneClaimMode:z.string().nullish(),MilestoneClaimGraceHours:z.number().nullish(),ScoreSources:z.array(nt).nullish()}).passthrough(),Xy=z.object({Milestones:z.record(z.string(),ri).nullish(),RankRewards:z.record(z.string(),$y).nullish()}).passthrough(),Vs=z.object({Definitions:z.record(z.string(),Yy).nullish(),Presets:Xy.nullish()}).passthrough(),Ne={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 ju="Leaderboard",Wu={key:"leaderboard.progress",login:"LeaderboardProgress",ttlMs:5*6e4,dependsOn:["Leaderboard","EventToken"],invalidateOn:["leaderboard:scoreSubmitted","leaderboard:scoresSubmittedBatch","leaderboard:cycleRewardClaimed","leaderboard:cycleRewardsClaimedBatch","leaderboard:milestoneClaimed","leaderboard:milestonesClaimedBatch","leaderboard:allRewardsClaimedBatch"]},Ns=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Wu,{schema:Fs,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(ju,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ju,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","LeaderboardID is required.");if(t<=0)return b("client","Score must be positive.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(i);if(s.ok){let n=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),n.NewScore,t,n.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",n);}return s}async submitScoreFromSource(e,t,i,s,n=1){if(!e)return b("client","LeaderboardID is required.");if(!t)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},p=await this.ctx.api.leaderboard.submitScoreFromSource(r);if(p.ok){let d=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),d.NewScore,d.NewScore,d.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",d);}return p}async claimCycleReward(e){if(!e)return b("client","LeaderboardID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return i}async claimMilestone(e,t,i){if(!e||!t)return b("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},n=await this.ctx.api.leaderboard.claimMilestone(s);if(n.ok){let r=n.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",r);}return n}async getFriendsLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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(b("client","leaderboardIDs is required.")):this.ctx.cache.read(Wu,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return b("client","scores is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let n=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(n),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let r of s.Milestones??[])!r.Success||!r.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(n,r.Data.MilestoneID),r.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.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 b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let s of i.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var zo=z.object({}).passthrough().transform(o=>o),_s=z.object({SeasonChainID:z.string(),CycleIndex:z.number().nullish(),Season:z.lazy(()=>$u).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:j.nullish(),UserState:zo.nullish(),NextTier:z.lazy(()=>Hu).nullish()}).passthrough(),Qu=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),AmountGranted:j.nullish(),NewStatusTokens:j.nullish(),OldTier:z.number().nullish(),NewTier:z.number(),TierUp:z.boolean().nullish()}),wo=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),TierNumber:z.number(),Resources:M.nullish(),Inventory:K.nullish()}),Ku=gt(wo);var Hu=z.object({Tier:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredTokens:j.nullish(),TierReachedReward:H.nullish()}).passthrough(),$u=z.object({SeasonID:z.string().nullish(),Order:z.number().nullish(),DurationSec:j.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(Hu).nullish(),LinkedCollectionID:z.string().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough();var eR=z.object({SeasonChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:fe.nullish(),Seasons:z.array($u).nullish(),GrantTokensAccessMode:z.string().nullish(),Gate:Z.nullish()}).passthrough(),js=z.object({Chains:z.record(z.string(),eR).nullish()}).passthrough(),Ut={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Ju="Season",Zu={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:o=>{let e=Date.parse(o.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Zu,{schema:_s,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ju,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ju,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(Zu,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(b("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","SeasonChainID is required.");if(t<=0)return b("client","Amount must be positive.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${d()}`},s=await this.ctx.api.season.grantStatusTokens(i);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","TierNumber must be positive.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${d()}`},s=await this.ctx.api.season.claimTierReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",n);}return s}async claimTierRewardsBatch(e,t){if(!e)return b("client","SeasonChainID is required.");let i=(t??[]).filter(r=>r>0);if(i.length===0)return b("client","TierNumbers is required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${d()}`},n=await this.ctx.api.season.claimTierRewardsBatch(s);if(n.ok){let r=n.data;for(let p of r.Items??[]){let d=p.Data?.TierNumber;p.Success&&typeof d=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,d);}this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",r);}return n}};var Yu="Premium",Qs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Yu,e);if(t){let n={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",n),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(Yu,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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 b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(i);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,i="Default",s=1){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,RelatedEntityID:`premium_purchase_${e}_${t}`},r=await this.ctx.api.premium.purchaseItemOrCurrency(n);if(r.ok){let p=r.data;p.Premium&&this.ctx.data.user.applyPremium(p.Premium),this.ctx.data.user.applyResourceOperation(p.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",p);}return r}async purchaseRealMoney(e,t,i,s,n,r,p,d){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!s||!n)return b("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return c$1;let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:r,PackageName:p,AppStoreEnvironment:d,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(R);if(V.ok){let ae=V.data;ae.Premium&&this.ctx.data.user.applyPremium(ae.Premium),this.ctx.data.user.applyResourceOperation(ae.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",ae);}return V}};var Ks=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ItemInstanceID:z.string().nullish(),Level:z.number().nullish(),EquippedAt:c.nullish()}),Mo=z.object({CharacterID:z.string(),Level:z.number().nullish(),Experience:j.nullish(),Power:z.number().nullish(),StatLevels:z.record(z.string(),z.number()).nullish(),Equipment:z.record(z.string(),Ks).nullish(),UpdatedAt:c.nullish()}).passthrough(),Xu=z.object({Characters:z.record(z.string(),Mo).nullish()}),Oo=z.object({ServerTimeUtc:c,CharacterID:z.string(),StatID:z.string(),StatLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),Eo=z.object({ServerTimeUtc:c,CharacterID:z.string(),NewLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),ec=z.object({ServerTimeUtc:c,CharacterID:z.string(),Equipment:z.record(z.string(),Ks).nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),tc=z.object({ServerTimeUtc:c,CharacterID:z.string(),ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),tR=z.object({ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish()}),ic=z.object({ServerTimeUtc:c,Characters:z.record(z.string(),tR).nullish(),Inventory:K.nullish()}),Uo=z.object({ServerTimeUtc:c,CharacterID:z.string(),Power:z.number().nullish(),Resources:M.nullish()}),sc=z.object({ServerTimeUtc:c,CharacterID:z.string(),SkinID:z.string(),Resources:M.nullish(),Inventory:K.nullish(),Equipped:z.boolean().nullish(),EquipError:z.string().nullish(),Equipment:Ks.nullish(),Power:z.number().nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish()}),nc=z.object({ServerTimeUtc:c,CharacterID:z.string(),SkinID:z.string(),Equipped:Ks.nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),rc=z.object({ServerTimeUtc:c,CharacterID:z.string(),Cleared:z.boolean().nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),iR=z.object({SkinID:z.string(),IsDefault:z.boolean().nullish(),Misconfigured:z.string().nullish(),Owned:z.boolean().nullish(),OwnedCopies:z.number().nullish(),IsWorn:z.boolean().nullish(),MeetsRequirements:z.boolean().nullish(),SoldDirectly:z.boolean().nullish(),OnSale:z.boolean().nullish(),SaleEndsAtUtc:c.nullish(),GateOpen:z.boolean().nullish(),Purchasable:z.boolean().nullish(),PriceOptions:ue.nullish()}),sR=z.object({CharacterID:z.string(),CharacterOpen:z.boolean().nullish(),DefaultSkinID:z.string().nullish(),WornSkinID:z.string().nullish(),Skins:z.array(iR).nullish()}),oc=z.object({ServerTimeUtc:c,Characters:z.record(z.string(),sR).nullish()}),ac=gt(Uo),lc=gt(Eo),uc=gt(Oo),qo=z.object({RequiredStatID:z.string(),RequiredLevel:z.number()}).passthrough(),cc=z.object({StatID:z.string(),TypeID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),MaxLevel:z.number().nullish(),Weight:z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Ve.nullish(),BaseStatValue:z.number().nullish(),ValueCurve:Ve.nullish(),RankCurve:Ve.nullish(),Requirements:z.array(qo).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),nR=z.object({SlotID:z.string(),MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(qo).nullish(),AllowedRarityIDs:z.array(z.string()).nullish(),AllowedItemTags:z.array(z.string()).nullish(),MinItemLevel:z.number().nullish(),MaxItemLevel:z.number().nullish()}).passthrough(),pc=z.object({Slots:z.record(z.string(),nR).nullish()}).passthrough(),hc=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Lore:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),rR=z.object({ClassID:z.string().nullish(),RarityID:z.string().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),oR=z.object({UnlockedByDefault:z.boolean().nullish(),PriceOptions:ue.nullish()}).passthrough(),aR=z.object({Stats:Q.nullish(),Levels:Q.nullish(),Equipment:Q.nullish()}).passthrough(),dc=z.object({MaxRank:z.number().nullish(),FirstPaidRank:z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Ve.nullish()}).passthrough(),Bo="@skin";function lR(o){return !!o&&o.startsWith("@")}var uR=z.object({CatalogID:z.string().nullish(),ItemID:z.string()}).passthrough(),cR=z.object({PriceOptions:ue.nullish(),Schedule:fe.nullish(),Gate:Z.nullish()}).passthrough(),pR=z.object({MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(qo).nullish()}).passthrough(),hR=z.object({SkinID:z.string().nullish(),Identity:hc.nullish(),Item:uR.nullish(),Sale:cR.nullish(),Requirements:pR.nullish()}).passthrough(),dR=z.object({DefaultSkinID:z.string().nullish(),Definitions:z.record(z.string(),hR).nullish()}).passthrough(),mR=z.object({CharacterID:z.string(),Identity:hc.nullish(),Classification:rR.nullish(),Unlock:oR.nullish(),Presets:aR.nullish(),Equipment:pc.nullish(),Stats:z.record(z.string(),cc).nullish(),RankLadder:dc.nullish(),RankStatCurve:Ve.nullish(),StatMaxLevelCurve:Ve.nullish(),Skins:dR.nullish()}).passthrough(),fR=z.object({Stats:z.record(z.string(),cc).nullish()}).passthrough(),gR=z.object({RankLadder:dc.nullish()}).passthrough(),yR=z.object({Equipment:pc.nullish()}).passthrough(),RR=z.object({Stats:z.record(z.string(),fR).nullish(),Levels:z.record(z.string(),gR).nullish(),Equipment:z.record(z.string(),yR).nullish()}).passthrough(),Hs=z.object({Definitions:z.record(z.string(),mR).nullish(),Presets:RR.nullish()}).passthrough(),_e={GetCharacterDefinitions:"GetCharacterDefinitions",GetUserCharacters:"GetUserCharacters",UnlockCharacter:"UnlockCharacter",UpgradeStatLevel:"UpgradeStatLevel",UpgradeCharacterLevel:"UpgradeCharacterLevel",EquipItems:"EquipItems",UnequipItems:"UnequipItems",UnequipAllCharacters:"UnequipAllCharacters",UnlockCharactersBatch:"UnlockCharactersBatch",UpgradeCharacterLevelsBatch:"UpgradeCharacterLevelsBatch",UpgradeStatLevelsBatch:"UpgradeStatLevelsBatch",UnlockSkin:"UnlockSkin",EquipSkin:"EquipSkin",UnequipSkin:"UnequipSkin",GetCharacterSkins:"GetCharacterSkins"},CR="SKIN_ALREADY_OWNED";var Lo="Character",$s=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Lo)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,n])=>n?.Unlock?.UnlockedByDefault===true&&!i[n.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(Lo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Lo,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return c$1;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 b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${d()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok){let n=s.data;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.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",n);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return b("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${d()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,p=>{p.StatLevels??={},p.StatLevels[r.StatID]=r.StatLevel,r.Power!=null&&(p.Power=r.Power),p.UpdatedAt=r.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",r);}return n}async upgradeCharacterLevel(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${d()}`,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok){let n=s.data;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.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",n);}return s}async equipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(i);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(i);if(s.ok){let n=s.data;this.applyUnequipChangesLocally(e,n),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:n.ClearedSlotIDs??[],power:n.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return c$1;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 b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${d()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok){let r=n.data;this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),r.Equipped&&r.Equipment&&this.applySkinLocally(r.CharacterID,r.Equipment,r.Power,r.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",r);}return n}async equipSkin(e,t,i){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},n=await this.ctx.api.character.equipSkin(s);if(n.ok){let r=n.data;this.applyInventoryDelta(r.Inventory),this.applySkinLocally(r.CharacterID,r.Equipped??null,r.Power,r.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",r);}return n}async unequipSkin(e){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let s=i.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):c$1}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,Bo,t??null),n.patchCharacter(e,r=>{i!=null&&(r.Power=i),r.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return b("client","characterIDs is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level??=1,n.StatLevels??={},n.Equipment??={},s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level=s.NewLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(n.StatLevels??={},n.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.StatLevels??={},n.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[s,n]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,s,n);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let n of i)s.patchCharacterEquipment(e,n,null);s.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,s]of Object.entries(e.Characters??{})){for(let n of s.ClearedSlotIDs??[])t.patchCharacterEquipment(i,n,null);t.patchCharacter(i,n=>{s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=e.ServerTimeUtc;});}}};var mc="Match",Js=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,r){let p=this.ctx.auth.context;if(!p)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:r,RelatedEntityID:`pvp_create_${p.userID}_${d()}`},R=await this.ctx.api.match.createMatch(d$1);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",R.data)),R}async updateMatch(e,t={}){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(i);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,s){let n=this.ctx.auth.context;if(!n)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${d()}`},p=await this.ctx.api.match.instantBattle(r);if(p.ok){let d=p.data,R=this.ctx.data.config.itemDefinitions;if(d.Resources)this.ctx.data.user.applyResourceOperation(d.Resources,R);else if(d.ResourcesDual){let V=d.ResourcesDual;V.FromUserID===n.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,R):V.ToUserID===n.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",d);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let s=this.ctx.authedRequest();if(!s)return c$1;s.Page=e,s.PageSize=t,s.Statuses=i;let n=await this.ctx.api.match.getMyMatches(s);return n.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",n.data),n}async getAvailableMatches(e=0,t=20,i=false){let s=this.ctx.authedRequest();if(!s)return c$1;s.Page=e,s.PageSize=t,s.OnlyPublic=i;let n=await this.ctx.api.match.getAvailableMatches(s);return n.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",n.data),n}async getDefinitions(e){let t=this.ctx.cache.configSection(mc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(mc,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var fc="Craft",Zs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(fc,e);if(t){let n={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(fc,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n){if(!e)return b("client","CraftID is required.");let r=this.ctx.auth.context;if(!r)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,RelatedEntityID:`craft_${e}_${r.userID}_${d()}`},d$1=await this.ctx.api.craft.craft(p);return d$1.ok&&(this.ctx.data.user.applyResourcesWithDelta(d$1.data.Resources,d$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",d$1.data)),d$1}};var qt=z.lazy(()=>z.union([z.string(),z.number(),z.boolean(),z.null(),z.array(qt),z.record(z.string(),qt)]));var Bt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},gc=z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Kt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Ti(o){return o!==Kt.Pending&&o!==Kt.Running}var SR={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 xR(o){return o?/\b(AI_[A-Z_]+)\s*:/.exec(o)?.[1]??null:null}var bR=z.object({Url:z.string().nullish(),ContentType:z.string().nullish(),Variant:z.string().nullish()}),DR=z.object({Code:z.string().nullish(),Message:z.string().nullish()}),Ys=z.object({GenerationID:z.string(),FeatureKey:z.string().nullish(),Modality:gc.nullish(),Status:z.string(),Progress:z.number().nullish(),OutputText:z.string().nullish(),OutputJson:z.record(z.string(),qt).nullish(),Assets:z.array(bR).nullish(),Error:DR.nullish(),Charge:M.nullish(),PlayerRefunded:z.boolean().nullish(),Reused:z.boolean().nullish(),Reward:M.nullish(),Context:z.record(z.string(),qt).nullish(),PaymentSettled:z.boolean().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish()}),yc=z.object({Data:z.array(Ys).nullish(),Skip:z.number().nullish(),Limit:z.number().nullish()}),PR=z.object({Name:z.string().nullish(),Type:z.string().nullish(),Required:z.boolean().nullish(),MaxLength:z.number().nullish(),Enum:z.array(z.string()).nullish()}).passthrough(),IR=z.object({Modality:gc.nullish(),Async:z.boolean().nullish(),Limits:Re.nullish(),PriceOptions:ue.nullish(),Tags:z.array(z.string()).nullish(),HistoryMessages:z.number().nullish(),MaxTokens:z.number().nullish(),AllowImages:z.boolean().nullish(),MaxInputImages:z.number().nullish(),MaxInputImageBytes:z.number().nullish(),AllowedImageTypes:z.array(z.string()).nullish(),MaxImages:z.number().nullish(),AllowEdit:z.boolean().nullish(),AllowReferenceImage:z.boolean().nullish(),MaxPromptChars:z.number().nullish(),LockBehavior:z.boolean().nullish(),ImageSize:z.string().nullish(),VideoSize:z.string().nullish(),VideoSeconds:z.number().nullish(),Voice:z.string().nullish(),AudioFormat:z.string().nullish(),MusicFormat:z.string().nullish(),ThreeDOperation:z.string().nullish(),ThreeDAnimations:z.array(z.string()).nullish(),Reward:H.nullish(),PromptVariables:z.array(PR).nullish(),AllowFreePrompt:z.boolean().nullish()}).passthrough(),Rc=z.object({Enabled:z.boolean().nullish(),Features:z.record(z.string(),IR).nullish()}).passthrough(),Fe={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 Cc="AI",vR=/^[A-Za-z0-9_-]{1,128}$/,TR=2e3,AR=5e3,kR=30*6e4;function zR(o,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,o);e?.addEventListener("abort",i,{once:true});})}var Xs=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(Cc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Cc,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,i){return this.generate(e,{Text:t},i,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):c$1}async getGeneration(e){if(!e)return b("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):c$1}isTerminal(e){return Ti(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;i=p.data;}else {if(!e?.GenerationID)return b("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??kR),n=Math.max(1,t.intervalMs??TR),r=Math.max(n,t.maxIntervalMs??AR);for(;!Ti(i.Status);){if(t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");if(Date.now()+n>s)return b("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await zR(n,t.signal),t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(i);if(n=Math.min(r,Math.round(n*1.5)),!p.ok){if(p.reason==="connection")continue;return p}i=p.data,Ti(i.Status)||t.onUpdate?.(i);}return a(i)}pollFor(e){switch(e.Modality){case Bt.Text:return this.getText(e.GenerationID);case Bt.Image:return this.getImage(e.GenerationID);case Bt.Audio:return this.getAudio(e.GenerationID);case Bt.Music:return this.getMusic(e.GenerationID);case Bt.Video:return this.getVideo(e.GenerationID);case Bt.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,s){if(!e)return b("client","FeatureKey is required.");let n=i?.relatedEntityID;if(n!==void 0&&!vR.test(n))return b("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:n??d()},p=await s(r);return p.ok&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return b("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.GenerationID=e;let s=await t(i);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Kt.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===Kt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Kt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Go="Collection",en=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(Go),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let n=e.cache.configSection("Season");return Object.values(n?.Chains??{}).some(p=>(p?.Seasons??[]).some(d=>!!d?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Go,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Go,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,s){let n=this.ctx.auth.context;if(!n)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${d()}`},p=await this.ctx.api.collection.openPack(r);return p.ok&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${d()}`},r=await this.ctx.api.collection.openCollectionChest(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:chestOpened",r.data)),r}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${d()}`},n=await this.ctx.api.collection.useCollectibleJoker(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",n.data)),n}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${d()}`},n=await this.ctx.api.collection.claimSetReward(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",n.data)),n}async claimSetRewardsBatch(e){if(!e||e.length===0)return b("client","sets is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${d()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,n,r=false){let p=this.ctx.auth.context;if(!p)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:r,RelatedEntityID:`trade_send_${p.userID}_${s}_${d()}`},R=await this.ctx.api.collection.sendTradeOffer(d$1);return R.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",R.data)),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${d()}`},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 c$1;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${d()}`},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 c$1;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${d()}`},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 c$1;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 c$1;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 wR=z.object({}).passthrough().transform(o=>o),MR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},OR={Active:"Active",Left:"Left",Replaced:"Replaced"},ER=z.object({ObjectIndex:z.number().nullish(),ObjectCompletionRewardClaimed:z.boolean().nullish()}).passthrough(),UR=z.object({UserID:z.string().nullish(),PublicData:Ee.nullish(),BuildObjectsProgress:ER.nullish(),IsBot:z.boolean().nullish(),SpinsCount:z.number().nullish(),TokensSpent:z.number().nullish(),MemberStatus:z.string().nullish(),GrandPrizeClaimed:z.boolean().nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),qR=z.object({Index:z.number().nullish(),OwnerUserID:z.string().nullish(),CurrentProgress:z.number().nullish(),MaxProgress:z.number().nullish(),IsCompleted:z.boolean().nullish()}).passthrough(),BR=z.object({Objects:z.array(qR).nullish()}).passthrough(),Sc=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),CoopChainID:z.string().nullish(),CoopEventID:z.string().nullish(),CycleIndex:z.number().nullish(),Members:z.array(UR).nullish(),BuildObjectsState:BR.nullish(),Status:z.string().nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:z.number().nullish()}).passthrough(),xc=z.object({CoopChainID:z.string(),CycleIndex:z.number().nullish(),EventOrder:z.number().nullish(),EventDef:z.lazy(()=>bc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:z.number().nullish()}).passthrough(),LR=z.string(),Fo=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Weight:z.number().nullish(),MinProgress:z.number().nullish(),MaxProgress:z.number().nullish()}).passthrough(),GR=z.object({Index:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxProgress:z.number().nullish(),CompletionReward:H.nullish()}).passthrough(),FR=z.object({Objects:z.array(GR).nullish(),PriceOptions:ue.nullish(),SpinnerTable:z.array(Fo).nullish(),MaxSpinsPerCall:z.number().nullish()}).passthrough(),bc=z.object({CoopEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),EventType:LR.nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),BuildObjects:FR.nullish(),GrandPrize:H.nullish()}).passthrough(),VR=z.object({CoopChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:fe.nullish(),Events:z.array(bc).nullish(),Gate:Z.nullish()}).passthrough(),tn=z.object({ServerTimeUtc:c.nullish(),UserState:wR.nullish(),ActiveGroup:Sc.nullish()}),Vo=z.object({ServerTimeUtc:c.nullish(),Group:Sc.nullish(),SecondsRemaining:j.nullish()}),Dc=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Resources:M.nullish(),ObjectIndex:z.number().nullish(),Sector:Fo.nullish(),RequestedSpins:z.number().nullish(),SpinsUsed:z.number().nullish(),Sectors:z.array(Fo).nullish(),ProgressDelta:z.number().nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),ObjectCompleted:z.boolean().nullish(),AllObjectsCompleted:z.boolean().nullish()}),No=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Pc=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),sn=z.object({Chains:z.record(z.string(),VR).nullish()}).passthrough(),dt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Ic="CoopEvent",vc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},nn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(vc,{schema:tn,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ic,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ic,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return b("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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(vc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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 b("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","CoopChainID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let s=i.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,s){if(!e||!t)return b("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,RelatedEntityID:d()},r=await this.ctx.api.coopEvent.spin(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",r.data)),r}async claimObjectReward(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c$1;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 b("client","GroupID is required.");if(!this.ctx.auth.context)return c$1;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 c$1;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 NR={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},_R={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},jR=z.object({NodeID:z.string().nullish(),Status:z.string().nullish(),ExecutionCount:z.number().nullish(),UnlockedAtUtc:c.nullish(),CompletedAtUtc:c.nullish(),LastExecutedAtUtc:c.nullish(),NextAvailableAtUtc:c.nullish(),LastExecutionRefID:z.string().nullish()}).passthrough(),WR=z.object({TrackID:z.string().nullish(),CurrentValue:z.number().nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),Tc=z.object({OfferID:z.string().nullish(),InstanceKey:z.string().nullish(),SourceOfferVersion:z.number().nullish(),Status:z.string().nullish(),ActivatedAtUtc:c.nullish(),ExhaustedAtUtc:c.nullish(),ExpiredAtUtc:c.nullish(),DismissedAtUtc:c.nullish(),ShowCount:z.number().nullish(),LastShownAtUtc:c.nullish(),Nodes:z.record(z.string(),jR).nullish(),Tracks:z.record(z.string(),WR).nullish(),SelectedChoiceNodeID:z.string().nullish()}).passthrough(),QR=z.object({SlotID:z.string().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),ActiveOfferID:z.string().nullish(),ActiveOfferStartedAtUtc:c.nullish(),ActiveOfferExpiresAtUtc:c.nullish(),ActiveOffer:Tc.nullish(),NextCycleStartsAtUtc:c.nullish(),LastUpdatedUtc:c.nullish(),DismissSkipAvailableAtUtc:c.nullish(),LastDismissedAtUtc:c.nullish(),ActiveScheduleInstanceKey:z.string().nullish()}).passthrough(),KR=z.object({TotalExecutions:z.number().nullish(),DailyExecutions:z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),HR=z.object({TotalActivations:z.number().nullish(),TotalExhausted:z.number().nullish(),TotalExpired:z.number().nullish(),TotalDismissed:z.number().nullish(),TotalShows:z.number().nullish(),LastShownAtUtc:c.nullish(),LastActivatedAtUtc:c.nullish(),LastExhaustedAtUtc:c.nullish(),NodeCounts:z.record(z.string(),KR).nullish()}).passthrough(),$R=z.object({Slots:z.record(z.string(),QR).nullish(),OfferHistory:z.record(z.string(),HR).nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),JR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},ZR={Eq:"Eq",Gte:"Gte",Lte:"Lte"},YR=z.object({Order:z.number().nullish(),OfferID:z.string().nullish(),DurationSec:z.number().nullish(),DelayBeforeActivationSec:z.number().nullish()}).passthrough(),rn=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Ac=z.object({Schedule:fe.nullish(),Gate:Z.nullish()}).passthrough(),kc=z.object({AllowDismissSkip:z.boolean().nullish(),DismissSkipDelaySec:z.number().nullish()}).passthrough(),XR=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Behaviour:Q.nullish()}).passthrough(),eC=z.object({SlotID:z.string().nullish(),Enabled:z.boolean().nullish(),Identity:rn.nullish(),Availability:Ac.nullish(),Behaviour:kc.nullish(),Queue:z.array(YR).nullish(),Presets:XR.nullish()}).passthrough(),tC=z.object({ViewsRequiredToComplete:z.number().nullish(),MaxViewsPerActivation:z.number().nullish(),GrantRewardsPerView:z.boolean().nullish()}).passthrough(),iC=z.object({RewardedVideo:tC.nullish()}).passthrough(),sC=z.object({TrackID:z.string().nullish(),Operator:z.string().nullish(),Value:z.number().nullish()}).passthrough(),nC=z.object({Identity:Q.nullish(),Graph:Q.nullish(),Milestones:Q.nullish()}).passthrough(),rC=z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish()}).passthrough(),oC=z.object({TrackID:z.string().nullish(),Amount:z.number().nullish(),RespectBounds:z.boolean().nullish()}).passthrough(),aC=z.object({TrackID:z.string().nullish(),DisplayName:z.string().nullish(),StartValue:z.number().nullish(),MinValue:z.number().nullish(),MaxValue:z.number().nullish(),ClampToMin:z.boolean().nullish(),ClampToMax:z.boolean().nullish(),HiddenFromUI:z.boolean().nullish()}).passthrough(),lC=z.object({RequiredCompletedNodeIDs:z.array(z.string()).nullish(),RequiredAnyCompletedNodeIDs:z.array(z.string()).nullish(),RequiredTracks:z.array(sC).nullish(),VisibleWhileLocked:z.boolean().nullish()}).passthrough(),zc=z.object({Options:ue.nullish()}).passthrough(),wc=z.object({Grants:H.nullish(),TrackChanges:z.array(oC).nullish(),MilestonePoints:z.number().nullish()}).passthrough(),uC=z.object({NodeID:z.string().nullish(),Type:z.string().nullish(),Identity:rn.nullish(),Pricing:zc.nullish(),Reward:wc.nullish(),Action:iC.nullish(),UnlockRules:lC.nullish(),NextNodeIDs:z.array(z.string()).nullish(),ChoiceGroupID:z.string().nullish(),Limits:Re.nullish(),HideWhenCompleted:z.boolean().nullish(),ExhaustOfferOnComplete:z.boolean().nullish(),Presets:rC.nullish()}).passthrough(),Mc=z.object({RootNodeIDs:z.array(z.string()).nullish(),Nodes:z.array(uC).nullish(),Tracks:z.array(aC).nullish(),ExhaustedWhenAllTerminalNodesCompleted:z.boolean().nullish()}).passthrough(),Oc=z.object({Milestones:z.record(z.string(),Le).nullish(),ClaimMode:z.string().nullish(),Token:Wt.nullish()}).passthrough(),Ec=z.object({OfferID:z.string().nullish(),Version:z.number().nullish(),Enabled:z.boolean().nullish(),Identity:rn.nullish(),Graph:Mc.nullish(),Milestones:Oc.nullish(),Presets:nC.nullish()}).passthrough(),cC=z.object({Identity:z.record(z.string(),rn).nullish(),Availability:z.record(z.string(),Ac).nullish(),Behaviour:z.record(z.string(),kc).nullish(),Graph:z.record(z.string(),Mc).nullish(),Milestones:z.record(z.string(),Oc).nullish(),Pricing:z.record(z.string(),zc).nullish(),Reward:z.record(z.string(),wc).nullish()}).passthrough(),_o=z.object({Slots:z.record(z.string(),eC).nullish(),Offers:z.record(z.string(),Ec).nullish(),Presets:cC.nullish()}).passthrough(),Uc=z.object({DealOfferDefinitions:_o.nullish()}),qc=z.object({DealOffers:$R.nullish()}),pC=z.object({EntityID:z.string().nullish(),TotalEarned:z.number().nullish(),ClaimedIDs:z.array(z.string()).nullish(),ReachedUnclaimedIDs:z.array(z.string()).nullish()}).passthrough(),hC=z.object({SlotID:z.string().nullish(),SortOrder:z.number().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),OfferDef:Ec.nullish(),ActivationState:Tc.nullish(),IsNewActivation:z.boolean().nullish(),ComputedExpiresAtUtc:c.nullish(),Cost:bt.nullish(),Milestone:pC.nullish(),ScheduleInstanceKey:z.string().nullish()}).passthrough(),on=z.object({Slots:z.array(hC).nullish()}),Bc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),NodeID:z.string().nullish(),NodeCompleted:z.boolean().nullish(),OfferExhausted:z.boolean().nullish(),Idempotent:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Lc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),Gc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),Fc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Vc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),ClaimedIDs:z.array(z.string()).nullish(),Rejected:z.record(z.string(),z.string()).nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Rt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var dC="DealOffer",Nc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},an=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Nc,{schema:on,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(dC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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(Nc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return c$1;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 b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${d()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,s){if(!e||!t)return b("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return c$1;let n=i&&i.trim().length>0?i.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:n??`deal_exec_${e}_${t}_${d()}`},p=await this.ctx.api.dealOffer.executeNode(r);return p.ok&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${d()}`},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 b("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${d()}`},s=await this.ctx.api.dealOffer.claimMilestone(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;let i=[...new Set(t.map(r=>r.trim()).filter(r=>r.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${d()}`},n=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",n.data)),n}};var _c="Referral",ln=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(_c,e);if(t){let n={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",n),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(_c,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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=jt.parseReferralCode(e)?.toUpperCase();if(!t)return b("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},n=await this.ctx.api.referral.activateReferralCode(s);if(n.ok){let r=n.data;r.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(r.ReferrerUserID,r.QualificationPending),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",r);}return n}async claimInviteReward(e){let t=e.trim();if(!t)return b("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},n=await this.ctx.api.referral.claimInviteReward(s);if(n.ok){let r=n.data;r.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(r.RewardID),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",r);}return n}async claimInviteRewardsBatch(e){let t=(e??[]).map(r=>r?.trim()).filter(Boolean);if(t.length===0)return b("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},n=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(n.ok){let r=n.data;for(let p of r.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",r);}return n}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return c$1;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 mC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},jc=z.enum(["System","Reward","Gift","Social"]).catch("System"),fC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},gC=z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),yC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},RC=z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),tt={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},CC={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"},SC=100,xC=z.object({Subject:z.string().nullish(),Body:z.string().nullish()}).passthrough(),Wc=z.object({FeatureID:z.string().nullish(),Args:z.record(z.string(),z.string()).nullish(),Url:z.string().nullish(),Label:z.string().nullish()}).passthrough(),bC=z.object({Texts:z.record(z.string(),xC).nullish(),Category:jc.nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Wc.nullish(),SenderName:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),DC=z.object({Enabled:z.boolean().nullish(),Grant:ce.nullish(),Cost:ce.nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:c.nullish(),SenderGate:Z.nullish(),TemplateID:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),PC=z.object({Type:z.string().nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxAmountPerGift:z.number().nullish()}).passthrough(),IC=z.object({Enabled:z.boolean().nullish(),AllowedResources:z.array(PC).nullish(),MaxEntriesPerGift:z.number().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:c.nullish(),FeePercent:z.number().nullish(),FeeCost:ce.nullish(),SenderGate:Z.nullish(),ExpirationDays:z.number().nullish(),TemplateID:z.string().nullish()}).passthrough(),Qc=z.object({Enabled:z.boolean().nullish(),Capacity:z.number().nullish(),RewardLetterDays:z.number().nullish(),PlainLetterDays:z.number().nullish(),ClaimedRetentionDays:z.number().nullish(),DefaultLanguage:z.string().nullish(),Templates:z.record(z.string(),bC).nullish(),Gifts:z.object({Social:z.record(z.string(),DC).nullish(),Transfer:IC.nullish()}).passthrough().nullish(),Integrations:z.object({Leaderboard:z.boolean().nullish(),CoopEvent:z.boolean().nullish(),Season:z.boolean().nullish(),Referral:z.boolean().nullish()}).passthrough().nullish()}).passthrough(),vC=z.object({MessageID:z.string(),Source:gC,Category:jc,TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Wc.nullish(),SenderName:z.string().nullish(),SenderUserID:z.string().nullish(),SenderAvatarUrl:z.string().nullish(),SenderNote:z.string().nullish(),Rewards:H.nullish(),HasRewards:z.boolean().nullish(),IsTransfer:z.boolean().nullish(),SentAt:c,ExpiresAt:c.nullish(),ReadAt:c.nullish(),ClaimedAt:c.nullish()}).passthrough(),TC=z.object({MessageID:z.string(),Module:RC,Key:z.string(),TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish()}).passthrough(),jo=z.object({ID:z.string(),Error:z.string().nullish()}).passthrough(),Kc=z.object({ServerTimeUtc:c.nullish(),Messages:z.array(vC).default([]),NextCursor:z.string().nullish(),PendingRewards:z.array(TC).nullish(),UnreadCount:z.number().nullish(),UnclaimedCount:z.number().nullish(),DeliveredNow:z.number().nullish()}).passthrough(),un=z.object({ServerTimeUtc:c.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Wo=z.object({ServerTimeUtc:c.nullish(),AffectedCount:z.number().default(0),Failed:z.array(jo).default([]),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),AC=z.object({MessageID:z.string(),Rewards:ce.nullish()}).passthrough(),cn=z.object({ServerTimeUtc:c.nullish(),Claimed:z.array(AC).default([]),Failed:z.array(jo).default([]),Resources:M.nullish(),Inventory:K.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Hc=z.object({ServerTimeUtc:c.nullish(),GiftID:z.string().nullish(),Sent:z.array(z.string()).default([]),Failed:z.array(jo).default([]),Resources:M.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish()}).passthrough(),$c=z.object({ServerTimeUtc:c.nullish(),MessageID:z.string().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),RecipientReceives:ce.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish(),IdempotentReplay:z.boolean().nullish()}).passthrough(),Jc=z.object({ServerTimeUtc:c.nullish(),ResetsAt:c.nullish(),Social:z.record(z.string(),z.object({IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ReceivedInPeriod:z.number().default(0),SentTo:z.array(z.string()).default([]),ResetsAt:c.nullish()}).passthrough()).default({}),Transfer:z.object({Enabled:z.boolean().default(false),IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish()}).passthrough().nullish()}).passthrough();var Qo="Mailbox",Ko={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},pn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ko,{schema:un,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(Ko,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Qo)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Qo,e);if(t)return a(t);let i=this.request();if(!i)return c$1;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(Qo,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return c$1;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(Ko,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return c$1;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 c$1;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 b("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):c$1}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return b("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):c$1}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):c$1}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 c$1;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return b("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return b("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return c$1;let n=await this.ctx.api.mailbox.sendGift(s);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",n.data)),n}async sendTransfer(e,t,i){if(!e?.trim())return b("client","RecipientUserID is required.");if(!i?.requestID?.trim())return b("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return c$1;let n=await this.ctx.api.mailbox.sendTransfer(s);return n.ok&&(n.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(n.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",n.data)),n}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):c$1}};var hn={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},Ho="idos-app",Zc=z.object({ServerTimeUtc:z.string().nullish(),Allowed:z.boolean(),DenyReason:z.string().nullish(),Message:z.string().nullish(),RetryAfterSeconds:z.number().nullish(),RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),AdUnitID:z.string().nullish(),Type:z.string().nullish(),ExpiresAtUtc:z.string().nullish(),CreditsToAward:z.number().nullish(),RequiresServerSideVerification:z.boolean().nullish()}),Yc=z.object({ServerTimeUtc:z.string().nullish(),RequestID:z.string().nullish(),Status:z.string(),CreditsAwarded:z.number().nullish(),RetryAfterSeconds:z.number().nullish(),ExpiresAtUtc:z.string().nullish(),AlreadyProcessed:z.boolean().nullish(),GrantedWithoutSsv:z.boolean().nullish(),Resources:M.nullish()});var $o={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},kC=5*6e4;function dn(){return s()}async function Jo(o){let e=await j$1($o.request,$o.response,{titleID:o.titleID,userID:o.userID,requestID:o.requestID,placementID:o.placementID,adUnitID:o.adUnitID??null},{answerTimeoutMs:kC});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var zC=new Set(["CANCELLED","DECLINED","CLOSED"]),wC=45e3,MC=o=>new Promise(e=>setTimeout(e,o)),mn=class{constructor(e){this.ctx=e;}ctx;get available(){return dn()}async showRewarded(e){if(!dn())return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let i=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!i.ok)return {status:"unavailable",reason:i.error};let s=i.data;if(!s.Allowed)return {status:"denied",reason:s.DenyReason??void 0,retryAfterSeconds:s.RetryAfterSeconds??void 0};if(s.ProviderID!==Ho||!s.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let n=await Jo({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:s.RequestID,placementID:e,adUnitID:s.AdUnitID});return n.ok?this.awaitReward(s.RequestID,n.via):{status:zC.has(n.error??"")?"cancelled":"unavailable",reason:n.error}}async awaitReward(e,t){let i=Date.now()+wC;for(;;){let s=this.ctx.authedRequest();if(!s)return {status:"pending",via:t};let n=await this.ctx.api.advertising.completeView({...s,RequestID:e});if(n.ok&&n.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:n.data.CreditsAwarded??0,via:t};let r=Math.min(Math.max((n.ok?n.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+r>i)return {status:"pending",via:t,reason:n.ok?void 0:n.error};await MC(r);}}};var OC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},EC={Title:"Title",Platform:"Platform"},Xc=z.object({UserID:z.string(),PublicData:Ee.nullish(),Source:z.enum(["Title","Platform"]).nullish()}),Ai=z.object({Friends:z.array(Xc).nullish()}),UC=z.object({FriendsCount:z.number().nullish(),IncomingRequestsCount:z.number().nullish(),OutgoingRequestsCount:z.number().nullish()}),ki=z.object({TargetUserID:z.string().nullish(),Status:z.string().nullish(),Target:Xc.nullish(),Counters:UC.nullish()}),qC={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},BC={Like:"Like",Favorite:"Favorite"},LC={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},GC={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},FC={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},VC=z.object({Key:z.string().nullish(),DisplayName:z.string().nullish(),AvatarUrl:z.string().nullish()}).passthrough(),NC=z.object({Id:z.string(),Verb:z.string().nullish(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),Count:z.number().nullish(),LastActors:z.array(VC).nullish(),Payload:z.object({Title:z.string().nullish(),Excerpt:z.string().nullish(),ImageUrl:z.string().nullish()}).passthrough().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),OccurredAt:c.nullish(),OwnerImpact:M.nullish(),IsBlocked:z.boolean().nullish(),TargetObjectName:z.string().nullish()}).passthrough(),ep=z.object({Items:z.array(NC).nullish(),HasMore:z.boolean().nullish(),NextBeforeUpdatedAt:z.string().nullish(),NextBeforeID:z.string().nullish(),UnreadCount:z.number().nullish(),SeenAt:c.nullish()}).passthrough(),zi=z.object({UnreadCount:z.number().nullish(),SeenAt:c.nullish()}).passthrough(),_C=z.object({Likes:z.number().nullish(),Favorites:z.number().nullish(),Followers:z.number().nullish(),Following:z.number().nullish(),Comments:z.number().nullish(),Replies:z.number().nullish(),Posts:z.number().nullish(),Dislikes:z.number().nullish()}).passthrough(),Lt=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Counts:_C.nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish(),Following:z.boolean().nullish(),Blocked:z.boolean().nullish()}).passthrough(),tp=z.object({Items:z.array(Lt).nullish()}).passthrough(),Zo={HasMore:z.boolean().nullish(),NextCursorAt:z.string().nullish(),NextCursorID:z.string().nullish()},jC=z.object({UserID:z.string(),PublicData:Ee.nullish(),Mutual:z.boolean().nullish(),Since:c.nullish()}).passthrough(),fn=z.object({Items:z.array(jC).nullish(),...Zo}).passthrough(),WC=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Kind:z.string().nullish(),At:c.nullish()}).passthrough(),ip=z.object({Items:z.array(WC).nullish(),...Zo}).passthrough(),gn=z.object({CommentID:z.string(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),ParentCommentID:z.string().nullish(),AuthorUserID:z.string().nullish(),AuthorPublicData:Ee.nullish(),Text:z.string().nullish(),Status:z.string().nullish(),Pinned:z.boolean().nullish(),CreatedAt:c.nullish(),EditedAt:c.nullish(),Likes:z.number().nullish(),Replies:z.number().nullish(),Liked:z.boolean().nullish(),IsMine:z.boolean().nullish()}).passthrough(),sp=z.object({Items:z.array(gn).nullish(),...Zo,TotalCount:z.number().nullish()}).passthrough(),np=z.object({CommentID:z.string().nullish(),Deleted:z.boolean().nullish()}).passthrough(),rp=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish(),AutoHidden:z.boolean().nullish()}).passthrough(),op=z.object({CommentsEnabled:z.boolean().nullish(),CommentableTypes:z.array(z.string()).nullish(),CommentMaxLength:z.number().nullish(),CommentMaxLinks:z.number().nullish()}).passthrough(),QC="FRIENDS_FROM_PLATFORM",KC={Off:"Off",Default:"Default",Always:"Always"},HC={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},ap=z.object({Profile:z.enum(["Off","Default","Always"]).nullish(),Friends:z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:z.boolean().nullish()}).passthrough(),Ce={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 Yo={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},yn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Yo,{schema:zi,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return c$1;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 c$1;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 c$1;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 c$1;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 b("client","TargetUserID is required.");if(!this.ctx.auth.context)return c$1;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 b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c$1;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 b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c$1;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 b("client","FriendUserID is required.");if(!this.ctx.auth.context)return c$1;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 c$1;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(Yo,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return c$1;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 c$1;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(Yo,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)):c$1}async getEntityStates(e,t){if(!t?.length)return b("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):c$1}async addComment(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i?.trim())return b("client","Text is required.");n.Text=i,n.ParentCommentID=s;let r=await this.ctx.api.social.addComment(n);return r.ok&&this.ctx.emitter.emit("social:commentAdded",r.data),r}async editComment(e,t){if(!e)return b("client","CommentID is required.");if(!t?.trim())return b("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.CommentID=e,i.Text=t;let s=await this.ctx.api.social.editComment(i);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return b("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=i.parentCommentID,this.applyPage(s,i.cursor,i.limit),this.ctx.api.social.getComments(s))}async report(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i)return b("client","ReportReason is required.");n.ReportReason=i,n.ReportComment=s;let r=await this.ctx.api.social.report(n);return r.ok&&this.ctx.emitter.emit("social:reported",r.data),r}async mutate(e,t,i,s){let n=this.targetRequest(t,i);if("ok"in n)return n;n.ReactionKind=s;let r=await this.ctx.api.social[e](n);return r.ok&&this.ctx.emitter.emit("social:entityStateChanged",r.data),r}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):c$1}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 b("client","EntityType is required.");if(!t)return b("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):c$1}};var lp="TimedBoost";function $C(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Rn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(lp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(lp,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return c$1;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 c$1;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(!$C(i))return b("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${d()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok){let r=n.data;if(r.ActivatedBoost){let p=r.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(r.ActivatedBoost,p);}this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",r);}return n}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return c$1;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 At={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},JC={Client:"Client",Server:"Server",System:"System"},ZC=z.enum(["Client","Server","System"]).catch("Client"),YC=z.object({Value:z.string().nullish(),UpdatedAt:c.nullish(),Version:z.number().nullish(),LastWriter:ZC.nullish(),ExpiresAt:c.nullish()}).passthrough(),Cn=z.record(z.string(),YC),up=z.object({Version:z.number().nullish(),Private:Cn.nullish(),Public:Cn.nullish(),ReadOnly:Cn.nullish()}),Xo=z.object({UserID:z.string().nullish(),Version:z.number().nullish(),Public:Cn.nullish()}),ea=z.object({ServerTimeUtc:c.nullish(),Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:c.nullish()}),XC=z.object({Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:c.nullish()}),cp=z.object({ServerTimeUtc:c.nullish(),Results:z.array(XC).nullish()}),pp=z.object({ServerTimeUtc:c.nullish(),DeletedCount:z.number().nullish()}),hp=z.object({Results:z.array(Xo).nullish(),NotFoundUserIDs:z.array(z.string()).nullish()}),eS={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},tS=z.enum(["String","Int","Bool","Json"]).catch("String"),iS=z.object({KeyID:z.string(),Bucket:z.string().nullish(),ValueType:tS.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),Sn=z.object({Keys:z.record(z.string(),iS).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),mt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var sS="UserCustomData";function dp(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var xn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(sS,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return c$1;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 b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,At.Private)}async setPublicData(e,t){return this.setData(e,t,At.Public)}async setData(e,t,i){let s=e.trim();if(!dp(s))return b("client",'KeyID is required and must not contain "." or "$".');if(t==null)return b("client","Value is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(i===At.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(p.ok){let d=p.data;this.ctx.data.user.patchUserCustomDataKey(i,d.KeyID,t,d.Version??0,d.ExpiresAt),this.ctx.emitter.emit(i===At.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",d);}return p}async deleteKey(e,t){let i=e.trim();if(!dp(i))return b("client",'KeyID is required and must not contain "." or "$".');if(t!==At.Private&&t!==At.Public)return b("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},n=await this.ctx.api.userCustomData.deleteKey(s);return n.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),n}async batchSet(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let n=s.Bucket??At.Private,r=e.find(p=>p.Bucket===n&&p.KeyID===s.KeyID);r&&this.ctx.data.user.patchUserCustomDataKey(n,s.KeyID,r.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return b("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 nS="TitleCustomDataDefinitions",mp=50;function rS(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}function ta(o){if(o.ExpiresAt==null)return false;let e=Date.parse(o.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function oS(o){let e={};for(let[t,i]of Object.entries(o))ta(i)||(e[t]=i);return e}var bn=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(nS,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return c$1;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(n=>n.trim()).filter(n=>n.length>0);if(!t.length)return b("client","At least one KeyID is required.");if(t.some(n=>!rS(n)))return b("client",'KeyID must not contain "." or "$".');if(t.length>mp)return b("client",`At most ${mp} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return c$1;i.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!ta(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!ta(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=oS(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 Dn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return c$1;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 c$1;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 c$1;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 c$1;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var aS=15,lS="GameLoop",fp="BoardDefinition",Pn=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 c$1;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(fp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),a(i);let s=this.ctx.authedRequest();if(!s)return c$1;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(fp,n.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n.data)),n}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return b("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return c$1;i.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return c$1;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 b("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let n=s.data,r=Ql(new Date,aS);this.ctx.data.user.patchBoardState(p=>{p.Position=n.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(n.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),n.ActionRequired&&n.ActionData?p.Pending={Type:n.ActionRequired,TargetUserID:n.ActionData.TargetUserID,TargetPublicData:n.ActionData.PublicData,TargetBuildingStates:n.ActionData.TargetBuildingStates??void 0,TargetHasShield:n.ActionData.TargetHasShield??void 0,RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:r}:n.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:r,Special:{ModeID:n.SpecialModeOffer.ModeID??void 0,Choices:n.SpecialModeOffer.Choices??void 0}});}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),n.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",n);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.IsBotTarget&&n.Operation?this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs):!n.IsBotTarget&&n.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(n.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",n);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return b("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${d()}`},n=await this.ctx.api.gameLoop.boardLoopRaid(s);if(n.ok){let r=n.data;r.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(r.RaidLayout,r.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(r)),this.ctx.emitter.emit("gameLoop:boardRaided",r);}else await this.getUserBoardState();return n}async boardLoopRaidFast(e){if(!e.length)return b("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(s.ok){let n=s.data;n.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(n)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",n);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return b("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let n=s.data;n.StageComplete?this.ctx.data.user.patchBoardState(r=>{r.StageLevel=(r.StageLevel??1)+1,r.Position=0,r.Pending=null,r.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(n.BuiltIndex,r=>{n.NewLevel!=null&&(r.Level=n.NewLevel),r.IsDamaged=false,n.MaxLevelRewardClaimed&&(r.MaxLevelRewardClaimed=true);}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",n);}return s}async boardSpecialChoose(e,t){if(!e)return b("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${d()}`},n=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(n.ok){let r=n.data;r.Mode==="Instant"||r.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(d=>{d.ChoiceID=e,d.ChosenMode=r.Mode??"Timed",d.StartedAtUtc=r.StartedAtUtc??null,d.DurationSeconds=r.DurationSeconds??null,d.AdViewsUsed=0;}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",r);}return n}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let n=s.data;this.ctx.data.user.patchBoardSpecialPending(r=>{r.AdViewsUsed=n.AdViewsUsed??0,r.AccumulatedMultiplier=n.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",n);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${d()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",n);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return c$1;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 c$1;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 b("client","milestoneID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return c$1;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 c$1;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 In=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let n=e.trim();if(!n)return b("client","FunctionName is required.");if(!this.ctx.auth.context)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(r);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var gp=z.object({ServerTimeUtc:c,SourceType:si,SourceID:z.string(),TargetType:si,TargetID:z.string(),SourceSpent:j,FeeAmount:j,RateApplied:Y,TargetCredited:j}),yp=z.object({ServerTimeUtc:c,SourceType:si,SourceID:z.string(),TargetType:si,TargetID:z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),vn={Convert:"Convert",CryptoConvert:"CryptoConvert"},uS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},Rp=z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),cS={Automatic:"Automatic",Manual:"Manual"},pS=z.enum(["Automatic","Manual"]).catch("Automatic"),hS=z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),InitialDeposit:z.number().nullish(),MinBalance:z.number().nullish(),MaxBalance:z.number().nullish(),DailyEarnLimit:z.number().nullish(),DailySpendLimit:z.number().nullish()}).passthrough(),dS=z.object({Rate:z.number().nullish(),Max:z.number().nullish(),Period:z.number().nullish()}).passthrough(),mS=z.object({IsTradable:z.boolean().nullish(),IsPurchasable:z.boolean().nullish(),IsRefundable:z.boolean().nullish()}).passthrough(),fS=z.object({TargetCurrencyType:si.nullish(),TargetCurrencyID:z.string(),Rate:Y.nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish(),DailyLimit:z.number().nullish()}).passthrough(),Cp=z.object({Enabled:z.boolean().nullish(),RateMode:pS.nullish(),Fee:z.number().nullish(),Targets:z.array(fS).nullish()}).passthrough(),Sp=z.object({CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough(),gS=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Economy:hS.nullish(),Recharge:dS.nullish(),Conversion:Cp.nullish(),Permissions:mS.nullish(),Audit:Sp.nullish(),Status:Rp.nullish()}).passthrough(),yS=z.object({NetworkID:z.string(),ContractAddress:z.string().nullish(),Decimals:z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),RS=z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),CS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),SpendableInGame:z.boolean().nullish(),ConvertibleToVirtual:z.boolean().nullish()}).passthrough(),SS=z.object({Mode:z.string().nullish(),FundingNetworkID:z.string().nullish(),PerPlayerDailyTokens:z.number().nullish(),TitleDailyTokens:z.number().nullish(),RefuseOverCap:z.boolean().nullish()}).passthrough(),ia=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),DisplayDecimals:z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),UsdPriceRefreshMinutes:z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:z.array(yS).nullish(),Limits:RS.nullish(),Permissions:CS.nullish(),Conversion:Cp.nullish(),Audit:Sp.nullish(),Status:Rp.nullish(),ServerGrantPolicy:SS.nullish(),UnbackedRewardCurrencyID:z.string().nullish()}).passthrough(),Tn=z.object({VirtualCurrencies:z.record(z.string(),gS).nullish(),CryptoCurrencies:z.record(z.string(),ia).nullish()}).passthrough();var xS={EVM:"EVM",Solana:"Solana"},bS=z.enum(["EVM","Solana"]).catch("EVM"),DS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},PS=z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),IS={Token:"Token",Nft:"Nft"},xp=z.enum(["Token","Nft"]).catch("Token"),vS={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},TS=z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),AS={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},kS=z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),zS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},sa=z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),bp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function An(o){let e=o?.trim();return e||bp.GameTopUp}var wS={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},Dp=z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),MS=z.object({ContractAddress:z.string().nullish(),ItemCatalogID:z.string().nullish(),DisplayName:z.string().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),Pp=z.object({Ios:z.boolean().nullish(),Android:z.boolean().nullish(),Web:z.boolean().nullish()}).passthrough(),OS=z.object({NetworkID:z.string().nullish(),DisplayName:z.string().nullish(),Type:bS.nullish(),ChainID:z.number().nullish(),ChainTicker:z.string().nullish(),RewardPoolAddress:z.string().nullish(),VaultDepositAddress:z.string().nullish(),ChainConfigVersion:z.number().nullish(),RequiredConfirmations:z.number().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:Pp.nullish(),NftCollections:z.array(MS).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RpcUrl:z.string().nullish(),GasPrice:z.number().nullish(),NftBridgeAddress:z.string().nullish(),SignatureEpoch:z.number().nullish()}).passthrough(),ES=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:Pp.nullish()}).passthrough(),US=z.object({MinAccountAgeDays:z.number().nullish(),MultiAccountCheckEnabled:z.boolean().nullish(),BanOnSharedWithdrawalAddress:z.boolean().nullish(),PendingWithdrawalTtlHours:z.number().nullish()}).passthrough(),qS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},BS=z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Ip=z.object({Enabled:z.boolean().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:BS.nullish(),DenyMessage:z.string().nullish()}).passthrough(),LS=z.object({Enabled:z.boolean().nullish(),WalletConnectProjectId:z.string().nullish(),ShowOnLoginScreen:z.boolean().nullish()}).passthrough(),GS={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},wi=z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),FS=z.object({Mode:wi.nullish(),TokenGates:z.array(Ip).nullish()}).passthrough(),na=z.object({SystemState:ES.nullish(),Networks:z.record(z.string(),OS).nullish(),AccountSafety:US.nullish(),WalletLogin:LS.nullish(),PlayAccess:FS.nullish(),IframeConnectHosts:z.array(z.string()).nullish()}).passthrough(),VS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),LinkedAt:c.nullish(),LastUsedAt:c.nullish(),LinkType:PS.nullish(),IsSignatureVerified:z.boolean().nullish()}).passthrough(),vp=z.object({TitleTransactionID:z.string().nullish(),Type:xp.nullish(),NetworkID:z.string().nullish(),AssetID:z.string().nullish(),Amount:Y.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),NS=z.object({Status:TS.nullish(),Tier:kS.nullish(),VerifiedAt:c.nullish(),ExpiresAt:c.nullish(),RejectedAt:c.nullish(),ProviderReference:z.string().nullish(),RejectionReason:z.string().nullish()}).passthrough(),_S=z.object({CurrencyID:z.string().nullish(),Deposits:z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),jS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:z.record(z.string(),_S).nullish()}).passthrough(),WS=z.object({NetworkID:z.string().nullish(),ItemCatalogID:z.string().nullish(),Deposits:z.number().nullish(),Withdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),QS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),PerCollection:z.record(z.string(),WS).nullish()}).passthrough(),KS=z.object({Tokens:jS.nullish(),Nfts:QS.nullish()}).passthrough(),ra=z.object({CurrencyID:z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Gt=z.object({Granted:z.boolean(),Mode:wi.nullish(),Error:z.string().nullish(),WalletRequired:z.boolean().nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),GrantedUntil:c.nullish(),Balances:z.array(ra).nullish()}).passthrough(),HS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:c.nullish(),Passed:z.boolean().nullish(),GrantedUntil:c.nullish(),Error:z.string().nullish(),Balances:z.array(ra).nullish()}).passthrough(),$S=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CanUnlink:z.boolean().nullish()}).passthrough(),Tp=z.object({Mode:wi.nullish(),TokenGates:z.array(Ip).nullish(),WalletLoginEnabled:z.boolean().nullish(),CanLinkWallet:z.boolean().nullish(),WalletsFromPlatformProfile:z.boolean().nullish(),LinkedWallets:z.array($S).nullish(),Status:Gt.nullish()}).passthrough(),JS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:c.nullish(),LoggedInAt:c.nullish(),GatePassed:z.boolean().nullish(),GatedBalances:z.array(ra).nullish()}).passthrough(),ZS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),UnlinkedAt:c.nullish()}).passthrough(),YS=z.object({Version:z.number().nullish(),Stats:KS.nullish(),LinkedWallets:z.record(z.string(),VS).nullish(),LastWalletLogin:JS.nullish(),PlayAccess:HS.nullish(),PendingWithdrawals:z.array(vp).nullish(),Kyc:NS.nullish(),FirstActivityAt:c.nullish(),LastActivityAt:c.nullish(),IsFlagged:z.boolean().nullish(),FlagReason:z.string().nullish(),UnlinkedWallets:z.array(ZS).nullish()}).passthrough(),XS=z.object({CurrencyID:z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:c}).passthrough(),di=z.object({CryptoBalances:z.record(z.string(),XS).nullish(),PendingAdded:vp.nullish(),PendingRemovedIDs:z.array(z.string()).nullish()}).passthrough(),ex=z.object({Amount:Y,Frozen:Y,CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough().transform(o=>o),tx=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:Dp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:sa.nullish(),SignatureData:z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),TokenID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:c.nullish(),BurnAmount:z.number().nullish(),RefundedAt:c.nullish(),RefundCheckedAt:c.nullish()}).passthrough(),ix=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:Dp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:sa.nullish(),SignatureData:z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),NFTID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),SkinID:z.string().nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:c.nullish()}).passthrough(),Ap=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),oa=z.object({TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),ContractAddress:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(Ap).nullish(),Signature:z.string().nullish()}).passthrough(),aa=z.object({Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),ProgramID:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(Ap).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),kp=z.object({Blockchain:na.nullish(),CryptoCurrencies:z.record(z.string(),ia).nullish()}).passthrough(),zp=z.object({State:YS.nullish(),CryptoBalances:z.record(z.string(),ex).nullish()}).passthrough(),wp=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:di.nullish()}).passthrough(),Mp=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}).passthrough(),Op=z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:c.nullish(),EvmSignature:oa.nullish(),SolanaSignature:aa.nullish(),StateDelta:di.nullish(),ChainID:z.number().nullish()}).passthrough(),Ep=z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),EvmSignature:oa.nullish(),SolanaSignature:aa.nullish(),StateDelta:di.nullish(),Inventory:K.nullish()}).passthrough(),Up=z.object({TokenTransactions:z.array(tx).nullish(),NFTTransactions:z.array(ix).nullish(),RefundedIDs:z.array(z.string()).nullish()}).passthrough(),la=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:z.string().nullish()}).passthrough(),qp=z.object({TitleTransactionID:z.string().nullish(),Kind:xp.nullish(),EvmSignature:oa.nullish(),SolanaSignature:aa.nullish()}).passthrough(),Bp=z.object({TitleTransactionID:z.string().nullish(),OnChainTxHash:z.string().nullish(),Status:sa.nullish(),StateDelta:di.nullish()}).passthrough(),He={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 sx="Blockchain",Lp="Blockchain:Definitions",kn=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Lp,e);if(t)return a(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return c$1;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(sx,n.data.Blockchain),this.ctx.data.config.patchSection(Lp,n.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",n.data)),n)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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 b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,i,s,n){if(!e)return b("client","CurrencyID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let r=this.ctx.authedRequest();if(!r)return c$1;r.CurrencyID=e,r.NetworkID=t,r.WalletAddress=i,r.Amount=s,r.Category=An(n);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(r);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,i,s,n,r,p){if(!e)return b("client","ItemID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.NetworkID=t,d.WalletAddress=i,d.Amount=s,d.Category=An(n),r!==void 0&&(d.Level=r),p&&(d.ItemInstanceID=p);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(d);return R.ok&&(this.ctx.data.user.applyBlockchainStateDelta(R.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",R.data)),R}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","TitleTransactionID is required.");if(!t)return b("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.TitleTransactionID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return c$1;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 c$1;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var nx={Head:"Head",Torso:"Torso",Legs:"Legs"},zn=z.enum(["Head","Torso","Legs"]).catch("Head"),rx={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},ua=z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Fp=z.object({AttackTarget:zn,DefenseTarget:zn});var ox=z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),ax=z.object({RoundIndex:z.number().nullish(),AttackerID:z.string().nullish(),DefenderID:z.string().nullish(),AttackZone:zn.nullish(),DefenseZone:zn.nullish(),HitType:ox.nullish(),DamageDealt:z.number().nullish(),DefenderHpRemaining:z.number().nullish()}).passthrough(),lx=z.object({MaxHp:z.number().nullish(),CurrentHp:z.number().nullish(),Damage:z.number().nullish(),AttackSpeed:z.number().nullish(),CritChance:z.number().nullish(),CritMultiplier:z.number().nullish(),Armor:z.number().nullish(),DodgeChance:z.number().nullish()}).passthrough(),ux=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Gp=z.object({UserID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),SelectedCharacter:Mo.nullish(),BattleStrategy:z.array(Fp).nullish(),UnstackableItems:z.record(z.string(),ux).nullish(),Stats:lx.nullish()}).passthrough(),cx=z.object({WinnerUserID:z.string().nullish(),LoserUserID:z.string().nullish(),Entry:ce.nullish(),NetReward:ce.nullish(),BattleLog:z.array(ax).nullish(),IsDraw:z.boolean().nullish(),P1BattleProfile:Gp.nullish(),P2BattleProfile:Gp.nullish()}).passthrough(),Vp=z.object({MatchID:z.string(),TitleID:z.string().nullish(),RuleID:z.string().nullish(),CreatedAt:c.nullish(),CreatorID:z.string().nullish(),CreatorCharacterID:z.string().nullish(),CreatorStrategy:z.array(Fp).nullish(),TargetUserID:z.string().nullish(),Entry:ce.nullish(),CreationCostPaid:ce.nullish(),RefundCreationCostOnCancel:z.boolean().nullish(),ExpiresAt:c.nullish(),JoinedByUserID:z.string().nullish(),JoinedByCharacterID:z.string().nullish(),JoinedAt:c.nullish(),Status:ua.nullish(),WinnerUserID:z.string().nullish(),CompletedAt:c.nullish(),IsRewardDistributed:z.boolean().nullish(),RewardDistributedAt:c.nullish()}).passthrough(),Np=z.object({Status:ua,MatchID:z.string(),Entry:ce.nullish(),Resources:M.nullish()}),_p=z.object({Match:Vp.nullish()}),jp=z.object({MatchID:z.string(),Status:ua,Resources:M.nullish()}),Wp=z.object({Battle:cx.nullish(),Resources:M.nullish(),ResourcesDual:Dt.nullish()}),ca=z.object({Matches:z.array(Vp).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}),Ct={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var px=z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var hx=z.enum(["Constant","Variable","Curve"]).catch("Constant"),dx=z.object({HealthStatID:z.string().nullish(),DamageStatID:z.string().nullish(),ArmorStatID:z.string().nullish(),AttackSpeedStatID:z.string().nullish(),CritChanceStatID:z.string().nullish(),CritDamageStatID:z.string().nullish(),DodgeStatID:z.string().nullish(),AllMightStatID:z.string().nullish()}).passthrough(),mx=z.enum(["Flat","PercentReduction"]).catch("Flat"),fx=z.object({MaxRounds:z.number().nullish(),BlockDamageMultiplier:z.number().nullish(),MinHitDamage:z.number().nullish(),DefaultCritMultiplier:z.number().nullish(),MaxCritChance:z.number().nullish(),MaxDodgeChance:z.number().nullish(),ArmorMode:mx.nullish(),MaxArmorReduction:z.number().nullish()}).passthrough(),gx=z.object({Kind:hx.nullish(),Constant:z.number().nullish(),VariableID:z.string().nullish(),Argument:z.string().nullish(),Curve:Ve.nullish(),OnePlus:z.boolean().nullish()}).passthrough(),yx=z.object({Coefficient:z.number().nullish(),Factors:z.array(gx).nullish()}).passthrough(),Ht=z.object({Terms:z.array(yx).nullish()}).passthrough(),Rx=z.object({Health:Ht.nullish(),Damage:Ht.nullish(),Armor:Ht.nullish(),AttackSpeed:Ht.nullish(),CritChance:Ht.nullish(),CritDamage:Ht.nullish(),Dodge:Ht.nullish()}).passthrough(),Qp=z.object({StatMapping:dx.nullish(),Combat:fx.nullish(),Formula:Rx.nullish()}).passthrough(),Cx=z.object({BurnRate:z.number().nullish()}).passthrough(),Mi=z.object({Kind:px.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),TokenType:_i.nullish(),EntityID:z.string().nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish()}).passthrough(),Kp=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Mi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),Hp=z.object({PriceOptions:ue.nullish(),RefundCostOnCancel:z.boolean().nullish(),MaxOpenMatches:z.number().nullish(),OfferLifetimeSeconds:z.number().nullish(),Limits:Re.nullish(),AllowPrivateMatches:z.boolean().nullish(),MaxMatchesPerOpponentPerDay:z.number().nullish()}).passthrough(),Sx=z.object({RuleID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Economy:Cx.nullish(),Entry:Kp.nullish(),Creation:Hp.nullish(),Settings:Qp.nullish()}).passthrough(),xx=z.object({Rules:z.record(z.string(),Sx).nullish(),Defaults:Qp.nullish(),EntryDefaults:Kp.nullish(),CreationDefaults:Hp.nullish()}).passthrough(),pa=z.object({InstantBattle:xx.nullish()}).passthrough(),$p=pa;var bx={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},ha=z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),Dx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},da=z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),Px={Burn:"Burn",Ledger:"Ledger"},Ix=z.enum(["Burn","Ledger"]).catch("Burn"),Mn={Item:"Item",VirtualCurrency:"VirtualCurrency"},ma=z.enum(["Item","VirtualCurrency"]).catch("Item"),vx=z.object({Percent:z.number().nullish(),MinPerPosition:j.nullish()}).passthrough(),On=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Mi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),fa=z.object({Percent:z.number().nullish(),MinPerPosition:j.nullish(),Sink:Ix.nullish(),LedgerAccountID:z.string().nullish(),PerCatalogOverrides:z.record(z.string(),vx).nullish(),ApplyToDirectTrades:z.boolean().nullish()}).passthrough(),Tx=z.object({AllowedCatalogIDs:z.array(z.string()).nullish(),DeniedCatalogIDs:z.array(z.string()).nullish(),DeniedItemIDs:z.array(z.string()).nullish(),AllowUnstackableWithState:z.boolean().nullish(),AllowedCurrencyIDs:z.array(z.string()).nullish(),DeniedCurrencyIDs:z.array(z.string()).nullish()}).passthrough(),Ax=z.object({Enabled:z.boolean().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),MaxActiveListings:z.number().nullish(),CreateLimits:Re.nullish(),BuyLimits:Re.nullish(),ListingFeeOptions:ue.nullish(),RefundListingFeeOnCancel:z.boolean().nullish()}).passthrough(),kx=z.object({Enabled:z.boolean().nullish(),MinDurationHours:z.number().nullish(),MaxDurationHours:z.number().nullish(),AntiSnipeWindowSeconds:z.number().nullish(),AntiSnipeExtensionSeconds:z.number().nullish(),MaxAntiSnipeExtensions:z.number().nullish(),MinBidStepPercent:z.number().nullish(),MinBidStepAbsolute:j.nullish(),BidLimits:Re.nullish()}).passthrough(),zx=z.object({Enabled:z.boolean().nullish(),MaxActiveOrders:z.number().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),CreateLimits:Re.nullish(),FillLimits:Re.nullish()}).passthrough(),wx=z.object({Enabled:z.boolean().nullish(),OfferExpirationHours:z.number().nullish(),MaxPendingOutgoing:z.number().nullish(),AllowGifts:z.boolean().nullish(),CreateLimits:Re.nullish()}).passthrough(),Mx=z.object({Enabled:z.boolean().nullish()}).passthrough(),ga=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:fe.nullish(),PricePolicy:On.nullish(),Commission:fa.nullish(),Tradability:Tx.nullish(),Listings:Ax.nullish(),Auctions:kx.nullish(),BuyOrders:zx.nullish(),DirectTrades:wx.nullish(),Matching:Mx.nullish()}).passthrough(),Jp=z.object({BidIndex:z.number().nullish(),UserID:z.string().nullish(),Amount:j.nullish(),Settled:z.boolean().nullish(),SettledAt:c.nullish()}).passthrough(),Ox=z.object({BidAxisType:ni.nullish(),BidCurrencyID:z.string().nullish(),BidCatalogID:z.string().nullish(),BidItemID:z.string().nullish(),StartingBid:j.nullish(),CurrentBid:j.nullish(),CurrentBidderID:z.string().nullish(),BidCount:z.number().nullish(),ExtensionCount:z.number().nullish(),PendingRefunds:z.array(Jp).nullish()}).passthrough(),wn=z.object({LastAt:c.nullish(),DailyCount:z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),Ex=z.object({Create:wn.nullish(),Buy:wn.nullish(),Sell:wn.nullish(),Bid:wn.nullish()}).passthrough(),Ux=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),qx=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:Ux.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),kt=z.object({OfferID:z.string().nullish(),OfferType:ha.nullish(),Status:da.nullish(),CreatorUserID:z.string().nullish(),CreatorPublicData:Ee.nullish(),TargetUserID:z.string().nullish(),GoodsType:ma.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:j.nullish(),GoodsInstances:z.array(qx).nullish(),Price:ce.nullish(),Auction:Ox.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),Bx=z.object({GoodsType:ma.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),CountsByType:z.partialRecord(ha,j).nullish()}).passthrough(),Zp=z.object({Definitions:ga.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish()}).passthrough(),ya=z.object({Offers:z.array(kt).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Yp=z.object({Groups:z.array(Bx).nullish()}).passthrough(),Xp=z.object({Offer:kt.nullish()}).passthrough(),lt=z.object({OfferID:z.string().nullish(),Status:da.nullish(),Settlement:Dt.nullish(),Resources:M.nullish(),CommissionTaken:ce.nullish()}).passthrough(),Oi=z.object({OfferID:z.string().nullish(),Offer:kt.nullish(),Resources:M.nullish(),Matched:z.boolean().nullish(),Settlement:lt.nullish()}).passthrough(),eh=z.object({OfferID:z.string().nullish(),CurrentBid:j.nullish(),BidCount:z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish()}).passthrough(),En=z.object({MyOffers:z.array(kt).nullish(),MyBids:z.array(kt).nullish(),MyBuyOrders:z.array(kt).nullish(),IncomingTrades:z.array(kt).nullish(),OutgoingTrades:z.array(kt).nullish(),Claimables:z.array(kt).nullish(),DrainedRefunds:z.array(Jp).nullish(),Limits:Ex.nullish()}).passthrough(),Lx=z.object({OfferID:z.string().nullish(),OfferType:ha.nullish(),FinalStatus:da.nullish(),SellerUserID:z.string().nullish(),BuyerUserID:z.string().nullish(),GoodsType:ma.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:j.nullish(),PricePaid:ce.nullish(),CommissionTaken:ce.nullish(),CompletedAt:c.nullish(),MyRole:z.string().nullish()}).passthrough(),th=z.object({Entries:z.array(Lx).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),ze={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 Gx="Marketplace",ih={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"]},Un=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ih,{schema:En,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(Gx,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,s=20){if(!e)return b("client","ItemID is required.");let n=this.ctx.authedRequest();if(!n)return c$1;n.ItemID=e,n.OfferTypeFilter=t,n.ContinuationToken=i,n.PageSize=s;let r=await this.ctx.api.marketplace.getOffersByItem(n);return r.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",r.data),r}async getOffer(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let s=this.ctx.authedRequest();if(!s)return c$1;s.ItemID=e,s.ContinuationToken=t,s.PageSize=i;let n=await this.ctx.api.marketplace.getBuyOrders(s);return n.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",n.data),n}getMyState(e,t){return this.ctx.cache.read(ih,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let s=this.ctx.authedRequest();if(!s)return c$1;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let n=await this.ctx.api.marketplace.getHistory(s);return n.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",n.data),n}async createListing(e,t,i,s,n,r,p){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.PriceBundle=s,d.DurationHours=n,d.ItemInstanceIDs=r,d.SelectedOptionID=p;let R=await this.ctx.api.marketplace.createListing(d);return this.applyCreateOfferResult(R,"marketplace:listingCreated"),R}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c$1;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let r=await this.ctx.api.marketplace.marketBuy(s);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",r.data)),r}async marketSell(e,t,i){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c$1;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let r=await this.ctx.api.marketplace.marketSell(s);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",r.data)),r}async createAuction(e,t,i,s,n,r,p={}){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.BidAxisType=s,d.BidCurrencyID=p.bidCurrencyID,d.BidCatalogID=p.bidCatalogID,d.BidItemID=p.bidItemID,d.StartingBid=n,d.DurationHours=r,d.ItemInstanceIDs=p.itemInstanceIDs,d.SelectedOptionID=p.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(d);return this.applyCreateOfferResult(R,"marketplace:auctionCreated"),R}async placeBid(e,t){if(!e)return b("client","OfferID is required.");if(!t||t<=0)return b("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return c$1;i.OfferID=e,i.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,s,n){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let r=this.ctx.authedRequest();if(!r)return c$1;r.ItemID=e,r.CatalogID=t,r.GoodsAmount=i,r.PriceBundle=s,r.DurationHours=n;let p=await this.ctx.api.marketplace.createBuyOrder(r);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,s,n){if(!e)return b("client","TargetUserID is required.");if(!t)return b("client","CatalogID is required.");if(!i)return b("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return c$1;r.TargetUserID=e,r.CatalogID=t,r.ItemID=i,r.ItemInstanceIDs=s,r.RequestedBundle=n;let p=await this.ctx.api.marketplace.createDirectTrade(r);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return b("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.OfferID=e,i.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(i);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.OfferID=e;let n=await t(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,n.data)),n}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=Mn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Mn.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):b("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 qn=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return b("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let s=await this.ctx.api.multiplayer.createRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.RoomID=e,s.TargetUserID=t,s.Ban=i;let n=await this.ctx.api.multiplayer.kickMember(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",n.data),n}async unbanMember(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return c$1;i.Page=e,i.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(i);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,i,s){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");if(!i)return b("client","SignalKind is required.");let n=this.ctx.authedRequest();if(!n)return c$1;n.RoomID=e,n.TargetUserID=t,n.SignalKind=i,n.Payload=s;let r=await this.ctx.api.multiplayer.sendSignal(n);return r.ok&&this.ctx.emitter.emit("multiplayer:signalSent",r.data),r}async sendChat(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(i);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,i){if(!e)return b("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.RoomID=e,s.Ready=t,s.MemberState=i;let n=await this.ctx.api.multiplayer.setMemberState(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",n.data),n}};var sh=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Bn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;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)):c$1}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 b("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):c$1}async getCreatorProfile(e,t,i){if(!e)return b("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):c$1}async publish(e){if(!e.files||e.files.length===0)return b("client","At least one file is required.");let t=new Map,i=e.files.map((d,R)=>{if("sourceAssetUrl"in d)return {Role:d.role,ContentType:d.contentType,SourceAssetUrl:d.sourceAssetUrl};let V=nh(d.data,d.contentType);return t.set(R,V),{Role:d.role,ContentType:d.contentType,Size:V.size}}),s=e.thumbnail?nh(e.thumbnail.data,e.thumbnail.contentType):null,n=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!n.ok)return n;let r=n.data.Uploads??[];for(let d=0;d<r.length;d++){let R=r[d];if(!R||R.ServerCopy||!R.Url)continue;let V=t.get(d);if(!V)return b("client",`No bytes for file #${d+1}.`);let ae=await this.putBytes(R.Url,V,R.ContentType??V.type);if(!ae.ok)return ae}let p=n.data.ThumbnailUpload;if(p?.Url&&s){let d=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!d.ok)return d}return this.publishUploaded({ContentID:n.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})}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):c$1}async publishUploaded(e){if(!e.ContentID)return b("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let s=await this.ctx.api.workshop.updateContent(i);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getMyContent(s)):c$1}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let s=await this.ctx.api.workshop.acquire(i);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let s of t.data.Files??[])if(s.Url)try{let n=await this.ctx.fetchImpl(s.Url);if(!n.ok)return b("connection",`Download failed (HTTP ${n.status}).`);i.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await n.arrayBuffer()});}catch(n){return b("connection",`Download failed: ${n instanceof Error?n.message:String(n)}${sh}`)}return a({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)):c$1}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):c$1}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${sh}`)}}contentRequest(e){if(!e)return b("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):c$1}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 nh(o,e){return o instanceof Blob?o:typeof o=="string"?new Blob([new TextEncoder().encode(o)],{type:e}):o instanceof Uint8Array?new Blob([o.slice().buffer],{type:e}):new Blob([o],{type:e})}var Fx={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},Vx=z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Nx={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},rh=z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),_x={Everyone:"Everyone",Owner:"Owner",Server:"Server"},oh=z.enum(["Everyone","Owner","Server"]).catch("Everyone"),jx={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},Wx=z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),Qx={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},Kx=z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),Hx={Count:"Count",Sum:"Sum"},$x=z.enum(["Count","Sum"]).catch("Count"),Jx={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},Zx=z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),Yx={Strict:"Strict",Loose:"Loose"},Xx=z.enum(["Strict","Loose"]).catch("Strict"),eb=z.object({Kind:Kx,Collection:z.string().nullish(),Validate:z.boolean().nullish()}),tb=z.object({Type:rh,ItemType:rh.nullish(),Ref:eb.nullish(),Required:z.boolean().optional(),Default:z.string().nullish(),Min:z.number().nullish(),Max:z.number().nullish(),MaxLength:z.number().nullish(),MaxItems:z.number().nullish(),Enum:z.array(z.string()).nullish(),Unique:z.boolean().optional(),UniqueIgnoreCase:z.boolean().optional(),Indexed:z.boolean().optional(),Visibility:oh.optional(),ClientWritable:z.boolean().nullish(),Immutable:z.boolean().optional(),Description:z.string().nullish(),AllowedMimeTypes:z.array(z.string()).nullish(),MaxFileBytes:z.number().nullish()}),ib=z.object({ID:z.string(),Components:z.array(z.object({Field:z.string(),Descending:z.boolean().optional()})).default([])}),Ln=z.object({Mode:Wx,Role:z.string().nullish(),MembersField:z.string().nullish()}),sb=z.object({Read:z.array(Ln).nullish(),Create:z.array(Ln).nullish(),Update:z.array(Ln).nullish(),Delete:z.array(Ln).nullish()}),Ra=z.object({Cost:ce.nullish(),Grant:ce.nullish()}),nb=z.object({ID:z.string(),SortKey:z.string(),PartitionField:z.string().nullish(),PageSize:z.number().optional(),MaxItems:z.number().optional(),PublishItems:z.boolean().optional()}),rb=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Namespace:z.string().nullish(),Tags:z.array(z.string()).nullish(),Enabled:z.boolean().nullish(),Kind:Vx,Mode:Xx.optional(),SchemaVersion:z.number().optional(),Fields:z.record(z.string(),tb).nullish(),SortKeys:z.array(ib).nullish(),Access:sb.nullish(),Limits:z.object({MaxItemBytes:z.number().nullish(),MaxItemsPerOwner:z.number().nullish(),TtlSeconds:z.number().nullish()}).nullish(),OnOwnerDeleted:Zx.optional(),Counters:z.array(z.object({ID:z.string(),Kind:$x,SumField:z.string().nullish(),GroupBy:z.string().nullish(),Visibility:oh.optional()})).nullish(),Economy:z.object({OnCreate:Ra.nullish(),OnUpdate:Ra.nullish(),OnDelete:Ra.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:z.array(nb).nullish(),AnonymousSearch:z.boolean().nullish(),Integrations:z.object({QuestMetricOnCreate:z.string().nullish(),QuestMetricOnUpdate:z.string().nullish(),QuestMetricOnDelete:z.string().nullish(),AnalyticsEventOnCreate:z.string().nullish(),AnalyticsEventOnUpdate:z.string().nullish(),AnalyticsEventOnDelete:z.string().nullish(),TriggerOnCreate:z.string().nullish(),TriggerOnUpdate:z.string().nullish(),TriggerOnDelete:z.string().nullish()}).nullish(),Moderation:z.object({BlockedTerms:z.array(z.string()).nullish()}).nullish()}),ah=z.object({Enabled:z.boolean().optional(),Collections:z.record(z.string(),rb).default({})}),ob=z.object({FileID:z.string(),Url:z.string(),ContentType:z.string().nullish(),Size:z.number()}),lh=z.object({FileID:z.string(),UploadUrl:z.string(),ContentType:z.string(),MaxBytes:z.number(),ExpiresAt:z.string()}),mi=z.object({Collection:z.string(),ItemID:z.string(),OwnerUserID:z.string().nullish(),Data:z.record(z.string(),z.unknown()).default({}),Version:z.number(),CreatedAt:z.string(),UpdatedAt:z.string(),ExpireAt:z.string().nullish(),Expanded:z.record(z.string(),z.unknown()).nullish(),Files:z.record(z.string(),ob).nullish()}),Ca=z.object({Item:mi}),uh=z.object({Items:z.array(mi).default([]),Missing:z.array(z.string()).default([])}),Sa=z.object({Items:z.array(mi).default([]),NextCursor:z.string().nullish()}),ch=z.object({Count:z.number(),Capped:z.boolean().optional()}),xa=z.object({Item:mi,AlreadyExists:z.boolean().optional(),Economy:M.nullish()}),ph=z.object({ItemID:z.string(),Deleted:z.boolean(),Economy:M.nullish()}),hh=z.object({CounterID:z.string(),Group:z.unknown().optional(),Value:z.number()}),dh=z.object({Results:z.array(z.object({Op:z.string(),Collection:z.string(),ItemID:z.string(),Item:mi.nullish(),Deleted:z.boolean().optional()})).default([])}),mh=z.object({Roles:z.array(z.string()).default([])}),fh=z.object({Views:z.record(z.string(),z.string()).default({}),ItemUrlTemplate:z.string().nullish()}),gh=z.object({Version:z.string(),Collection:z.string(),View:z.string(),SortKey:z.string().nullish(),PageSize:z.number(),UpdatedAt:z.string(),BaseUrl:z.string(),Partitions:z.record(z.string(),z.object({Segment:z.string(),Pages:z.number(),Total:z.number()})).default({})}),yh=z.object({Page:z.number(),HasMore:z.boolean(),Items:z.array(mi).default([])}),ab={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 lb=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Sh=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Da=100,Rh=25,Ch=100;function ub(o,e,t){return {Field:o,Op:e,Value:t}}var Gn=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(c$1)}get(e,t,i={}){let s=it(e)??Ei(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.get({...n,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let s=it(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(r=>Sh.test(r)))];return n.length?n.length>Ch?Promise.resolve(b("client",`At most ${Ch} ids per call.`)):this.call(r=>this.ctx.api.dataCollections.getMany({...r,Collection:e,ItemIDs:n,Expand:i.expand})):Promise.resolve(b("client","At least one valid item id is required."))}query(e,t={},i={}){let s=it(e)??ba(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.query({...n,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),n=[],r=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:r,Limit:t.Limit??Da},i);if(!p.ok)return p;if(n.push(...p.data.Items),r=p.data.NextCursor??void 0,!r||n.length>=s)return a(n.slice(0,s))}}count(e,t={}){let i=it(e)??ba(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,i={}){let s=it(e)??(i.itemID?Ei(i.itemID):null);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.create({...n,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,s={}){let n=it(e)??Ei(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.update({...r,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=it(e)??Ei(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.delete({...n,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(b("client","Operations are empty."));if(e.length>Rh)return Promise.resolve(b("client",`At most ${Rh} operations per batch.`));let t=e.map(i=>it(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let s=it(e);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.getCounter({...n,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,s){let n=it(e);return n?Promise.resolve(n):t?s>0?this.call(r=>this.ctx.api.dataCollections.beginFileUpload({...r,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(b("client","File size must be positive.")):Promise.resolve(b("client","Field is required."))}async uploadFile(e,t,i,s={}){let n=s.contentType||i.type||"application/octet-stream",r=await this.beginFileUpload(e,t,n,i.size);if(!r.ok)return r;let p=await this.putBytes(r.data.UploadUrl,i,r.data.ContentType||n);return p.ok?r:p}async getPublicViews(e){let t=it(e);if(t)return t;let i=this.publicViews.get(e);if(i)return a(i);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,i={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let n=s.data.Views[t];if(!n)return b("client",`Collection '${e}' has no public view '${t}'.`);let r=await this.fetchJson(n,gh);if(!r.ok)return r;let p=r.data.Partitions[i.partition??""],d=Math.max(1,i.page??1);if(!p||d>p.Pages)return a({pointer:r.data,page:{Page:d,HasMore:false,Items:[]}});let R=await this.fetchJson(`${r.data.BaseUrl}${p.Segment}/page-${d}.json`,yh);return R.ok?a({pointer:r.data,page:R.data}):R}getPublic(e,t){let i=it(e)??Ei(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=it(e)??ba(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(c$1)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return b("connection","Internet Connection Error")}if(!i.ok)return b("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return b("server","CDN answer is not JSON.")}let n=t.safeParse(s);return n.success?a(n.data):b("server","CDN answer has an unexpected shape.")}};function it(o){return lb.test(o??"")?null:b("client",`Collection id '${o}' is invalid (letters, digits, '_', '-', ':').`)}function Ei(o){return Sh.test(o??"")?null:b("client",`Item id '${o}' is invalid.`)}function ba(o){return o.Limit!=null&&(o.Limit<1||o.Limit>Da)?b("client",`Limit must be 1..${Da}.`):(o.Where?.length??0)>8?b("client","At most 8 filters per query."):null}var Pa={Open:"Open",Declared:"Declared"},cb=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Blocked:z.boolean().nullish(),Highlight:z.number().nullish()}).passthrough(),pb=z.object({ParamName:z.string().nullish(),DisplayName:z.string().nullish()}).passthrough(),xh=z.object({Enabled:z.boolean().nullish(),EventNaming:z.string().nullish(),Events:z.record(z.string(),cb).nullish(),Dimensions:z.array(pb).nullish(),RetentionDays:z.number().nullish(),AutomaticEvents:z.boolean().nullish()}).passthrough(),Ft={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},St={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Fn=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,hb={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},db=z.object({Index:z.number().nullish(),Name:z.string().nullish(),Reason:z.string().nullish()}).passthrough(),bh=z.object({Accepted:z.number().nullish(),Dropped:z.array(db).nullish(),Duplicate:z.boolean().nullish(),Disabled:z.boolean().nullish()}).passthrough(),Ia={LogEvents:"LogEvents"};function Dh(o,e=0){let t=o??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let p=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let p=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let n=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(n)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(n[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let r=/\bWindows NT (\d+\.\d+)/.exec(t);return r?{osName:"Windows",osVersion:r[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function Ph(o){let e=typeof navigator>"u"?void 0:navigator,t=Dh(e?.userAgent??"",e?.maxTouchPoints??0),i={};o.appVersion&&(i.AppVersion=o.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let s=o.locale||e?.language;return s&&(i.Language=s),i}var mb=25,fb=3e4,Ih=1800*1e3,vh=500,gb=5,yb=1e3,Rb=3600*1e3,Th="idos_analytics_queue",va="idos_analytics_pending",Ta="idos_analytics_opt_out",Ah="idos_analytics_first_open",kh="idos_analytics_last_activity",zh="idos_analytics_last_context",wh="idos_analytics_owner",Vn=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"||!Fn.test(e)?b("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Cb(e)?b("client",`Event name "${e}" uses a reserved prefix (${St.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return b("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Ft.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return a(null);if(this.config()?.Enabled===false)return this.clear(),a(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return a(null);this.pending={BatchID:d(),Events:this.queue.splice(0,St.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return c$1;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(Ta);return}this.write(Ta,"1"),this.clear();}get isEnabled(){return this.read(Ta)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(wh);e&&t&&t!==e&&this.clear(),e&&this.write(wh,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},fb),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(kh)??"0");this.read(Ah)||(this.write(Ah,new Date().toISOString()),this.enqueue(Ft.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(zh);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Ft.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Ft.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(zh,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Ih)&&this.enqueue(Ft.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>=Ih&&this.enqueue(Ft.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,s){if(!this.isEnabled||this.disabledByServer)return a(null);let n=this.config();if(n?.Enabled===false)return a(null);if(s&&n?.AutomaticEvents===false)return a(null);if(n?.Events?.[e]?.Blocked)return b("client",`Event "${e}" is blocked by the title.`);if(!s&&n?.EventNaming?.toLowerCase()===Pa.Declared.toLowerCase()&&!n.Events?.[e])return b("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return b("client","value must be a finite number.");let r=Sb(t);if(r.error)return b("client",r.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return r.params&&(p.Params=r.params),i!==void 0&&(p.Value=i),this.queue.push(p),this.queue.length>vh&&this.queue.splice(0,this.queue.length-vh),this.touch(),this.persist(),this.started&&this.queue.length>=mb&&this.flush(),a(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},yb));}dropStale(){let e=Date.now()-(St.maxEventAgeMs-Rb);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??=Ph({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(Th);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(va);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(Th,this.queue),this.pending?this.writeJson(va,this.pending):this.remove(va);}touch(){this.write(kh,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 Cb(o){let e=o.toLowerCase();return St.reservedPrefixes.some(t=>e.startsWith(t))}function Sb(o){if(!o)return {};let e=Object.keys(o);if(e.length===0)return {};if(e.length>St.maxParams)return {error:`Too many parameters: ${e.length}, max ${St.maxParams}.`};let t={};for(let i of e){if(!Fn.test(i))return {error:`Invalid parameter name "${i}".`};let s=o[i];typeof s=="string"?t[i]=s.length>St.maxStringValueLength?s.slice(0,St.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var xb="idos_experiments",Nn=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 c$1;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let n=Number(s);return s.trim()!==""&&Number.isFinite(n)?n:i}if(typeof i=="boolean"){let n=s.trim().toLowerCase();return n==="true"||n==="1"?true:n==="false"||n==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,n]of t){let r=this.views.get(s);(!r||r.VariantID!==n.VariantID||r.Status!==n.Status)&&i.push(n);}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 `${xb}:${this.ctx.settings.titleID}`}};function Vt(o,e,t,i){let n=`api/v2/${o&&o.length>0?o:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Vt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,s){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...s,ticket:t.ClientSessionTicket})}};var _n=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Ia.LogEvents,e,bh,{silent:true})}};var bb=z.object({VariantID:z.string().nullish(),DisplayName:z.string().nullish(),Weight:z.number().nullish(),IsControl:z.boolean().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),Db={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Pb=z.object({MetricID:z.string().nullish(),Kind:z.string().nullish(),EventName:z.string().nullish(),IsPrimary:z.boolean().nullish()}).passthrough(),Ib=z.object({ExperimentID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),IsEnabled:z.boolean().nullish(),Schedule:fe.nullish(),Gate:Z.nullish(),Variants:z.array(bb).nullish(),Salt:z.string().nullish(),LayerID:z.string().nullish(),StickyAssignment:z.boolean().nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Goals:z.array(Pb).nullish(),ActivationEvent:z.string().nullish(),RolloutVariantID:z.string().nullish()}).passthrough(),Mh=z.object({Experiments:z.record(z.string(),Ib).nullish()}).passthrough(),vb={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Tb=z.object({ExperimentID:z.string().nullish(),VariantID:z.string().nullish(),Status:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),Oh=z.object({Experiments:z.array(Tb).nullish(),IsAbTestingAvailable:z.boolean().nullish()}).passthrough(),Aa={GetExperiments:"GetExperiments"};var jn=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Aa.GetExperiments,e,Oh)}};var Eh=z.object({PlatformUserID:z.string().nullish(),PlatformAuthToken:z.string().nullish(),PlatformAuthTokenExpiration:c.nullish(),TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:c,PlayAccess:Gt.nullish(),RefreshToken:z.string().nullish(),RefreshTokenExpiration:c.nullish()}),Uh=z.object({TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:c,RefreshToken:z.string(),RefreshTokenExpiration:c.nullish(),PlayAccess:Gt.nullish()}),Ab=z.object({ReturnMode:z.string().nullish(),UrlScheme:z.string().nullish(),UserCodeSupported:z.boolean().nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),qh=z.object({Google:z.object({Enabled:z.boolean().nullish(),WebClientID:z.string().nullish(),PlatformFallback:z.boolean().nullish(),AndroidClientID:z.string().nullish(),IosClientID:z.string().nullish(),DesktopClientID:z.string().nullish()}).passthrough().nullish(),Apple:z.object({Enabled:z.boolean().nullish(),BundleID:z.string().nullish(),ServiceID:z.string().nullish()}).passthrough().nullish(),PlayAccessMode:wi.nullish(),WalletLoginNetworks:z.array(z.object({NetworkID:z.string().nullish(),Type:z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:z.boolean().nullish(),NativeSso:Ab.nullish()}).passthrough(),Bh=z.object({Linked:z.boolean().nullish(),Challenge:z.string().nullish(),ExpiresAt:c.nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),PlayAccess:Gt.nullish()}).passthrough(),Lh=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CooldownUntil:c.nullish(),PlayAccess:Gt.nullish()}).passthrough(),Gh=z.object({CodeTtlMinutes:z.number().nullish(),ResendCooldownSeconds:z.number().nullish()}),qe=z.object({IsCompleted:z.boolean().nullish(),ServerTime:c.nullish()}),Fh=z.object({Message:z.string(),ExpiresAt:c}),Ue={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 Wn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Vt(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(Ue.RefreshSession),e,Uh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ue.GetAuthOptions),e,qh,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Vt(this.ctx.settings.titleID,"Authentication",Ue.LinkWallet,e.UserID??""),e,Bh,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Vt(this.ctx.settings.titleID,"Authentication",Ue.UnlinkWallet,e.UserID??""),e,Lh,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ue.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ue.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ue.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ue.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ue.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ue.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(Ue.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ue.RegisterWithEmail),e,Gh,{ticket:null})}confirmEmailRegistration(e){return this.login(Ue.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ue.ResendVerificationCode),e,qe,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ue.RequestWalletChallenge),e,Fh,{ticket:null})}loginWithWallet(e){return this.login(Ue.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ue.ForgotPassword),e,qe,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ue.ResetPassword),e,qe,{ticket:null})}};var kb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},Vh=z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),zb=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),IsEnabled:z.boolean().nullish(),Order:z.number().nullish()}).passthrough(),Nh=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),Locales:z.record(z.string(),zb).nullish(),MissingKeyMode:Vh.nullish(),MaxEntriesPerLocale:z.number().nullish(),MaxValueLengthBytes:z.number().nullish()}).passthrough(),wb=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish()}).passthrough(),_h=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish(),Fallback:wb.nullish()}).passthrough(),Qn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Mb=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),Order:z.number().nullish(),Version:z.number().nullish()}).passthrough(),jh=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),MissingKeyMode:Vh.nullish(),ResolvedLocale:z.string().nullish(),Locales:z.array(Mb).nullish()}).passthrough(),Wh=z.object({RequestedLocale:z.string().nullish(),Locale:z.string().nullish(),Version:z.number().nullish(),NotModified:z.boolean().nullish(),Entries:z.record(z.string(),z.string()).nullish(),FallbackLocale:z.string().nullish(),FallbackVersion:z.number().nullish()}).passthrough();var ka=z.object({TitleConfigVersion:z.string().nullish(),TitleConfigUrl:z.string().nullish(),User:z.unknown().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish(),Localization:_h.nullish(),Views:z.array(z.object({Name:z.string(),Key:z.string().nullish(),Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(o=>o),Qh=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish()}).passthrough().transform(o=>o),Kh=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),User:z.unknown().nullish()}).passthrough().transform(o=>o),Hh=z.object({}).passthrough().transform(o=>o),$h=z.object({}).passthrough().transform(o=>o),Jh=z.object({Today:z.number(),Yesterday:z.number(),CurrentWeek:z.number(),CurrentMonth:z.number(),Total:z.number(),TotalSessions:z.number(),FirstActiveAt:c.nullish(),LastActiveAt:c.nullish(),LongestSessionEverSeconds:z.number().nullish(),CurrentWeekActiveHoursMask:z.number().nullish(),CurrentMonthActiveHoursMask:z.number().nullish(),ReactivationCount:z.number().nullish(),History:z.record(z.string(),z.unknown()).nullish()}).passthrough(),Zh=z.object({Username:z.string()}),ut={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Kn=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(ut.GetClientState,e,ka)}getClientStateExcept(e){return this.send(ut.GetClientStateExcept,e,ka)}getStateVersions(e){return this.send(ut.GetStateVersions,e,Qh)}getUserState(e){return this.send(ut.GetUserState,e,Kh)}getInventory(e){return this.send(ut.GetInventory,e,Hh)}getEventTokens(e){return this.send(ut.GetEventTokens,e,$h)}getUsageTime(e){return this.send(ut.GetUsageTime,e,Jh)}addUsageTime(e){return this.send(ut.AddUsageTime,e,qe,{silent:true})}deleteUserAccount(e){return this.send(ut.DeleteUserAccount,e,qe)}changeUsername(e){return this.send(ut.ChangeUsername,e,Zh)}};var Hn=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(vn.Convert,e,gp)}cryptoConvert(e){return this.send(vn.CryptoConvert,e,yp)}};var Ob=z.object({ItemInstanceID:z.string(),Units:z.number(),Level:z.number()}),za=z.object({ServerTimeUtc:c,ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Level:z.number(),Resources:M.nullish(),FodderConsumed:z.array(Ob).nullish()}),Yh=z.array(Ie(za)),$n={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Eb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},Ub=z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),qb={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Bb=z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Lb=z.object({ContractAddress:z.string().nullish(),TokenID:z.string().nullish(),TokenStandard:z.string().nullish(),MaxLevel:z.number().nullish()}).passthrough(),Gb=z.object({Networks:z.record(z.string(),Lb).nullish(),MetadataUrl:z.string().nullish()}).passthrough(),Fb=z.object({FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),Vb=z.object({MinCharacterLevel:z.number().nullish(),UseRequirements:z.record(z.string(),z.number()).nullish(),AllowedCharacterIDs:z.array(z.string()).nullish(),AllowedSlotIDs:z.array(z.string()).nullish(),IdleRateBonus:z.number().nullish()}).passthrough(),Nb=z.object({ValuationMode:Ub.nullish(),WeightCurve:Ve.nullish(),Selection:Bb.nullish()}).passthrough(),_b=z.object({MaxLevel:z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Ve.nullish(),FlatBonusCurve:Ve.nullish(),PercentBonusCurve:Ve.nullish(),PowerCurve:Ve.nullish(),Fodder:Nb.nullish()}).passthrough(),jb=z.object({RarityID:z.string().nullish(),CollectionID:z.string().nullish(),AuthorID:z.string().nullish()}).passthrough(),Wb=z.object({ItemID:z.string(),CatalogID:z.string(),ItemClass:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),CustomData:z.record(z.string(),z.string()).nullish(),IsStackable:z.boolean().nullish(),IsTradable:z.boolean().nullish(),Weight:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),NFT:Gb.nullish(),Stats:Fb.nullish(),Equipment:Vb.nullish(),Upgrade:_b.nullish(),Metadata:jb.nullish(),ExpirationDurationSeconds:z.number().nullish(),MaxSupply:z.number().nullish()}).passthrough(),Qb=z.object({Items:z.record(z.string(),Wb).nullish()}).passthrough(),Jn=z.object({Catalogs:z.record(z.string(),Qb).nullish()}).passthrough();var Zn=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send($n.UpgradeLevel,e,za)}upgradeLevelsBatch(e){return this.send($n.UpgradeLevelsBatch,e,Yh)}};var Yn=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(It.Purchase,e,So)}purchaseBatch(e){return this.send(It.PurchaseBatch,e,tu)}getDefinitions(e){return this.send(It.GetDefinitions,e,gs)}getUserState(e){return this.send(It.GetUserState,e,iu)}getStorefront(e){return this.send(It.GetStorefront,e,ys)}getCreditsConfirmation(e){return this.send(It.GetCreditsConfirmation,e,Co)}getCreditsBalance(e){return this.send(It.GetCreditsBalance,e,eu)}};var Kb={Apple:"Apple",Google:"Google"},Xn=z.object({PremiumID:z.string().nullish(),PurchaseDate:z.string().nullish(),ExpirationDate:z.string().nullish(),TransactionID:z.string().nullish(),IsAutoRenewEnabled:z.boolean().nullish()}).passthrough(),er=z.object({Subscriptions:z.record(z.string(),Xn).nullish(),ActivatedTrialIDs:z.array(z.string()).nullish(),MaxActiveTier:z.number().nullish()}).passthrough().transform(o=>o),Hb=z.object({PremiumID:z.string().nullish(),DisplayName:z.string().nullish(),Tier:z.number().nullish(),DurationDays:z.number().nullish(),TrialDurationDays:z.number().nullish(),PriceOptions:ue.nullish(),Benefits:z.record(z.string(),z.string()).nullish()}).passthrough(),wa=z.object({Definitions:z.record(z.string(),Hb).nullish()}).passthrough(),Xh=z.object({Premium:wa.nullish()}),ed=z.object({ServerTimeUtc:c.nullish(),Premium:er.nullish()}),tr=z.object({ServerTimeUtc:c.nullish(),Premium:er.nullish(),Subscription:Xn.nullish(),Resources:M.nullish()}),$t={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var $b={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},Jb=z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),td=z.object({StartUtc:c.nullish(),EndUtc:c.nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Ma=z.object({ResourceAction:z.string().nullish(),RevokeEntitlement:z.boolean().nullish(),BlockFuturePurchases:z.boolean().nullish()}).passthrough(),Zb=z.object({PremiumID:z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:z.number().nullish(),RevokeOnRefund:z.boolean().nullish()}).passthrough(),Yb=z.object({Rewards:Q.nullish(),Rules:Q.nullish(),Refund:Q.nullish()}).passthrough(),Xb=z.object({ProductID:z.string().nullish(),Name:z.string().nullish(),Type:Jb.nullish(),Enabled:z.boolean().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:z.number().nullish(),TelegramStarsPrice:z.number().nullish(),Rules:td.nullish(),Refund:Ma.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Subscription:Zb.nullish(),Presets:Yb.nullish()}).passthrough(),eD=z.object({StoreID:z.string().nullish(),Enabled:z.boolean().nullish(),PackageName:z.string().nullish(),VerificationMode:z.string().nullish(),PlayPublicKey:z.string().nullish(),RequireCertificateChain:z.boolean().nullish(),SecretName:z.string().nullish(),IssuerID:z.string().nullish(),KeyID:z.string().nullish(),AcknowledgePurchases:z.boolean().nullish(),NotificationPackageName:z.string().nullish()}).passthrough(),tD=z.object({Rewards:H.nullish()}).passthrough(),iD=z.object({Rules:td.nullish()}).passthrough(),sD=z.object({Refund:Ma.nullish()}).passthrough(),nD=z.object({Rewards:z.record(z.string(),tD).nullish(),Rules:z.record(z.string(),iD).nullish(),Refund:z.record(z.string(),sD).nullish()}).passthrough(),rD=z.object({MaxPurchaseAgeDays:z.number().nullish(),AllowSandbox:z.boolean().nullish(),RequirePackageMatch:z.boolean().nullish(),MaxReceiptsPerBatch:z.number().nullish(),RefundCheckHorizonDays:z.number().nullish(),RejectCrossUserReceipts:z.boolean().nullish()}).passthrough(),oD=z.object({Enabled:z.boolean().nullish(),Products:z.record(z.string(),Xb).nullish(),Stores:z.record(z.string(),eD).nullish(),Presets:nD.nullish(),Validation:rD.nullish(),Refund:Ma.nullish()}).passthrough(),id=z.object({ProductID:z.string().nullish(),TotalPurchases:z.number().nullish(),DailyPurchases:z.number().nullish(),DailyResetUtc:c.nullish(),LastPurchasedAt:c.nullish(),Owned:z.boolean().nullish(),Refunded:z.boolean().nullish(),PurchaseBlocked:z.boolean().nullish(),Store:z.string().nullish(),LastTransactionID:z.string().nullish()}).passthrough(),sd=z.object({ProductID:z.string().nullish(),PremiumID:z.string().nullish(),Store:z.string().nullish(),OriginalTransactionID:z.string().nullish(),LastTransactionID:z.string().nullish(),ExpiresAt:c.nullish(),AutoRenew:z.boolean().nullish(),Status:z.string().nullish(),RenewalCount:z.number().nullish(),LastStoreCheckAt:c.nullish(),LastStoreCheckError:z.string().nullish(),UpdatedAt:c.nullish()}).passthrough(),aD=z.object({Products:z.record(z.string(),id).nullish(),LifetimeSpendUsdCents:z.number().nullish(),Subscriptions:z.record(z.string(),sd).nullish(),LastRefundCheckAt:c.nullish(),TotalPurchases:z.number().nullish(),FirstPurchaseAt:c.nullish(),LastPurchaseAt:c.nullish()}).passthrough(),lD=z.object({ProductID:z.string(),Available:z.boolean(),Owned:z.boolean(),Blocked:z.boolean(),Reason:z.string().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish()}).passthrough(),nd=z.object({ServerTimeUtc:c,Purchase:oD.nullish(),Availability:z.array(lD).nullish()}),rd=z.object({ServerTimeUtc:c,Purchase:aD.nullish()}),uD={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},cD=z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Oa=z.object({ServerTimeUtc:c,Store:Ni.nullish(),ProductID:z.string().nullish(),TransactionID:z.string().nullish(),Status:cD.nullish(),Granted:z.boolean().nullish(),Quantity:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish(),ProductState:id.nullish(),Premium:er.nullish(),Subscription:Xn.nullish(),SubscriptionMirror:sd.nullish()}).passthrough(),od=z.object({ServerTimeUtc:c,ProductID:z.string().nullish(),Stars:z.number().nullish(),InvoiceLink:z.string(),ExpiresAt:c.nullish()}).passthrough(),ad=gt(Oa),Jt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var ir=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(Jt.GetDefinitions,e,nd)}getUserState(e){return this.send(Jt.GetUserState,e,rd)}validatePurchase(e){return this.send(Jt.ValidatePurchase,e,Oa)}validatePurchasesBatch(e){return this.send(Jt.ValidatePurchasesBatch,e,ad)}createTelegramInvoice(e){return this.send(Jt.CreateTelegramInvoice,e,od)}};var pD=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),ld=z.object({Reward:H.nullish(),Weight:z.number().nullish(),AmountRange:pD.nullish()}).passthrough(),fi=z.object({SlotID:z.string().nullish(),MinRolls:z.number().nullish(),MaxRolls:z.number().nullish(),Pool:z.array(ld).nullish()}).passthrough(),gi=z.object({RuleID:z.string().nullish(),Threshold:z.number().nullish(),Pool:z.array(ld).nullish()}).passthrough(),hD=z.object({RewardSlots:z.array(fi).nullish()}).passthrough(),dD=z.object({PityRules:z.array(gi).nullish()}).passthrough(),sr=z.object({SlotPresets:z.record(z.string(),hD).nullish(),PityPresets:z.record(z.string(),dD).nullish()}).passthrough();var mD=z.object({RuleID:z.string(),BoxIndex:z.number().nullish()}),ud=z.object({ServerTimeUtc:c,LootboxID:z.string(),OpenedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish(),Results:z.array(M).nullish(),TriggeredPity:z.array(mD).nullish()}),fD=z.object({RewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),gD=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxDrops:j.nullish()}).passthrough(),yD=z.object({LootboxID:z.string(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:ue.nullish(),RewardSlots:z.array(fi).nullish(),PityRules:z.array(gi).nullish(),Presets:fD.nullish(),RewardMultiplier:ji.nullish(),SupplyLimits:z.array(gD).nullish(),MaxOpenCount:z.number().nullish()}).passthrough(),RD=z.object({MaxOpenCount:z.number().nullish()}).passthrough(),Ea=z.object({Definitions:z.record(z.string(),yD).nullish(),RewardPools:sr.nullish(),Settings:RD.nullish()}).passthrough(),cd=z.object({LootboxDefinitions:Ea.nullish()}),nr={GetDefinitions:"GetDefinitions",Open:"Open"};var rr=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(nr.GetDefinitions,e,cd)}open(e){return this.send(nr.Open,e,ud)}};var CD=z.object({}).passthrough().transform(o=>o),SD=z.object({}).passthrough().transform(o=>o),xD=z.object({}).passthrough().transform(o=>o),bD=z.object({}).passthrough().transform(o=>o),DD=z.object({}).passthrough().transform(o=>o),pd=z.object({ServerTimeUtc:c,CalendarID:z.string(),DayNumber:z.number().nullish(),DailyState:CD,Resources:M.nullish(),Inventory:K.nullish()}),hd=z.object({ServerTimeUtc:c,AccrualID:z.string(),AccruedSeconds:j.nullish(),AppliedRatePerSecond:z.number().nullish(),IdleState:SD,Resources:M.nullish(),Inventory:K.nullish()}),dd=z.object({ServerTimeUtc:c,ComebackID:z.string(),ClaimedTierIndex:z.number().nullish(),ComebackState:xD,Resources:M.nullish(),Inventory:K.nullish()}),md=z.object({ServerTimeUtc:c,ClaimID:z.string(),ClaimState:bD,Resources:M.nullish(),Inventory:K.nullish()}),fd=z.object({Enabled:z.boolean(),Multiplier:z.number().nullish(),Progress:j.nullish(),Source:z.string().nullish(),SourceKey:z.string().nullish()}),PD=z.object({RewardMode:z.string().nullish(),RewardStackLowerTiers:z.boolean().nullish()}).passthrough(),ID=z.object({DayNumber:z.number().nullish(),Rewards:H.nullish(),IsMilestone:z.boolean().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Ui=z.object({Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Ua=z.object({Availability:Q.nullish()}).passthrough(),vD=z.object({Availability:z.record(z.string(),Ui).nullish()}).passthrough(),TD=z.object({CalendarID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Days:z.array(ID).nullish(),IsLooping:z.boolean().nullish(),MissBehavior:z.string().nullish(),ResetByDays:z.number().nullish(),MissThresholdMultiplier:z.number().nullish(),ClaimMode:z.string().nullish(),ClaimCooldownSeconds:z.number().nullish(),Availability:Ui.nullish(),Presets:Ua.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),AD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Multiplier:z.number().nullish()}).passthrough(),kD=z.object({BaseRatePerSecond:z.number().nullish(),PowerCoefficient:z.number().nullish(),BoardRankCoefficient:z.number().nullish(),EquipmentBonusEnabled:z.boolean().nullish(),EquipmentCharacterID:z.string().nullish(),PremiumMultipliers:z.array(AD).nullish()}).passthrough(),zD=z.object({MinCharacterLevel:z.number().nullish(),RequirementsCharacterID:z.string().nullish(),Availability:Ui.nullish(),RequiredItemIDs:z.array(z.string()).nullish(),RequiredEquippedItemIDs:z.array(z.string()).nullish()}).passthrough(),wD=z.object({AccrualID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rate:kD.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:z.number().nullish(),MinClaimSeconds:z.number().nullish(),Requirements:zD.nullish(),FirstClaimMode:z.string().nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),MD=z.object({MinAbsenceSeconds:z.number().nullish(),Rewards:H.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),OD=z.object({ComebackID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(MD).nullish(),ClaimCooldownSeconds:z.number().nullish(),ClaimWindowSeconds:z.number().nullish(),TrackPresenceOnRead:z.boolean().nullish(),Availability:Ui.nullish(),Presets:Ua.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),ED=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),CooldownSeconds:z.number().nullish(),MaxClaimsPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish(),TotalClaimLimit:z.number().nullish()}).passthrough(),UD=z.object({ClaimID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Mode:z.string().nullish(),Rewards:H.nullish(),PremiumLimitOverrides:z.array(ED).nullish(),Availability:Ui.nullish(),Presets:Ua.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),qa=z.object({TierRewards:PD.nullish(),MilestoneRewardMultiplier:ji.nullish(),DailyCalendars:z.record(z.string(),TD).nullish(),IdleAccruals:z.record(z.string(),wD).nullish(),Comebacks:z.record(z.string(),OD).nullish(),Claims:z.record(z.string(),UD).nullish(),Presets:vD.nullish()}).passthrough(),gd=z.object({RewardDefinitions:qa.nullish()}),yd=z.object({Rewards:DD.nullish()}),zt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var or=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(zt.GetRewardDefinitions,e,gd)}getUserRewardsState(e){return this.send(zt.GetUserRewardsState,e,yd)}getMilestoneRewardMultiplier(e){return this.send(zt.GetMilestoneRewardMultiplier,e,fd)}claimDailyReward(e){return this.send(zt.ClaimDailyReward,e,pd)}collectIdleAccrual(e){return this.send(zt.CollectIdleAccrual,e,hd)}claimComebackReward(e){return this.send(zt.ClaimComebackReward,e,dd)}claimReward(e){return this.send(zt.ClaimReward,e,md)}};var ar=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(rt.GetTutorialDefinitions,e,El)}getUserTutorialState(e){return this.send(rt.GetUserTutorialState,e,Ki)}startFlow(e){return this.send(rt.StartFlow,e,Mt)}reportStepShown(e){return this.send(rt.ReportStepShown,e,Mt)}completeStep(e){return this.send(rt.CompleteStep,e,Mt)}completeStepsBatch(e){return this.send(rt.CompleteStepsBatch,e,Bl)}skipStep(e){return this.send(rt.SkipStep,e,Mt)}skipFlow(e){return this.send(rt.SkipFlow,e,Mt)}claimFlowReward(e){return this.send(rt.ClaimFlowReward,e,ql)}resetFlow(e){return this.send(rt.ResetFlow,e,Mt)}};var qD={Open:"Open",Application:"Application"},BD=z.enum(["Open","Application"]).catch("Open"),LD={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Rd=z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),GD={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Ba=z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),FD={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var Zt={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},VD=z.object({CampaignID:z.string().nullish(),DisplayNameKey:z.string().nullish(),DescriptionKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),IsRunning:z.boolean().nullish()}).passthrough(),Cd=z.object({IsEnabled:z.boolean().nullish(),CreatorPortalUrl:z.string().nullish(),ParticipationMode:BD.nullish(),IsCreator:z.boolean().nullish(),CreatorStatus:Rd.nullish(),VerificationCode:z.string().nullish(),TeamID:z.string().nullish(),Campaigns:z.array(VD).nullish()}).passthrough(),ND=z.object({Earned:z.number().nullish(),Mature:z.number().nullish(),CountedMetrics:z.record(z.string(),z.number()).nullish(),ReachedMilestones:z.array(z.string()).nullish(),CappedBySubmissionLimit:z.boolean().nullish(),CappedByCreatorLimit:z.boolean().nullish(),NotPaidAsCopy:z.boolean().nullish()}).passthrough(),_D=z.object({CampaignID:z.string().nullish(),CurrencyKind:Ba.nullish(),CurrencyID:z.string().nullish(),NetworkID:z.string().nullish(),Earned:z.number().nullish(),Mature:z.number().nullish(),Granted:z.number().nullish(),Paid:z.number().nullish(),Overpaid:z.number().nullish(),Claimable:z.number().nullish(),BySubmission:z.record(z.string(),ND).nullish(),ComputedAt:z.string().nullish()}).passthrough(),jD=z.object({PayoutID:z.string().nullish(),CampaignID:z.string().nullish(),Amount:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Ba.nullish(),NetworkID:z.string().nullish(),PaidAt:z.string().nullish()}).passthrough(),Sd=z.object({ServerTimeUtc:z.string().nullish(),HoldDays:z.number().nullish(),Campaigns:z.array(_D).nullish(),Payouts:z.array(jD).nullish()}).passthrough(),xd=z.object({CampaignID:z.string().nullish(),PayoutID:z.string().nullish(),Claimed:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Ba.nullish(),NetworkID:z.string().nullish(),RemainingFraction:z.number().nullish(),IdempotentReplay:z.boolean().nullish(),Message:z.string().nullish()}).passthrough(),WD=z.object({To:z.string().nullish(),Amount:z.string().nullish()}).passthrough(),QD=z.object({ContractAddress:z.string().nullish(),TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),Signature:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(WD).nullish()}).passthrough(),KD=z.object({Kind:z.string().nullish(),Target:z.string().nullish(),Required:z.number().nullish(),Actual:z.number().nullish(),Passed:z.boolean().nullish()}).passthrough(),bd=z.object({Passed:z.boolean().nullish(),Approved:z.boolean().nullish(),Status:Rd.nullish(),WalletMissing:z.boolean().nullish(),WalletConnectAllowed:z.boolean().nullish(),Conditions:z.array(KD).nullish()}).passthrough(),HD=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),$D=z.object({ProgramID:z.string().nullish(),Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(HD).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),Dd=z.object({ServerTimeUtc:z.string().nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ChainID:z.number().nullish(),CurrencyID:z.string().nullish(),AmountNative:z.number().nullish(),NetAmountNative:z.number().nullish(),BurnAmountNative:z.number().nullish(),AmountUsd:z.number().nullish(),ExpiresAt:z.string().nullish(),EvmSignature:QD.nullish(),SolanaSignature:$D.nullish(),StateDelta:di.nullish()}).passthrough();var lr=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(Zt.GetCommunityMarketingState,e,Cd)}getEarnings(e){return this.send(Zt.GetEarnings,e,Sd)}claim(e){return this.send(Zt.Claim,e,xd)}checkJoinEligibility(e){return this.send(Zt.CheckJoinEligibility,e,bd)}withdrawCryptoReward(e){return this.send(Zt.WithdrawCryptoReward,e,Dd)}};var ur=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(Ke.GetChatDefinitions,e,Ru)}getChannels(e){return this.send(Ke.GetChannels,e,Ts)}poll(e){return this.send(Ke.Poll,e,Cu)}getHistory(e){return this.send(Ke.GetHistory,e,Su)}getConversations(e){return this.send(Ke.GetConversations,e,Du)}sendMessage(e){return this.send(Ke.SendMessage,e,xu)}openDirectChannel(e){return this.send(Ke.OpenDirectChannel,e,bu)}markRead(e){return this.send(Ke.MarkRead,e,pi)}joinChannel(e){return this.send(Ke.JoinChannel,e,pi)}leaveChannel(e){return this.send(Ke.LeaveChannel,e,pi)}reportMessage(e){return this.send(Ke.ReportMessage,e,Pu)}ignoreUser(e){return this.send(Ke.IgnoreUser,e,pi)}unignoreUser(e){return this.send(Ke.UnignoreUser,e,pi)}};var cr=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(hi.GetPushConfig,e,Tu)}subscribePush(e){return this.send(hi.SubscribePush,e,Po)}unsubscribePush(e){return this.send(hi.UnsubscribePush,e,qe)}getPushSubscriptions(e){return this.send(hi.GetPushSubscriptions,e,Au)}};var pr=class extends B{constructor(e){super(e,"Localization");}send(e,t,i,s){let n=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${n}:${t.Locale}`:n,...s})}getLocalizationManifest(e){return this.send(Qn.GetLocalizationManifest,e,jh)}getLocalizationTable(e){return this.send(Qn.GetLocalizationTable,e,Wh)}};var hr=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(ht.GetQuestDefinitions,e,Qi)}getUserQuestState(e){return this.send(ht.GetUserQuestState,e,bl)}refreshQuestCycles(e){return this.send(ht.RefreshQuestCycles,e,qe)}claimQuestReward(e){return this.send(ht.ClaimQuestReward,e,oo)}claimQuestRewardsBatch(e){return this.send(ht.ClaimQuestRewardsBatch,e,Il)}claimMilestoneReward(e){return this.send(ht.ClaimMilestoneReward,e,ao)}claimMilestoneRewardsBatch(e){return this.send(ht.ClaimMilestoneRewardsBatch,e,vl)}claimGroupCompletionReward(e){return this.send(ht.ClaimGroupCompletionReward,e,Dl)}addQuestProgress(e){return this.send(ht.AddQuestProgress,e,Pl)}};var dr=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(at.GetActiveEvents,e,Es)}getDefinitions(e){return this.send(at.GetDefinitions,e,Os)}getUserLteState(e){return this.send(at.GetUserLteState,e,Mu)}grantTokens(e){return this.send(at.GrantTokens,e,M)}spendTokens(e){return this.send(at.SpendTokens,e,To)}claimMilestone(e){return this.send(at.ClaimMilestone,e,Ao)}claimMilestonesBatch(e){return this.send(at.ClaimMilestonesBatch,e,ko)}claimAllMilestones(e){return this.send(at.ClaimAllMilestones,e,ko)}spendTokensBatch(e){return this.send(at.SpendTokensBatch,e,Ou)}grantTokensBatch(e){return this.send(at.GrantTokensBatch,e,Eu)}};var mr=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ne.GetDefinitions,e,Vs)}getLeaderboard(e){return this.send(Ne.GetLeaderboard,e,vi)}getMyProgress(e){return this.send(Ne.GetMyProgress,e,qs)}submitScore(e){return this.send(Ne.SubmitScore,e,Bs)}submitScoreFromSource(e){return this.send(Ne.SubmitScoreFromSource,e,Bs)}claimCycleReward(e){return this.send(Ne.ClaimCycleReward,e,Ls)}claimMilestone(e){return this.send(Ne.ClaimMilestone,e,Gs)}getFriendsLeaderboard(e){return this.send(Ne.GetFriendsLeaderboard,e,vi)}getLeaderboardsBatch(e){return this.send(Ne.GetLeaderboardsBatch,e,Bu)}getProgressBatch(e){return this.send(Ne.GetProgressBatch,e,Fs)}claimCycleRewardsBatch(e){return this.send(Ne.ClaimCycleRewardsBatch,e,Lu)}claimMilestonesBatch(e){return this.send(Ne.ClaimMilestonesBatch,e,Gu)}submitScoresBatch(e){return this.send(Ne.SubmitScoresBatch,e,Fu)}claimAllRewardsBatch(e){return this.send(Ne.ClaimAllRewardsBatch,e,Vu)}getOverviewBatch(e){return this.send(Ne.GetOverviewBatch,e,Nu)}};var fr=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Ut.GetDefinitions,e,js)}getActiveSeason(e){return this.send(Ut.GetActiveSeason,e,_s)}getUserState(e){return this.send(Ut.GetUserState,e,zo)}grantStatusTokens(e){return this.send(Ut.GrantStatusTokens,e,Qu)}claimTierReward(e){return this.send(Ut.ClaimTierReward,e,wo)}claimTierRewardsBatch(e){return this.send(Ut.ClaimTierRewardsBatch,e,Ku)}};var gr=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send($t.GetDefinitions,e,Xh)}getUserState(e){return this.send($t.GetUserState,e,ed)}activateTrial(e){return this.send($t.ActivateTrial,e,tr)}purchaseItemOrCurrency(e){return this.send($t.PurchaseWithResources,e,tr)}purchaseRealMoney(e){return this.send($t.PurchaseRealMoney,e,tr)}};var yr=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(_e.GetCharacterDefinitions,e,Hs)}getUserCharacters(e){return this.send(_e.GetUserCharacters,e,Xu)}unlockCharacter(e){return this.send(_e.UnlockCharacter,e,Uo)}upgradeStatLevel(e){return this.send(_e.UpgradeStatLevel,e,Oo)}upgradeCharacterLevel(e){return this.send(_e.UpgradeCharacterLevel,e,Eo)}equipItems(e){return this.send(_e.EquipItems,e,ec)}unequipItems(e){return this.send(_e.UnequipItems,e,tc)}unequipAllCharacters(e){return this.send(_e.UnequipAllCharacters,e,ic)}unlockCharactersBatch(e){return this.send(_e.UnlockCharactersBatch,e,ac)}upgradeCharacterLevelsBatch(e){return this.send(_e.UpgradeCharacterLevelsBatch,e,lc)}upgradeStatLevelsBatch(e){return this.send(_e.UpgradeStatLevelsBatch,e,uc)}unlockSkin(e){return this.send(_e.UnlockSkin,e,sc)}equipSkin(e){return this.send(_e.EquipSkin,e,nc)}unequipSkin(e){return this.send(_e.UnequipSkin,e,rc)}getCharacterSkins(e){return this.send(_e.GetCharacterSkins,e,oc)}};var Rr=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(Ct.CreateMatch,e,Np)}updateMatch(e){return this.send(Ct.UpdateMatch,e,_p)}cancelMatch(e){return this.send(Ct.CancelMatch,e,jp)}instantBattle(e){return this.send(Ct.InstantBattle,e,Wp)}saveStrategy(e){return this.send(Ct.SaveStrategy,e,qe)}getMyMatches(e){return this.send(Ct.GetMyMatches,e,ca)}getAvailableMatches(e){return this.send(Ct.GetAvailableMatches,e,ca)}getDefinitions(e){return this.send(Ct.GetDefinitions,e,$p)}};var JD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Pd=z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),ZD={None:"None",Min:"Min",Average:"Average",Max:"Max"},YD=z.enum(["None","Min","Average","Max"]).catch("None"),XD={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},eP=z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),tP={Clamp:"Clamp",Reject:"Reject"},iP=z.enum(["Clamp","Reject"]).catch("Clamp"),sP=z.object({ItemInstanceID:z.string().nullish(),ItemID:z.string().nullish(),Level:z.number().nullish(),Units:z.number().nullish()}),nP=z.object({Index:z.number().nullish(),BurnedItemIDs:z.array(z.string()).nullish(),RolledCollectionID:z.string().nullish(),UsedCollections:z.record(z.string(),z.number()).nullish(),Output:so.nullish(),OutputLevel:z.number().nullish(),BurnedInstances:z.array(sP).nullish()}),Id=z.object({ServerTimeUtc:c,Type:Pd.nullish(),CraftID:z.string(),CraftedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),InputRarity:z.string().nullish(),OutputRarity:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish(),Results:z.array(nP).nullish()}),rP=z.object({CraftID:z.string().nullish(),Type:Pd.nullish(),CatalogID:z.string().nullish(),CollectionID:z.string().nullish(),InputRarityID:z.string().nullish(),OutputRarityID:z.string().nullish(),RequiredItemCount:z.number().nullish(),PriceOptions:ue.nullish(),OutputLevelMode:YD.nullish(),InputSelection:eP.nullish(),OutputLevelOverflow:iP.nullish()}).passthrough(),La=z.object({Definitions:z.record(z.string(),rP).nullish()}).passthrough(),vd=z.object({ServerTimeUtc:c.nullish(),CraftDefinitions:La.nullish()}),Cr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Sr=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Cr.GetDefinitions,e,vd)}craft(e){return this.send(Cr.Craft,e,Id)}};var oP=2e5,xr=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,Ys,{timeoutMs:oP,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Ys,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Fe.GetDefinitions,e,Rc)}generateText(e){return this.generate(Fe.GenerateText,e)}getText(e){return this.readGeneration(Fe.GetText,e)}generateImage(e){return this.generate(Fe.GenerateImage,e)}editImage(e){return this.generate(Fe.EditImage,e)}getImage(e){return this.readGeneration(Fe.GetImage,e)}generateVideo(e){return this.generate(Fe.GenerateVideo,e)}getVideo(e){return this.readGeneration(Fe.GetVideo,e)}generateAudio(e){return this.generate(Fe.GenerateAudio,e)}getAudio(e){return this.readGeneration(Fe.GetAudio,e)}generateMusic(e){return this.generate(Fe.GenerateMusic,e)}getMusic(e){return this.readGeneration(Fe.GetMusic,e)}generateThreeD(e){return this.generate(Fe.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Fe.GetThreeD,e)}listGenerations(e){return this.send(Fe.ListGenerations,e,yc)}getGeneration(e){return this.readGeneration(Fe.GetGeneration,e)}};var aP={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},lP=z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),Td=z.object({}).passthrough().transform(o=>o),yi=z.object({CollectibleID:z.string(),Rarity:z.number().nullish(),IsSpecial:z.boolean().nullish(),IsDuplicate:z.boolean().nullish(),CollectionCurrencyConverted:z.number().nullish()}),Ad=z.object({GrantedCollectibles:z.array(yi).nullish(),DuplicateCollectibles:z.array(yi).nullish(),CollectionCurrencyEarned:j.nullish()}),kd=z.object({OpenedCount:z.number().nullish(),Packs:z.array(Ad).nullish(),GrantedCollectibles:z.array(yi).nullish(),DuplicateCollectibles:z.array(yi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),NewlyCompletedSetIDs:z.array(z.string()).nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),zd=z.object({OpenedCount:z.number().nullish(),Chests:z.array(Ad).nullish(),GrantedCollectibles:z.array(yi).nullish(),DuplicateCollectibles:z.array(yi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),wd=z.object({GrantedCollectibleID:z.string().nullish(),NewlyCompletedSetID:z.string().nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Ga=z.object({SetID:z.string(),Resources:M.nullish(),Inventory:K.nullish()}),Md=z.array(Ie(Ga)),Od=z.object({Resources:M.nullish(),Inventory:K.nullish()}),uP=z.object({OfferID:z.string(),TitleID:z.string().nullish(),CollectionID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderPublicData:Ee.nullish(),OfferedCollectibleID:z.string().nullish(),OfferedCollectibleIsSpecial:z.boolean().nullish(),ReceiverUserID:z.string().nullish(),RequestedCollectibleID:z.string().nullish(),RequestedCollectibleIsSpecial:z.boolean().nullish(),Status:lP.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RespondedAtUtc:c.nullish(),DeclineReason:z.string().nullish(),IsSpecialTradeEvent:z.boolean().nullish(),SpecialTradeEventID:z.string().nullish()}).passthrough(),Ed=z.object({OfferID:z.string(),ExpiresAtUtc:c.nullish(),Resources:M.nullish()}),Ud=z.object({OfferID:z.string(),Resources:M.nullish()}),qd=z.object({OfferID:z.string(),ReceivedCollectibleID:z.string().nullish(),ReceivedIsSpecial:z.boolean().nullish(),SentCollectibleID:z.string().nullish(),SentCollectibleIsSpecial:z.boolean().nullish(),Transfer:z.unknown().nullish()}),Bd=z.object({OfferID:z.string(),Resources:M.nullish()}),Fa=z.object({Offers:z.array(uP).nullish()}),cP=z.object({CollectibleID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rarity:z.number().nullish(),HasSpecialVersion:z.boolean().nullish(),SortOrder:z.number().nullish()}).passthrough(),pP=z.object({SetID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SortOrder:z.number().nullish(),Collectibles:z.array(cP).nullish(),SetCompletionReward:H.nullish()}).passthrough(),hP=z.object({CollectionID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SeasonChainID:z.string().nullish(),Sets:z.array(pP).nullish(),GrandPrize:H.nullish()}).passthrough(),Ld=z.object({BonusRewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),dP=z.object({PackTypeID:z.string().nullish(),PriceOptions:ue.nullish(),BonusRewardSlots:z.array(fi).nullish(),PityRules:z.array(gi).nullish(),Presets:Ld.nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectibleCount:z.number().nullish(),MaxOpenCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),GuaranteeMaxRarity:z.boolean().nullish(),RarityWeights:z.record(z.string(),z.number()).nullish(),ColorTier:z.number().nullish()}).passthrough(),mP=z.object({Rarity:z.number().nullish(),CollectionCurrencyGranted:z.number().nullish()}).passthrough(),fP=z.object({CollectionChestID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectionCurrencyCost:z.number().nullish(),MaxOpenCount:z.number().nullish(),MinCollectibleCount:z.number().nullish(),MaxCollectibleCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),BonusRewardSlots:z.array(fi).nullish(),PityRules:z.array(gi).nullish(),Presets:Ld.nullish(),Tier:z.number().nullish()}).passthrough(),gP=z.object({SpecialTradeEventID:z.string().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),AllowedSpecialCollectibleIDs:z.array(z.string()).nullish(),SpecialTradeEventDailyTradeLimit:z.number().nullish()}).passthrough(),yP=z.object({MaxPackOpenCount:z.number().nullish(),MaxChestOpenCount:z.number().nullish()}).passthrough(),br=z.object({Collections:z.record(z.string(),hP).nullish(),PackTypes:z.record(z.string(),dP).nullish(),CollectionChests:z.array(fP).nullish(),DuplicateConversions:z.array(mP).nullish(),DailyTradeLimit:z.number().nullish(),CollectibleJokerCatalogID:z.string().nullish(),CollectibleJokerItemID:z.string().nullish(),SpecialTradeEvents:z.array(gP).nullish(),RewardPools:sr.nullish(),Settings:yP.nullish()}).passthrough(),je={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 Dr=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(je.GetDefinitions,e,br)}getUserState(e){return this.send(je.GetUserState,e,Td)}openPack(e){return this.send(je.OpenPack,e,kd)}openCollectionChest(e){return this.send(je.OpenCollectionChest,e,zd)}useCollectibleJoker(e){return this.send(je.UseCollectibleJoker,e,wd)}claimSetReward(e){return this.send(je.ClaimSetReward,e,Ga)}claimSetRewardsBatch(e){return this.send(je.ClaimSetRewardsBatch,e,Md)}claimGrandPrize(e){return this.send(je.ClaimGrandPrize,e,Od)}sendTradeOffer(e){return this.send(je.SendTradeOffer,e,Ed)}cancelTradeOffer(e){return this.send(je.CancelTradeOffer,e,Ud)}acceptTradeOffer(e){return this.send(je.AcceptTradeOffer,e,qd)}declineTradeOffer(e){return this.send(je.DeclineTradeOffer,e,Bd)}getMyTradeOffers(e){return this.send(je.GetMyTradeOffers,e,Fa)}getIncomingTradeOffers(e){return this.send(je.GetIncomingTradeOffers,e,Fa)}};var Pr=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(dt.GetDefinitions,e,sn)}getActiveEvent(e){return this.send(dt.GetActiveEvent,e,xc)}getUserState(e){return this.send(dt.GetUserState,e,tn)}getGroupState(e){return this.send(dt.GetGroupState,e,Vo)}joinOrCreateGroup(e){return this.send(dt.JoinOrCreateGroup,e,Vo)}spin(e){return this.send(dt.Spin,e,Dc)}claimObjectReward(e){return this.send(dt.ClaimObjectReward,e,No)}claimGrandPrize(e){return this.send(dt.ClaimGrandPrize,e,No)}leaveGroup(e){return this.send(dt.LeaveGroup,e,Pc)}};var Ir=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(Rt.GetDefinition,e,Uc)}getUserState(e){return this.send(Rt.GetUserState,e,qc)}getActiveDeals(e){return this.send(Rt.GetActiveDeals,e,on)}dismissDeal(e){return this.send(Rt.DismissDeal,e,Lc)}executeNode(e){return this.send(Rt.ExecuteNode,e,Bc)}recordShow(e){return this.send(Rt.RecordShow,e,Gc)}claimMilestone(e){return this.send(Rt.ClaimMilestone,e,Fc)}claimMilestonesBatch(e){return this.send(Rt.ClaimMilestonesBatch,e,Vc)}};var RP=z.object({}).passthrough().transform(o=>o),CP=z.object({FeatureKey:z.string().nullish(),IsEnabled:z.boolean().nullish(),Rate:z.number().nullish(),Basis:z.string().nullish(),SourceCurrencyID:z.string().nullish(),TargetCurrencyID:z.string().nullish(),MinSourceAmount:z.number().nullish(),MaxRewardPerOperation:z.number().nullish(),Limits:Re.nullish()}).passthrough(),Va=z.object({IsEnabled:z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:z.record(z.string(),Le).nullish(),SpendRewards:z.array(CP).nullish(),Qualification:z.object({}).passthrough().transform(o=>o).nullish()}).passthrough(),Na=z.object({Pending:z.boolean().nullish(),Qualified:z.boolean().nullish(),Groups:z.array(z.object({GroupID:z.string().nullish(),Met:z.boolean().nullish(),Conditions:z.array(z.object({Type:z.string().nullish(),Met:z.boolean().nullish(),Current:z.number().nullish(),Required:z.number().nullish()}).passthrough()).nullish()}).passthrough()).nullish()}).passthrough(),Gd=z.object({ReferralDefinitions:Va.nullish()}).passthrough(),Fd=z.object({Referral:RP.nullish(),InviteUrl:z.string().nullish(),Qualification:Na.nullish()}).passthrough(),Vd=z.object({QualificationPending:z.boolean().nullish(),Qualification:Na.nullish()}).passthrough(),Nd=z.object({ReferralCode:z.string().nullish(),ReferrerUserID:z.string().nullish(),IsFirstActivation:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),QualificationPending:z.boolean().nullish(),Qualification:Na.nullish()}).passthrough(),_a=z.object({RewardID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}).passthrough(),_d=gt(_a),Nt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var vr=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Nt.GetDefinitions,e,Gd)}getUserState(e){return this.send(Nt.GetUserState,e,Fd)}activateReferralCode(e){return this.send(Nt.ActivateReferralCode,e,Nd)}claimInviteReward(e){return this.send(Nt.ClaimInviteReward,e,_a)}claimInviteRewardsBatch(e){return this.send(Nt.ClaimInviteRewardsBatch,e,_d)}checkQualification(e){return this.send(Nt.CheckQualification,e,Vd)}};var Tr=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(tt.GetDefinitions,e,Qc)}getMessages(e){return this.send(tt.GetMessages,e,Kc)}getUnreadCount(e){return this.send(tt.GetUnreadCount,e,un)}readMessages(e){return this.send(tt.ReadMessages,e,Wo)}claimReward(e){return this.send(tt.ClaimReward,e,cn)}claimRewardsBatch(e){return this.send(tt.ClaimRewardsBatch,e,cn)}claimAll(e){return this.send(tt.ClaimAll,e,cn)}deleteMessages(e){return this.send(tt.DeleteMessages,e,Wo)}sendGift(e){return this.send(tt.SendGift,e,Hc)}sendTransfer(e){return this.send(tt.SendTransfer,e,$c)}getGiftStatus(e){return this.send(tt.GetGiftStatus,e,Jc)}};var Ar=class extends B{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(hn.RequestAdPermit,e,Zc)}completeView(e){return this.send(hn.CompleteView,e,Yc)}};var kr=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Ce.GetFriendsList,e,Ai)}getIncomingRequests(e){return this.send(Ce.GetIncomingRequests,e,Ai)}getOutgoingRequests(e){return this.send(Ce.GetOutgoingRequests,e,Ai)}getRecommendedFriends(e){return this.send(Ce.GetRecommendedFriends,e,Ai)}sendFriendRequest(e){return this.send(Ce.SendFriendRequest,e,ki)}acceptFriendRequest(e){return this.send(Ce.AcceptFriendRequest,e,ki)}declineFriendRequest(e){return this.send(Ce.DeclineFriendRequest,e,ki)}removeFriend(e){return this.send(Ce.RemoveFriend,e,ki)}getInbox(e){return this.send(Ce.GetInbox,e,ep)}markInboxSeen(e){return this.send(Ce.MarkInboxSeen,e,zi)}getInboxUnread(e){return this.send(Ce.GetInboxUnread,e,zi)}follow(e){return this.send(Ce.Follow,e,Lt)}unfollow(e){return this.send(Ce.Unfollow,e,Lt)}getFollowers(e){return this.send(Ce.GetFollowers,e,fn)}getFollowing(e){return this.send(Ce.GetFollowing,e,fn)}block(e){return this.send(Ce.Block,e,Lt)}unblock(e){return this.send(Ce.Unblock,e,Lt)}getBlocked(e){return this.send(Ce.GetBlocked,e,fn)}react(e){return this.send(Ce.React,e,Lt)}unreact(e){return this.send(Ce.Unreact,e,Lt)}getMyReactions(e){return this.send(Ce.GetMyReactions,e,ip)}getEntityStates(e){return this.send(Ce.GetEntityStates,e,tp)}addComment(e){return this.send(Ce.AddComment,e,gn)}editComment(e){return this.send(Ce.EditComment,e,gn)}deleteComment(e){return this.send(Ce.DeleteComment,e,np)}getComments(e){return this.send(Ce.GetComments,e,sp)}report(e){return this.send(Ce.Report,e,rp)}};var SP={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Yt=z.object({Target:z.string().nullish(),Operation:z.string().nullish(),Value:z.number().nullish()}).passthrough(),xP=z.object({BoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:ue.nullish(),Effect:Yt.nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),zr=z.object({Schedule:fe.nullish(),Gate:Z.nullish()}).passthrough(),ja=z.object({Availability:Q.nullish(),Effects:Q.nullish()}).passthrough(),bP=z.object({ScheduledBoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Effects:z.array(Yt).nullish(),Availability:zr.nullish(),Presets:ja.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),DP=z.object({ChainedBoostID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Effects:z.array(Yt).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),PP=z.object({ChainID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Phases:z.array(DP).nullish(),Availability:zr.nullish(),Presets:ja.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),IP=z.object({TriggeredBoostID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Sources:z.array(nt).nullish(),Effects:z.array(Yt).nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Availability:zr.nullish(),Presets:ja.nullish()}).passthrough(),vP=z.object({MaxAddPercent:z.number().nullish(),MaxMultiply:z.number().nullish(),MaxAddFlat:z.number().nullish()}).passthrough(),TP=z.object({Effects:z.array(Yt).nullish()}).passthrough(),AP=z.object({Availability:z.record(z.string(),zr).nullish(),Effects:z.record(z.string(),TP).nullish()}).passthrough(),kP=z.object({StackingCaps:z.record(z.string(),vP).nullish()}).passthrough(),wr=z.object({Definitions:z.record(z.string(),xP).nullish(),ScheduledBoosts:z.record(z.string(),bP).nullish(),BoostChains:z.record(z.string(),PP).nullish(),TriggeredBoosts:z.record(z.string(),IP).nullish(),Settings:kP.nullish(),Presets:AP.nullish()}).passthrough(),jd=z.object({InstanceID:z.string(),BoostID:z.string(),ActivatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RemainingCharges:z.number().nullish(),EffectSnapshot:Yt.nullish(),SourceType:z.string().nullish(),SourceRef:z.string().nullish()}).passthrough();z.object({Date:c.nullish(),DailyCount:z.number().nullish(),LastFiredUtc:c.nullish()}).passthrough();var Wd=z.object({ServerTimeUtc:c.nullish(),Active:z.record(z.string(),jd).nullish()}),Qd=z.object({ServerTimeUtc:c.nullish(),BoostID:z.string().nullish(),StackingPolicy:z.string().nullish(),ActivatedBoost:jd.nullish(),Resources:M.nullish()}),zP={Scheduled:"Scheduled",Chain:"Chain"},wP=z.object({Kind:z.string().nullish(),SourceID:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),PhaseOrder:z.number().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),Effects:z.array(Yt).nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Kd=z.object({ServerTimeUtc:c.nullish(),Windows:z.array(wP).nullish()}),Xt={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Mr=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(Xt.GetDefinitions,e,wr)}getActive(e){return this.send(Xt.GetActive,e,Wd)}getActiveWindows(e){return this.send(Xt.GetActiveWindows,e,Kd)}activate(e){return this.send(Xt.Activate,e,Qd)}cleanupExpired(e){return this.send(Xt.CleanupExpired,e,qe)}};var Or=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(mt.GetUserCustomDataDefinitions,e,Sn)}getMyUserCustomData(e){return this.send(mt.GetMyUserCustomData,e,up)}getPublicUserCustomDataOf(e){return this.send(mt.GetPublicUserCustomDataOf,e,Xo)}setPrivateData(e){return this.send(mt.SetPrivateData,e,ea)}setPublicData(e){return this.send(mt.SetPublicData,e,ea)}deleteKey(e){return this.send(mt.DeleteKey,e,qe)}batchSet(e){return this.send(mt.BatchSet,e,cp)}batchDelete(e){return this.send(mt.BatchDelete,e,pp)}batchGetPublicUserCustomDataOf(e){return this.send(mt.BatchGetPublicUserCustomDataOf,e,hp)}};var MP={Static:"Static",Runtime:"Runtime"},OP={Public:"Public",Private:"Private"},EP=z.enum(["Client","Server","System"]).catch("Client"),UP=z.enum(["String","Int","Bool","Json"]).catch("String"),qP=z.object({Value:z.string().nullish(),UpdatedAt:c.nullish(),Version:z.number().nullish(),LastWriter:EP.nullish(),ExpiresAt:c.nullish()}).passthrough(),Hd=z.record(z.string(),qP),Wa=z.object({StaticVersion:z.number().nullish(),RuntimeVersion:z.number().nullish(),Static:Hd.nullish(),Runtime:Hd.nullish(),NotModified:z.boolean().nullish()}),BP=z.object({KeyID:z.string(),Scope:z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:UP.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),Er=z.object({Keys:z.record(z.string(),BP).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),qi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Ur=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(qi.GetTitleCustomDataDefinitions,e,Er)}getPublicTitleData(e){return this.send(qi.GetPublicTitleData,e,Wa)}getPublicTitleDataKeys(e){return this.send(qi.GetPublicTitleDataKeys,e,Wa)}};var LP={Fast:"Fast",Sequential:"Sequential"},GP={Instant:"Instant",Timed:"Timed"};var FP={Hit:"Hit",Blocked:"Blocked"},VP=z.object({SlotIndex:z.number(),Level:z.number().nullish(),IsDamaged:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish()}).passthrough(),NP=z.object({Symbol:z.union([z.string(),z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:z.string().nullish()}).passthrough();z.object({ElapsedSeconds:z.number().nullish(),Reward:H.nullish()}).passthrough();var _P=z.object({RequiredValue:z.number().nullish(),Reward:H.nullish()}).passthrough(),jP=z.object({Reward:H.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough();z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(_P).nullish(),Rate:jP.nullish()}).passthrough();z.object({PlayedCount:z.number().nullish(),RewardsClaimedCount:z.number().nullish(),InstantClaimsCount:z.number().nullish(),EarlyClaimsCount:z.number().nullish(),LateClaimsCount:z.number().nullish(),AdViewsTotal:z.number().nullish(),StatRewardClaimsCount:z.number().nullish(),StatReportsClampedCount:z.number().nullish(),StatReportsUnknownMetricCount:z.number().nullish()}).passthrough();var $d=z.object({}).passthrough().transform(o=>o),Jd=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),We=z.object({Operation:M.nullish(),ScaleWithRollMultiplier:z.boolean().nullish()}).passthrough(),WP=z.object({Count:z.number().nullish(),Sides:z.number().nullish()}).passthrough(),QP=z.object({ShieldChance:z.number().nullish(),DamagedBuildingChance:z.number().nullish(),RankMultiplierMin:z.number().nullish(),RankMultiplierMax:z.number().nullish(),RankOffsetMin:z.number().nullish(),RankOffsetMax:z.number().nullish(),StageLevelSpread:z.number().nullish()}).passthrough(),KP=z.object({CostMatrixTemplatesByID:z.record(z.string(),z.array(z.array(z.number()))).nullish(),PerBoardGrowth:z.number().nullish(),VisualTemplateCycle:z.array(z.string()).nullish(),EconomyScaledResources:ce.nullish(),ScaleRaidStealWithEconomy:z.boolean().nullish(),ScaleAttackRewardWithEconomy:z.boolean().nullish(),AttackValueFromCostMatrix:z.boolean().nullish(),AttackBlockedRewardFactor:z.number().nullish(),ScaleVictimLossWithEconomy:z.boolean().nullish(),ScaleVictimLossWithTier:z.boolean().nullish(),SynthesizedBuildingSlots:z.number().nullish(),SynthesizedBuildingMaxLevel:z.number().nullish(),DifficultyGrowthPerBoard:z.number().nullish()}).passthrough(),HP=z.object({CostMatrix:z.array(z.array(z.number())).nullish(),PerBoardGrowth:z.number().nullish(),EconomyScale:z.number().nullish(),ScaledResources:ce.nullish()}).passthrough(),Zd=z.object({SlotIndex:z.number().nullish(),Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxLevel:z.number().nullish(),MaxLevelReward:H.nullish()}).passthrough(),$P=z.object({Index:z.number().nullish(),Type:z.string().nullish(),CustomTypeID:z.string().nullish(),RandomActionAttackWeight:z.number().nullish(),RandomActionRaidWeight:z.number().nullish(),ChanceTableID:z.string().nullish(),SpecialModeID:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),JP=z.object({Tiles:z.record(z.string(),$P).nullish()}).passthrough(),ZP=z.object({Weight:z.number().nullish(),Bonus:We.nullish(),Tag:z.string().nullish()}).passthrough(),YP=z.object({Weight:z.number().nullish(),Tag:z.string().nullish(),MinBonusCells:z.number().nullish(),MaxBonusCells:z.number().nullish(),BonusPool:z.array(ZP).nullish(),GuaranteedBonus:We.nullish(),IsJackpot:z.boolean().nullish(),JackpotFinalMultiplier:z.number().nullish(),JackpotSymbolDistribution:z.record(z.string(),z.number()).nullish()}).passthrough(),XP=z.object({Variants:z.array(YP).nullish()}).passthrough(),eI=z.object({Weight:z.number().nullish(),OutcomeID:z.string().nullish(),Reward:We.nullish(),ForceAction:z.string().nullish(),SpecialModeID:z.string().nullish()}).passthrough(),tI=z.object({Outcomes:z.array(eI).nullish()}).passthrough(),Yd=z.object({PerAdMultiplierRange:Jd.nullish(),MaxAdViews:z.number().nullish(),AdCreditCost:z.number().nullish(),FormulaKind:z.string().nullish(),ApplyMultiplierOnEarlyClaim:z.boolean().nullish()}).passthrough(),iI=z.object({ElapsedSeconds:z.number().nullish(),Reward:We.nullish()}).passthrough(),sI=z.object({Tiers:z.array(iI).nullish(),TierMode:z.string().nullish(),BelowFirstTierReward:We.nullish()}).passthrough(),nI=z.object({RequiredValue:z.number().nullish(),Reward:We.nullish()}).passthrough(),rI=z.object({Reward:We.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough(),oI=z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(nI).nullish(),Rate:rI.nullish()}).passthrough(),Xd=z.object({MetricsByID:z.record(z.string(),oI).nullish()}).passthrough(),aI=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:We.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:ue.nullish(),Multipliers:Yd.nullish(),Gradation:sI.nullish(),RunStats:Xd.nullish()}).passthrough(),lI=z.object({Choices:z.array(aI).nullish(),OfferExpireSeconds:z.number().nullish(),ClaimExpireSeconds:z.number().nullish()}).passthrough(),uI=z.object({Chance:z.number().nullish(),RequiredOutcome:z.string().nullish(),Reward:We.nullish(),Tag:z.string().nullish()}).passthrough(),cI=z.object({OnPassStart:We.nullish(),OnTileLanding:z.record(z.string(),We).nullish(),OnAttack:z.record(z.string(),We).nullish(),OnRaid:z.record(z.string(),We).nullish(),OnBuild:We.nullish(),OnStageComplete:We.nullish(),OnAttackBonusDrops:z.array(uI).nullish(),ChanceTablesByID:z.record(z.string(),tI).nullish(),SpecialModesByID:z.record(z.string(),lI).nullish()}).passthrough(),em=z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:z.number().nullish(),MaxShields:z.number().nullish(),Buildings:z.array(Zd).nullish(),HeistGridBonusConfig:XP.nullish(),StageOperations:cI.nullish(),TileLandingMultiplier:Jd.nullish(),EconomyOverride:HP.nullish()}).passthrough(),pI=z.object({Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BoardTemplateID:z.string().nullish(),Buildings:z.array(Zd).nullish(),StageTemplateID:z.string().nullish(),CostMatrixTemplateID:z.string().nullish(),UnitValue:z.number().nullish(),Override:em.nullish()}).passthrough(),hI=z.object({AttackCooldownSeconds:z.number().nullish(),RaidCooldownSeconds:z.number().nullish(),MaxRecentTargets:z.number().nullish(),LiveOpponentActiveDays:z.number().nullish(),LiveOpponentPoolSize:z.number().nullish(),LiveOpponentPoolCacheSeconds:z.number().nullish(),MaxLiveCandidateReads:z.number().nullish(),VictimImmunitySeconds:z.number().nullish()}).passthrough(),dI=z.object({Enabled:z.boolean().nullish(),IntervalSeconds:z.number().nullish(),MaxPerCatchUp:z.number().nullish(),Chance:z.number().nullish(),AttackWeight:z.number().nullish(),RaidWeight:z.number().nullish(),MinBoardStageLevel:z.number().nullish(),RaidLossMultiplier:z.number().nullish()}).passthrough(),qr=z.object({RollCurrencyID:z.string().nullish(),ShieldCurrencyID:z.string().nullish(),RaidMode:z.string().nullish(),AllowedRollMultipliers:z.array(z.number()).nullish(),BoardTemplatesByID:z.record(z.string(),JP).nullish(),StageTemplatesByID:z.record(z.string(),em).nullish(),StagesByLevel:z.record(z.string(),pI).nullish(),SoftCurrencyID:z.string().nullish(),ProceduralEconomy:KP.nullish(),Dice:WP.nullish(),Bots:QP.nullish(),Targeting:hI.nullish(),BotRaids:dI.nullish()}).passthrough(),mI=z.object({IsActive:z.boolean().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AnchorUtc:c.nullish(),RoundDurationSec:z.number().nullish(),PauseBetweenRoundsSec:z.number().nullish(),MaxRounds:z.number().nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),ContributionMin:z.number().nullish(),ContributionMax:z.number().nullish(),ScaleContributionWithRollMultiplier:z.boolean().nullish(),MaxProgress:z.number().nullish(),Milestones:z.record(z.string(),Le).nullish(),GrandPrize:H.nullish()}).passthrough(),Br=z.object({Board:qr.nullish(),CommunityChest:mI.nullish()}).passthrough(),tm=z.object({AttackerGainByOutcome:z.record(z.string(),ce).nullish()}).passthrough(),fI=z.object({TargetUserID:z.string().nullish(),IsBot:z.boolean().nullish(),PublicData:Ee.nullish(),TargetBuildingStates:z.array(VP).nullish(),TargetHasShield:z.boolean().nullish(),TargetStageLevel:z.number().nullish(),RaidRewardPreview:tm.nullish()}).passthrough(),gI=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:We.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:ue.nullish(),Multipliers:Yd.nullish(),RunStats:Xd.nullish()}).passthrough(),yI=z.object({ModeID:z.string().nullish(),Choices:z.array(gI).nullish()}).passthrough(),RI=z.object({GroupID:z.string().nullish(),Delta:j.nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),UnlockedMilestoneIDs:z.array(z.string()).nullish(),Completed:z.boolean().nullish()}).passthrough(),im=z.object({UsedMultiplier:z.number().nullish(),Steps:z.number().nullish(),DiceValues:z.array(z.number()).nullish(),OldPosition:z.number().nullish(),NewPosition:z.number(),CyclesCompletedDelta:j.nullish(),LandedTileType:z.string().nullish(),Operation:M.nullish(),Inventory:K.nullish(),ActionRequired:z.string().nullish(),ActionData:fI.nullish(),SpecialModeOffer:yI.nullish(),CommunityChestContribution:RI.nullish()}).passthrough(),sm=z.object({Outcome:z.string().nullish(),IsBotTarget:z.boolean().nullish(),BuildingIndexHit:z.number().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:Dt.nullish()}).passthrough(),Qa=z.object({Status:z.string().nullish(),Outcome:z.string().nullish(),FoundSymbol:z.union([z.string(),z.number()]).nullish(),FoundBonus:H.nullish(),OpenedIndex:z.number().nullish(),AttemptsLeft:z.number().nullish(),RaidLayout:z.array(NP).nullish(),HeistVariantTag:z.string().nullish(),IsJackpot:z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:Dt.nullish(),RaidRewardPreview:tm.nullish()}).passthrough(),nm=z.object({BuiltIndex:z.number(),NewLevel:z.number().nullish(),StageComplete:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish()}).passthrough(),rm=z.object({Mode:z.union([z.string(),z.number()]).nullish(),Operation:M.nullish(),Inventory:K.nullish(),DurationSeconds:z.number().nullish(),StartedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish()}).passthrough(),om=z.object({AdViewsUsed:z.number().nullish(),RolledMultiplier:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),RemainingAdViews:z.number().nullish()}).passthrough(),CI=z.object({MetricID:z.string().nullish(),ReachedTierIndex:z.number().nullish(),RequiredValue:z.number().nullish(),RewardUnits:z.number().nullish()}).passthrough(),am=z.object({FinalMultiplier:z.number().nullish(),AdViewsUsed:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),IsEarlyClaim:z.boolean().nullish(),ReachedTierIndex:z.number().nullish(),Operation:M.nullish(),Inventory:K.nullish(),AcceptedRunStats:z.record(z.string(),z.number()).nullish(),RunStatAwards:z.array(CI).nullish(),RunStatsClamped:z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),SI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},lm=z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),xI={Active:"Active",Left:"Left",Replaced:"Replaced"},bI=z.enum(["Active","Left","Replaced"]).catch("Active"),DI=z.object({CurrentProgress:j.nullish(),MaxProgress:j.nullish()}).passthrough(),PI=z.object({UserID:z.string().nullish(),PublicData:Ee.nullish(),IsBot:z.boolean().nullish(),ContributionPoints:j.nullish(),MilestoneClaims:z.record(z.string(),Cl).nullish(),GrandPrizeClaimed:z.boolean().nullish(),MemberStatus:bI.nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),um=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),RoundIndex:z.number().nullish(),Members:z.array(PI).nullish(),SharedProgress:DI.nullish(),Status:lm.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:z.number().nullish()}).passthrough(),II=z.object({GroupID:z.string().nullish(),RoundIndex:z.number().nullish(),FinalStatus:lm.nullish(),GrandPrizeReceived:z.boolean().nullish(),FinishedAtUtc:c.nullish()}).passthrough(),vI=z.object({ActiveGroupID:z.string().nullish(),ActiveRoundIndex:z.number().nullish(),History:z.array(II).nullish()}).passthrough(),cm=z.object({ServerTimeUtc:c.nullish(),UserState:vI.nullish(),ActiveGroup:um.nullish(),SecondsRemaining:j.nullish()}),pm=z.object({ServerTimeUtc:c.nullish(),Group:um.nullish(),SecondsRemaining:j.nullish()}),Ka=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),hm=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),Be={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 TI={Mesh:"Mesh",Host:"Host"},Ha=z.enum(["Mesh","Host"]).catch("Mesh"),AI={ServerRelay:"ServerRelay",P2P:"P2P"},$a=z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),kI={Public:"Public",Private:"Private"},zI=z.enum(["Public","Private"]).catch("Public"),wI={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},MI=z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),dm=z.object({Urls:z.string().nullish(),Username:z.string().nullish(),Credential:z.string().nullish()}).passthrough(),OI=z.object({Enabled:z.boolean().nullish()}).passthrough(),mm=z.object({SystemState:OI.nullish(),DefaultTopology:Ha.nullish(),AllowCreatorTopologyOverride:z.boolean().nullish(),DefaultChatMode:$a.nullish(),AllowCreatorChatOverride:z.boolean().nullish(),MaxPlayersPerRoom:z.number().nullish(),RoomTtlSeconds:z.number().nullish(),MaxRoomLifetimeSeconds:z.number().nullish(),HeartbeatIntervalMs:z.number().nullish(),MemberTimeoutMs:z.number().nullish(),MaxSignalPayloadBytes:z.number().nullish(),MaxChatTextLength:z.number().nullish(),RoomLogCap:z.number().nullish(),VoiceEnabled:z.boolean().nullish(),RecordVoices:z.boolean().nullish(),IceServers:z.array(dm).nullish()}).passthrough(),EI=z.object({UserID:z.string().nullish(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),Ready:z.boolean().nullish(),State:z.record(z.string(),z.string()).nullish(),JoinedAt:z.number().nullish(),IsHost:z.boolean().nullish(),LastSeenMs:z.number().nullish()}).passthrough(),UI=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),Topology:Ha.nullish(),ChatMode:$a.nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),MemberCount:z.number().nullish(),CreatedAt:z.number().nullish()}).passthrough(),qI=z.object({Seq:z.number().nullish(),Type:MI.nullish(),FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Kind:z.string().nullish(),Payload:z.string().nullish(),Ts:z.number().nullish()}).passthrough(),Bi=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),OwnerUserID:z.string().nullish(),Topology:Ha.nullish(),ChatMode:$a.nullish(),Visibility:zI.nullish(),Status:z.string().nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),Members:z.array(EI).nullish(),IceServers:z.array(dm).nullish(),Seq:z.number().nullish(),BannedUserIDs:z.array(z.string()).nullish()}).passthrough(),fm=z.object({Removed:z.boolean().nullish(),Banned:z.boolean().nullish()}).passthrough(),gm=z.object({WasBanned:z.boolean().nullish()}).passthrough(),Ja=z.object({Closed:z.boolean().nullish(),NewHostUserID:z.string().nullish()}).passthrough(),ym=z.object({Rooms:z.array(UI).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}).passthrough(),Rm=z.object({Envelopes:z.array(qI).nullish(),MaxSeq:z.number().nullish()}).passthrough(),Lr=z.object({Seq:z.number().nullish()}).passthrough(),$e={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 Za=z.object({TitleCustomData:Er.nullish(),Character:Hs.nullish(),Item:Jn.nullish(),Currency:Tn.nullish(),Store:gs.nullish(),Lootbox:Ea.nullish(),Quest:Qi.nullish(),TimedEvent:Os.nullish(),Leaderboard:Vs.nullish(),Season:js.nullish(),Reward:qa.nullish(),Collection:br.nullish(),Craft:La.nullish(),DealOffer:_o.nullish(),Premium:wa.nullish(),TimedBoost:wr.nullish(),CoopEvent:sn.nullish(),GameLoop:Br.nullish(),Match:pa.nullish(),Experiment:Mh.nullish(),Blockchain:na.nullish(),Marketplace:ga.nullish(),Multiplayer:mm.nullish(),UserCustomData:Sn.nullish(),Referral:Va.nullish(),Localization:Nh.nullish(),Analytics:xh.nullish(),Social:op.nullish(),PlatformBridge:ap.nullish()}).passthrough();var ei={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Gr=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(ei.GetTitlePublicConfiguration,e,Za)}getTitlePublicConfigurationExcept(e){return this.send(ei.GetTitlePublicConfigurationExcept,e,Za)}getCurrencyDefinitions(e){return this.send(ei.GetCurrencyDefinitions,e,Tn)}getItemDefinitions(e){return this.send(ei.GetItemDefinitions,e,Jn)}getServerTime(e){return this.send(ei.GetServerTime,e,qe)}};var Fr=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Be.GetGameLoops,e,Br)}getBoardDefinition(e,t=false){return this.send(Be.GetBoardDefinition,e,qr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Be.GetBoardDefinitionForLevel,e,qr,{silent:t})}getUserBoardState(e){return this.send(Be.GetUserBoardState,e,$d)}boardLoopRoll(e){return this.send(Be.BoardLoopRoll,e,im)}boardLoopAttack(e){return this.send(Be.BoardLoopAttack,e,sm)}boardLoopRaid(e){return this.send(Be.BoardLoopRaid,e,Qa)}boardLoopRaidFast(e){return this.send(Be.BoardLoopRaidFast,e,Qa)}boardLoopBuild(e){return this.send(Be.BoardLoopBuild,e,nm)}boardSpecialChoose(e){return this.send(Be.BoardSpecialChoose,e,rm)}boardSpecialApplyMultiplier(e){return this.send(Be.BoardSpecialApplyMultiplier,e,om)}boardSpecialClaim(e){return this.send(Be.BoardSpecialClaim,e,am)}getCommunityChestState(e){return this.send(Be.GetCommunityChestState,e,cm)}joinOrCreateCommunityChest(e){return this.send(Be.JoinOrCreateCommunityChest,e,pm)}claimCommunityChestMilestone(e){return this.send(Be.ClaimCommunityChestMilestone,e,Ka)}claimCommunityChestGrandPrize(e){return this.send(Be.ClaimCommunityChestGrandPrize,e,Ka)}leaveCommunityChest(e){return this.send(Be.LeaveCommunityChest,e,hm)}};var LI={Live:"Live",Latest:"Latest",Specific:"Specific"},GI={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},FI=z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),VI={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"},NI=z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),_I=z.object({Level:FI,Message:z.string().nullish(),Data:qt.nullish()}),jI=z.object({Error:NI,Message:z.string().nullish(),StackTrace:z.string().nullish()}),Cm=z.object({FunctionName:z.string().nullish(),Revision:z.number().nullish(),FunctionResult:qt.nullish(),FunctionResultTooLarge:z.boolean().nullish(),Logs:z.array(_I).nullish(),LogsTooLarge:z.boolean().nullish(),ExecutionTimeSeconds:z.number().nullish(),APIRequestsIssued:z.number().nullish(),Error:jI.nullish()}),Ya={Execute:"Execute"};var Vr=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(Ya.Execute,e,Cm)}};var Nr=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(He.GetDefinitions,e,kp)}getUserState(e){return this.send(He.GetUserState,e,zp)}depositToken(e){return this.send(He.DepositToken,e,wp)}depositNFT(e){return this.send(He.DepositNFT,e,Mp)}requestTokenWithdrawal(e){return this.send(He.RequestTokenWithdrawal,e,Op)}requestNFTWithdrawal(e){return this.send(He.RequestNFTWithdrawal,e,Ep)}getTransactionHistory(e){return this.send(He.GetTransactionHistory,e,Up)}retryWithdrawal(e){return this.send(He.RetryWithdrawal,e,qp)}confirmWithdrawal(e){return this.send(He.ConfirmWithdrawal,e,Bp)}donateToDeveloper(e){return this.send(He.DonateToDeveloper,e,la)}donateToUsersPool(e){return this.send(He.DonateToUsersPool,e,la)}getPlayAccess(e){return this.send(He.GetPlayAccess,e,Tp)}confirmPlayAccess(e){return this.send(He.ConfirmPlayAccess,e,Gt)}};var _r=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(ze.GetDefinitions,e,Zp)}getGroupedOffers(e){return this.send(ze.GetGroupedOffers,e,Yp)}getOffersByItem(e){return this.send(ze.GetOffersByItem,e,ya)}getOffer(e){return this.send(ze.GetOffer,e,Xp)}getBuyOrders(e){return this.send(ze.GetBuyOrders,e,ya)}getMyState(e){return this.send(ze.GetMyState,e,En)}getHistory(e){return this.send(ze.GetHistory,e,th)}createListing(e){return this.send(ze.CreateListing,e,Oi)}cancelListing(e){return this.send(ze.CancelListing,e,lt)}buy(e){return this.send(ze.Buy,e,lt)}marketBuy(e){return this.send(ze.MarketBuy,e,lt)}marketSell(e){return this.send(ze.MarketSell,e,lt)}createAuction(e){return this.send(ze.CreateAuction,e,Oi)}placeBid(e){return this.send(ze.PlaceBid,e,eh)}claimAuction(e){return this.send(ze.ClaimAuction,e,lt)}createBuyOrder(e){return this.send(ze.CreateBuyOrder,e,Oi)}cancelBuyOrder(e){return this.send(ze.CancelBuyOrder,e,lt)}fillBuyOrder(e){return this.send(ze.FillBuyOrder,e,lt)}createDirectTrade(e){return this.send(ze.CreateDirectTrade,e,Oi)}respondDirectTrade(e){return this.send(ze.RespondDirectTrade,e,lt)}cancelDirectTrade(e){return this.send(ze.CancelDirectTrade,e,lt)}claimBack(e){return this.send(ze.ClaimBack,e,lt)}};var jr=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send($e.CreateRoom,e,Bi)}joinRoom(e){return this.send($e.JoinRoom,e,Bi)}leaveRoom(e,t=false){return this.send($e.LeaveRoom,e,Ja,{keepalive:t})}listRooms(e){return this.send($e.ListRooms,e,ym)}getRoom(e){return this.send($e.GetRoom,e,Bi)}closeRoom(e){return this.send($e.CloseRoom,e,Ja)}poll(e){return this.send($e.Poll,e,Rm)}sendSignal(e){return this.send($e.SendSignal,e,Lr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send($e.ClaimHost,e,Bi)}kickMember(e){return this.send($e.KickMember,e,fm)}unbanMember(e){return this.send($e.UnbanMember,e,gm)}sendChat(e){return this.send($e.SendChat,e,Lr)}setMemberState(e){return this.send($e.SetMemberState,e,Lr)}};var WI={Free:"Free",Price:"Price",Holding:"Holding"},Xa=z.enum(["Free","Price","Holding"]).catch("Free"),QI={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},KI=z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),HI={All:"All",Any:"Any"},$I=z.enum(["All","Any"]).catch("All"),JI={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},ZI=z.enum(["Public","Unlisted","Friends"]).catch("Public"),YI={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},XI=z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),ev={Purchase:"Purchase",Free:"Free",Holding:"Holding"},xm=z.enum(["Purchase","Free","Holding"]).catch("Free"),tv={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},iv={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},sv=z.enum(["Creator","License","Free","Holding"]).catch("License"),nv=z.object({Type:ni.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),Amount:z.number().nullish(),MinLevel:z.number().nullish()}).passthrough(),rv=z.object({Requirements:z.array(nv).nullish(),Match:$I.nullish(),Mode:KI.nullish()}).passthrough(),ov=z.object({OptionID:z.string().nullish(),Mode:Xa.nullish(),Price:ce.nullish(),Holding:rv.nullish()}).passthrough(),av=z.object({AllowedMimeTypes:z.array(z.string()).nullish(),MaxBytes:z.number().nullish(),MaxCount:z.number().nullish(),Required:z.boolean().nullish()}).passthrough(),lv=z.object({DisplayName:z.string().nullish(),Enabled:z.boolean().nullish(),Files:z.record(z.string(),av).nullish(),ThumbnailRequired:z.boolean().nullish(),AllowedAccessModes:z.array(Xa).nullish(),PricePolicy:On.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ue.nullish(),TagVocabulary:z.array(z.string()).nullish(),MaxPublishedPerPlayer:z.number().nullish(),DailyPublishCap:z.number().nullish()}).passthrough(),uv=z.object({Allowed:z.array(Mi).nullish(),MaxRequirements:z.number().nullish()}).passthrough(),cv=z.object({AutoHideReportThreshold:z.number().nullish(),RequireApproval:z.boolean().nullish(),BlockedTerms:z.array(z.string()).nullish()}).passthrough(),pv=z.object({MaxTitleLength:z.number().nullish(),MaxDescriptionLength:z.number().nullish(),MaxTags:z.number().nullish(),MaxTagLength:z.number().nullish(),MaxMetadataKeys:z.number().nullish(),MaxMetadataValueLength:z.number().nullish(),MaxAccessOptions:z.number().nullish(),ThumbnailMaxBytes:z.number().nullish()}).passthrough(),hv=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Schedule:fe.nullish(),Gate:Z.nullish(),Order:z.number().nullish()}).passthrough(),dv=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:fe.nullish(),ContentTypes:z.record(z.string(),lv).nullish(),PricePolicy:On.nullish(),Commission:fa.nullish(),HoldingPolicy:uv.nullish(),Moderation:cv.nullish(),Limits:pv.nullish(),Featured:z.array(hv).nullish()}).passthrough(),mv=z.object({Acquisitions:z.number().nullish(),Downloads:z.number().nullish(),Likes:z.number().nullish(),Favorites:z.number().nullish(),ReportCount:z.number().nullish(),Remixes:z.number().nullish()}).passthrough(),ti=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),CreatorUserID:z.string().nullish(),IsOfficial:z.boolean().nullish(),CreatorPublicData:Ee.nullish(),Title:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),Metadata:z.record(z.string(),z.string()).nullish(),ThumbnailUrl:z.string().nullish(),Visibility:ZI.nullish(),Access:z.array(ov).nullish(),Status:XI.nullish(),ModerationNote:z.string().nullish(),Stats:mv.nullish(),Revision:z.number().nullish(),ParentContentID:z.string().nullish(),FileCount:z.number().nullish(),TotalBytes:z.number().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),PublishedAt:c.nullish(),IsMine:z.boolean().nullish(),Owned:z.boolean().nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish()}).passthrough(),fv=z.object({OptionID:z.string().nullish(),Mode:Xa.nullish(),Available:z.boolean().nullish()}).passthrough(),bm=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Order:z.number().nullish()}).passthrough(),Dm=z.object({Definitions:dv.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish(),CanPublish:z.record(z.string(),z.boolean()).nullish(),Collections:z.array(bm).nullish()}).passthrough(),Wr=z.object({Items:z.array(ti).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Pm=z.object({Content:ti.nullish(),AccessState:z.array(fv).nullish(),CanDownload:z.boolean().nullish()}).passthrough(),Im=z.object({Collection:bm.nullish(),Items:z.array(ti).nullish()}).passthrough(),vm=z.object({CreatorUserID:z.string().nullish(),PublicData:Ee.nullish(),PublishedCount:z.number().nullish(),FollowerCount:z.number().nullish(),IsFollowing:z.boolean().nullish(),Items:z.array(ti).nullish()}).passthrough(),Sm=z.object({Role:z.string().nullish(),Index:z.number().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish(),ServerCopy:z.boolean().nullish()}).passthrough(),Tm=z.object({ContentID:z.string().nullish(),Revision:z.number().nullish(),Uploads:z.array(Sm).nullish(),ThumbnailUpload:Sm.nullish(),ExpiresAt:c.nullish()}).passthrough(),Am=z.object({Content:ti.nullish(),Resources:M.nullish()}).passthrough(),el=z.object({Content:ti.nullish()}).passthrough(),km=z.object({ContentID:z.string().nullish(),OptionID:z.string().nullish(),Source:xm.nullish(),AlreadyOwned:z.boolean().nullish(),AccessActive:z.boolean().nullish(),Settlement:Dt.nullish(),Resources:M.nullish(),CommissionTaken:ce.nullish()}).passthrough(),gv=z.object({Role:z.string().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish()}).passthrough(),zm=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),Revision:z.number().nullish(),AccessVia:sv.nullish(),Files:z.array(gv).nullish(),ThumbnailUrl:z.string().nullish(),ExpiresAt:c.nullish()}).passthrough(),yv=z.object({ContentID:z.string().nullish(),Source:xm.nullish(),OptionID:z.string().nullish(),PricePaid:ce.nullish(),AcquiredAt:c.nullish(),Content:ti.nullish()}).passthrough(),wm=z.object({Licenses:z.array(yv).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Qe={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 Qr=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(Qe.GetDefinitions,e,Dm)}browse(e){return this.send(Qe.Browse,e,Wr)}getContent(e){return this.send(Qe.GetContent,e,Pm)}getCollection(e){return this.send(Qe.GetCollection,e,Im)}getCreatorProfile(e){return this.send(Qe.GetCreatorProfile,e,vm)}beginUpload(e){return this.send(Qe.BeginUpload,e,Tm)}publish(e){return this.send(Qe.Publish,e,Am)}updateContent(e){return this.send(Qe.UpdateContent,e,el)}unpublish(e){return this.send(Qe.Unpublish,e,el)}getMyContent(e){return this.send(Qe.GetMyContent,e,Wr)}acquire(e){return this.send(Qe.Acquire,e,km)}getDownload(e){return this.send(Qe.GetDownload,e,zm)}getMyLicenses(e){return this.send(Qe.GetMyLicenses,e,wm)}getMyFavorites(e){return this.send(Qe.GetMyFavorites,e,Wr)}};var Kr=class extends B{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let r=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(r,t,i,{throttleKey:`${r}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,ah,"defs")}get(e){return this.sendKeyed("Get",e,Ca,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,uh,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,Sa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,ch,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,xa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,xa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,ph,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,dh,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,hh,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,mh,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,lh,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,fh,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,Ca,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,Sa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Hr=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;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$1){this.settings=rl(e$1),this.emitter=new xi,this.platform=e$1.platform??new e,this.clientPlatform=e$1.clientPlatform??yl(),this.acquisition=new jt(this.platform),this.acquisition.capture(),this.playtime=new bi(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$1.fetch??globalThis.fetch.bind(globalThis),this.transport=new Xi({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e$1.fetch,debugLogging:this.settings.debugLogging,throttleMs:e$1.throttleMs,maxRequestsPerSecond:e$1.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new ss(this.emitter),this.cache=new rs(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e$1.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 os(this.platform.storage,this.settings.titleID),this.api={authentication:new Wn(this),user:new Kn(this),currency:new Hn(this),item:new Zn(this),store:new Yn(this),purchase:new ir(this),lootbox:new rr(this),reward:new or(this),quest:new hr(this),tutorial:new ar(this),communityMarketing:new lr(this),chat:new ur(this),push:new cr(this),localization:new pr(this),timedEvent:new dr(this),leaderboard:new mr(this),season:new fr(this),premium:new gr(this),character:new yr(this),match:new Rr(this),craft:new Sr(this),ai:new xr(this),collection:new Dr(this),coopEvent:new Pr(this),dealOffer:new Ir(this),referral:new vr(this),mailbox:new Tr(this),advertising:new Ar(this),social:new kr(this),timedBoost:new Mr(this),userCustomData:new Or(this),titleCustomData:new Ur(this),title:new Gr(this),gameLoop:new Fr(this),cloudCode:new Vr(this),blockchain:new Nr(this),marketplace:new _r(this),multiplayer:new jr(this),workshop:new Qr(this),dataCollections:new Kr(this),analytics:new _n(this),experiment:new jn(this)},this.userService=new ps(this),this.cache.attachState(this.userService),this.auth=new as(this),this.currency=new ds(this),this.item=new ms(this),this.store=new Rs(this),this.purchase=new Cs(this),this.checkout=new Ss(this),this.lootbox=new xs(this),this.reward=new bs(this),this.quest=new Ms(this),this.tutorial=new Ps(this),this.communityMarketing=new Is(this),this.chat=new As(this),this.push=new ks(this),this.localization=new ws(this),this.timedEvent=new Us(this),this.leaderboard=new Ns(this),this.season=new Ws(this),this.premium=new Qs(this),this.character=new $s(this),this.match=new Js(this),this.craft=new Zs(this),this.ai=new Xs(this),this.collection=new en(this),this.coopEvent=new nn(this),this.dealOffer=new an(this),this.referral=new ln(this),this.mailbox=new pn(this),this.ads=new mn(this),this.social=new yn(this),this.timedBoost=new Rn(this),this.userCustomData=new xn(this),this.titleCustomData=new bn(this),this.title=new Dn(this),this.gameLoop=new Pn(this),this.cloudCode=new In(this),this.blockchain=new kn(this),this.marketplace=new Un(this),this.multiplayer=new qn(this),this.workshop=new Bn(this),this.dataCollections=new Gn(this),this.analytics=new Vn(this),this.experiments=new Nn(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:d()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var $r=class{ctx;constructor(e){this.ctx=new Hr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Vt(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(n,{...s,...i},z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get 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 Cv(o){return new $r(o)}var Mm="idos_sso",Om="state",tl="idos:sso:state",Sv="https://idosgames.com/sso/",xv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],bv=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function Dv(){if(typeof window>"u")return false;let{origin:o}=window.location;return xv.includes(o)||bv.test(o)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function Pv(){if(typeof window>"u")return null;let o=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!o)return null;let e=new URLSearchParams(o),t=e.get(Mm);if(!t)return null;let i=e.get(Om)??"",s=kv();return wv(e),zv(),s&&i!==s?null:{code:t,state:i}}function Iv(o){if(typeof window>"u")return;let e=o.returnTo??vv(),t=Tv();Av(t);let i=new URL(o.ssoUrl??Sv);i.searchParams.set("title",o.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function vv(){let{origin:o,pathname:e,search:t}=window.location;return `${o}${e}${t}`}function Tv(){let o=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(o);else for(let e=0;e<o.length;e++)o[e]=Math.floor(Math.random()*256);return Array.from(o,e=>e.toString(16).padStart(2,"0")).join("")}function Av(o){try{window.sessionStorage.setItem(tl,o);}catch{}}function kv(){try{return window.sessionStorage.getItem(tl)}catch{return null}}function zv(){try{window.sessionStorage.removeItem(tl);}catch{}}function wv(o){o.delete(Mm),o.delete(Om);let e=o.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var Mv={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 Ov(o,e="Something went wrong. Please try again."){return o?Mv[o]??o:e}function Ev(o,e){return !!o?.Claims?.[e]?.ClaimedAt}function Uv(o){let e=o?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function qv(o,e){return o?.Claims?.[e]?.PremiumTiers??[]}function Um(o,e,t,i=1){if(!o)return e;let s=o.Base??e,n=Math.max(0,t-i),r;switch(o.Shape??"Flat"){case "PerStep":r=s+(o.PerStep??0)*n;break;case "PerStepRate":r=s*(1+(o.PerStepRate??0)*n);break;case "Geometric":r=s*Math.pow(1+(o.GrowthRate??0),n);break;case "Table":r=s*Em(o,t,1);break;case "TableAbsolute":r=Em(o,t,s);break;default:r=s;break}return Number.isNaN(r)?s:(o.MinResult!=null&&r<o.MinResult&&(r=o.MinResult),o.MaxResult!=null&&r>o.MaxResult&&(r=o.MaxResult),r)}function Bv(o,e,t=1){return Um(o,1,e,t)}function Lv(o){if(!o)return false;switch(o.Shape??"Flat"){case "PerStep":return (o.PerStep??0)!==0;case "PerStepRate":return (o.PerStepRate??0)!==0;case "Geometric":return (o.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return qm(o.Points).length>0;default:return o.MinResult!=null||o.MaxResult!=null}}function Gv(o){if(Number.isNaN(o)||o<=0)return 0;if(!Number.isFinite(o))return Number.MAX_SAFE_INTEGER;let e=Math.round(o);return Math.abs(o-e)<=1e-9*Math.max(1,Math.abs(o))?e:Math.ceil(o)}function qm(o){if(!o)return [];let e=[];for(let t of o)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function Em(o,e,t){let i=qm(o.Points);if(i.length===0)return t;let s=null,n=null,r=null;for(let p of i)(r===null||p.AtStep>r.AtStep)&&(r=p),p.AtStep<=e&&(s===null||p.AtStep>=s.AtStep)&&(s=p),p.AtStep>e&&(n===null||p.AtStep<n.AtStep)&&(n=p);if(s===null)return t;if(n===null){let p=o.TailGrowthRate??0;return p===0?r.Value:r.Value*Math.pow(1+p,e-r.AtStep)}switch(o.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+p*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let d=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+d*(n.Value-s.Value)}let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,p)}default:return s.Value}}var Fv={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},il=z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),Vv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Nv=z.enum(["Top","Bottom","Left","Right"]).catch("Top"),_v=z.object({PlacementID:z.string().nullish(),Type:il.nullish(),Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),CreditsRewarded:z.number().nullish(),AllowedProviderIDs:z.array(z.string()).nullish()}).passthrough(),jv=z.object({DefaultCreditsPerView:z.number().nullish(),MaxCreditsBalance:z.number().nullish(),DailyCreditEarnCap:z.number().nullish(),DailyViewCap:z.number().nullish(),MinSecondsBetweenViews:z.number().nullish()}).passthrough(),Wv=z.object({CooldownSeconds:z.number().nullish(),MinSessionTimeBeforeFirstSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),Qv=z.object({Enabled:z.boolean().nullish(),Position:Nv.nullish(),RefreshIntervalSeconds:z.number().nullish()}).passthrough(),Kv=z.object({Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish()}).passthrough(),Hv=z.object({MaxImpressionsPerHour:z.number().nullish(),MaxImpressionsPerDay:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),$v=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),DisableInterstitials:z.boolean().nullish(),DisableBanners:z.boolean().nullish(),DisableAppOpen:z.boolean().nullish()}).passthrough(),Jv=z.object({RequirePersonalizedAdsConsent:z.boolean().nullish(),RequireTrackingConsent:z.boolean().nullish(),CurrentPolicyVersion:z.string().nullish(),RegulatedRegions:z.array(z.string()).nullish()}).passthrough(),Zv=z.object({RequireServerSideVerification:z.boolean().nullish(),PendingRequestTtlSeconds:z.number().nullish(),MaxPendingRequestsPerUser:z.number().nullish()}).passthrough(),Yv=z.object({AndroidUnitID:z.string().nullish(),IosUnitID:z.string().nullish(),WebUnitID:z.string().nullish(),Type:il.nullish()}).passthrough(),Xv={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},eT=z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),tT=z.object({ProviderID:z.string().nullish(),Kind:eT.nullish(),Enabled:z.boolean().nullish(),Priority:z.number().nullish(),AndroidAppID:z.string().nullish(),IosAppID:z.string().nullish(),WebAppID:z.string().nullish(),Units:z.record(z.string(),Yv).nullish()}).passthrough();z.object({Enabled:z.boolean().nullish(),Placements:z.record(z.string(),_v).nullish(),Providers:z.record(z.string(),tT).nullish(),RewardedVideo:jv.nullish(),Interstitial:Wv.nullish(),Banner:Qv.nullish(),AppOpen:Kv.nullish(),FrequencyCapping:Hv.nullish(),PremiumAdReductions:z.array($v).nullish(),Consent:Jv.nullish(),Verification:Zv.nullish()}).passthrough();var iT=z.object({RewardedVideoCredit:z.number().nullish(),TotalEarned:z.number().nullish(),TotalSpent:z.number().nullish()}).passthrough(),sT=z.object({PlacementID:z.string().nullish(),LastShownAt:c.nullish(),LastCompletedAt:c.nullish(),TotalImpressions:z.number().nullish(),TotalCompletions:z.number().nullish(),ConsecutiveFailures:z.number().nullish()}).passthrough(),nT=z.object({Date:c.nullish(),ImpressionsByPlacement:z.record(z.string(),z.number()).nullish(),CompletionsByPlacement:z.record(z.string(),z.number()).nullish(),TotalImpressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish(),AppOpenImpressions:z.number().nullish(),CreditsEarnedToday:z.number().nullish()}).passthrough(),rT=z.object({SessionID:z.string().nullish(),SessionStartAt:c.nullish(),Impressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish()}).passthrough(),oT=z.object({PersonalizedAdsConsent:z.boolean().nullish(),TrackingConsent:z.boolean().nullish(),PolicyVersion:z.string().nullish(),Region:z.string().nullish(),ConsentGivenAt:c.nullish(),ConsentRevokedAt:c.nullish()}).passthrough(),aT=z.object({RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),Type:il.nullish(),IssuedAt:c.nullish(),ExpiresAt:c.nullish(),CreditsToAward:z.number().nullish()}).passthrough(),lT=z.object({InvalidSsvCount:z.number().nullish(),OrphanCompletions:z.number().nullish(),FastCompletions:z.number().nullish(),LastFlaggedAt:c.nullish()}).passthrough();z.object({Credits:iT.nullish(),Placements:z.record(z.string(),sT).nullish(),Daily:nT.nullish(),Session:rT.nullish(),LastImpressionAt:c.nullish(),LastInterstitialAt:c.nullish(),LastRewardedAt:c.nullish(),LastAppOpenAt:c.nullish(),TotalImpressions:z.number().nullish(),TotalRewardedCompletions:z.number().nullish(),AdsDisabledUntil:c.nullish(),Consent:oT.nullish(),PendingRequests:z.record(z.string(),aT).nullish(),FraudFlags:lT.nullish(),UpdatedAt:c.nullish()}).passthrough();
2
- export{Fe as AIAction,SR as AIErrorCode,Kt as AIGenerationStatus,Bt as AIModality,jt as AcquisitionCapture,Xv as AdProviderKind,Fv as AdType,hn as AdvertisingAction,Ia as AnalyticsAction,hb as AnalyticsDropReason,Pa as AnalyticsEventNaming,St as AnalyticsLimits,FP as AttackOutcome,Ae as AuthType,Ue as AuthenticationAction,Ft as AutomaticEvent,Vv as BannerPosition,He as BlockchainAction,xS as BlockchainNetworkType,bp as BlockchainOperationCategory,zS as BlockchainTransactionStatus,IS as BlockchainTransactionType,nx as BodyPart,zP as BoostWindowKind,_e as CharacterAction,Ke as ChatAction,cy as ChatAuthorType,ly as ChatBlockedTermAction,sy as ChatChannelType,oy as ChatDirectAudience,ny as ChatPartitioning,hy as ChatReportReason,ft as ClientPlatform,Ya as CloudCodeAction,VI as CloudCodeErrorCode,GI as CloudCodeLogLevel,LI as CloudCodeRevisionSelection,je as CollectionAction,Px as CommissionSink,xI as CommunityChestMemberStatus,SI as CommunityChestStatus,LD as CommunityCreatorStatus,Zt as CommunityMarketingAction,FD as CommunityMetricKind,qD as CommunityParticipationMode,GD as CommunityPayoutCurrencyKind,cS as ConversionRateMode,dt as CoopEventAction,MR as CoopGroupStatus,OR as CoopMemberStatus,Cr as CraftAction,XD as CraftInputSelectionMode,ZD as CraftOutputLevelMode,tP as CraftOutputLevelOverflow,JD as CraftType,Ii as CreditsConfirmationStatus,Ug as CreditsError,vn as CurrencyAction,uS as CurrencyStatus,ct as CurrencyType,Df as CurveInterpolation,xf as CurveShape,At as CustomDataBucket,eS as CustomDataValueType,JC as CustomDataWriter,nl as DEFAULT_BASE_URL,jx as DataAccessMode,Fx as DataCollectionKind,Yx as DataCollectionSchemaMode,ab as DataCollectionsAction,Hx as DataCounterKind,Nx as DataFieldType,_x as DataFieldVisibility,Jx as DataOwnerDeletedPolicy,Qx as DataRefKind,ZR as DealComparisonOperator,_R as DealNodeRuntimeStatus,JR as DealNodeType,Rt as DealOfferAction,NR as DealOfferActivationStatus,Fn as EVENT_NAME_PATTERN,wI as EnvelopeType,cf as EventTokenType,Aa as ExperimentAction,Db as ExperimentGoalKind,QC as FRIENDS_FROM_PLATFORM,qb as FodderSelectionMode,Eb as FodderValuationMode,OC as FriendActionStatus,EC as FriendSource,Be as GameLoopAction,$r as IDosGamesClient,$b as IapProductType,uD as IapPurchaseStatus,uf as IapStoreValues,$n as ItemAction,vS as KycStatus,AS as KycTier,Ne as LeaderboardAction,Qn as LocalizationAction,kb as LocalizationMissingKeyMode,nr as LootboxAction,SC as MAILBOX_COUNTER_CAP,tt as MailboxAction,mC as MailboxCategory,CC as MailboxErrors,fC as MailboxLetterSource,yC as MailboxRewardModule,Mn as MarketGoodsType,Dx as MarketOfferStatus,bx as MarketOfferType,ze as MarketplaceAction,Ct as MatchAction,rx as MatchStatus,$e as MultiplayerAction,AI as MultiplayerChatMode,TI as MultiplayerTopology,ty as OFFER_NOT_IN_ROTATION,$o as PLATFORM_AD_MESSAGES,Ho as PLATFORM_AD_PROVIDER,HC as PlatformFriendsMode,KC as PlatformProfileMode,GS as PlayAccessMode,vb as PlayerExperimentStatus,bi as PlaytimeTracker,$t as PremiumAction,Jt as PurchaseAction,hi as PushAction,vt as PushPermissionState,vy as PushTopic,Py as PushTransport,ht as QuestAction,Ef as QuestObjectiveSource,qf as QuestPrerequisiteMode,wf as QuestStatus,LP as RaidMode,Nt as ReferralAction,Fi as ResourceEntryType,zt as RewardAction,kI as RoomVisibility,CR as SKIN_ALREADY_OWNED,Bo as SKIN_SLOT,pf as ScheduleMode,Ut as SeasonAction,Ce as SocialAction,GC as SocialContentStatus,qC as SocialEntityType,FC as SocialInboxVerb,BC as SocialReactionKind,LC as SocialReportReason,GP as SpecialChoiceMode,It as StoreAction,Lg as StoreRotationMode,Kb as StoreType,Xt as TimedBoostAction,SP as TimedBoostStackingPolicy,at as TimedEventAction,ei as TitleAction,qi as TitleCustomDataAction,OP as TitleDataBucket,MP as TitleDataScope,aP as TradeOfferStatus,wS as TransactionDirection,rt as TutorialAction,Zf as TutorialBoardAction,Hf as TutorialFlowStatus,ff as TutorialGateMode,Qf as TutorialRestartPolicy,Jf as TutorialScriptModule,jf as TutorialStepCompletionMode,xi as TypedEmitter,ut as UserAction,mt as UserCustomDataAction,qS as WalletGateBalanceSource,DS as WalletLinkType,WI as WorkshopAccessMode,iv as WorkshopAccessVia,Qe as WorkshopAction,YI as WorkshopContentStatus,HI as WorkshopHoldingMatch,QI as WorkshopHoldingMode,ev as WorkshopLicenseSource,tv as WorkshopSort,JI as WorkshopVisibility,Ov as authErrorText,Iv as beginSsoRedirect,dn as canUsePlatformAds,Uv as claimedMilestoneIDs,Cv as createIDosGamesClient,ai as cryptoShortfallFromError,Bv as curveMultiplier,Sg as defineView,Dh as describeUserAgent,Um as evaluateCurve,qv as grantedPremiumTiers,Ti as isAIGenerationTerminal,Lv as isCurveConfigured,Ev as isMilestoneClaimed,lR as isReservedSlot,Dv as isSsoAvailable,An as normalizeBlockchainCategory,xR as parseAIErrorCode,Pv as readSsoCodeFromUrl,Jo as requestPlatformAd,Gv as roundAmount,ub as where,Eg as zPaymentProof,Xl as zPriceOption,ue as zPriceOptions};
1
+ import {s,j as j$1,e,d,n,v,w,t,f}from'./chunk-YSPGQWAB.js';export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,x as NoopPlatformAdapter,h as PLATFORM_BRIDGE_ACK,u as PLATFORM_CREDITS_CONFIRM_MESSAGES,f as PLATFORM_ORIGINS,i as PLATFORM_PAGE_UNAVAILABLE,k as PLATFORM_SIGN_IN_MESSAGES,r as PLATFORM_TOPUP_MESSAGES,j as askPlatformPage,v as canUsePlatformCreditsConfirm,l as canUsePlatformSignIn,s as canUsePlatformTopUp,m as canUsePreviewSignIn,p as clearPlatformSignInDeclined,g as isPlatformParentOrigin,q as isPlatformSignInDeclined,o as markPlatformSignInDeclined,w as requestPlatformCreditsConfirm,n as requestPlatformSignIn,t as requestPlatformTopUp}from'./chunk-YSPGQWAB.js';import {b,a,c}from'./chunk-CS7ACWDY.js';export{e as isFail,d as isOk}from'./chunk-CS7ACWDY.js';import {z}from'zod';import Ht from'decimal.js';var Di=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,s=>{i(),t(s);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let s of [...i])s(t);}removeAllListeners(){this.listeners.clear();}};function sf(){let r=new Map;return {get:e=>r.get(e)??null,set:(e,t)=>{r.set(e,t);},remove:e=>{r.delete(e);}}}function ol(){return nf()??sf()}function nf(){try{let r=globalThis.localStorage;if(!r)return null;let e="__idos_probe__";return r.setItem(e,"1"),r.removeItem(e),{get:t=>{try{return r.getItem(t)}catch{return null}},set:(t,i)=>{try{r.setItem(t,i);}catch{try{r.removeItem(t);}catch{}}},remove:t=>{try{r.removeItem(t);}catch{}}}}catch{return null}}var al="https://api.idosgames.com";function ll(r){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??al).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??ol(),locale:r.locale??rf(),appVersion:r.appVersion??""}}function rf(){try{return globalThis.navigator?.language??""}catch{return ""}}var ro="idos_acq",ul=["gclid","fbclid","ttclid","msclkid","yclid"],of=["ref","r"],af=["ref_","ref-","ref=","r_","r-"];var Qt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();lf(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=pf(this.platform.getDeviceModel());return s&&(i.OsVersion=s),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(ro);}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=dl(pl(t));if(i)return i}return Vi(t)}readFromEnvironment(){let e={},t=pl(this.platform.getFullURL());Wt(e,"UtmSource",t.get("utm_source")),Wt(e,"UtmMedium",t.get("utm_medium")),Wt(e,"UtmCampaign",t.get("utm_campaign")),Wt(e,"UtmTerm",t.get("utm_term")),Wt(e,"UtmContent",t.get("utm_content")),Wt(e,"ClaimToken",t.get("idos_click"));for(let R of ul){let V=t.get(R);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",s=cf(i);if(s){for(let R of uf)Wt(e,R,s.get(hl[R])??null);for(let R of ul){let V=s.get(R);if(V){e.ClickID=V;break}}}let n=Vi(s?s.get("ref")??s.get("r")??"":i),o=dl(t),c=n||o;c&&(e.ReferralCode=c,e.ChannelHint=n?"telegram":"query");let h=this.platform.getReferrer?.();return h&&(e.Referrer=h),e}read(){try{let e=this.platform.storage.getString(ro);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(ro,JSON.stringify(e));}catch{}}};function lf(r){return !!(r.UtmSource||r.UtmMedium||r.UtmCampaign||r.ClickID||r.Referrer||r.ReferralCode||r.ClaimToken)}function Wt(r,e,t){t&&(r[e]=t);}var cl="a1_",hl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},uf=Object.keys(hl);function cf(r){let e=(r||"").trim();if(!e.startsWith(cl))return null;let t=e.slice(cl.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),n=Uint8Array.from(s,h=>h.charCodeAt(0)),o=new TextDecoder().decode(n),c=new URLSearchParams(o);return [...c.keys()].length>0?c:null}catch{return null}}function pl(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function dl(r){for(let e of of){let t=r.get(e);if(t)return Vi(t)}return null}function Vi(r){let e=(r||"").trim();if(!e)return null;for(let t of af)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function pf(r){let e=r||"",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 ml="idos_usage_pending",fl="idos_usage_session",gl="idos_usage_closed_session",yl="idos_usage_new_session",Rl="idos_usage_last_activity",Pi=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(ml),this.currentSessionSeconds=this.readNumber(fl),this.pendingClosedSessionSeconds=this.readNumber(gl),this.isNewSessionPending=this.readNumber(yl)!==0;let e=this.readNumber(Rl);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(ml,this.pendingSeconds),this.writeNumber(fl,this.currentSessionSeconds),this.writeNumber(gl,this.pendingClosedSessionSeconds),this.writeNumber(yl,this.isNewSessionPending?1:0),this.writeNumber(Rl,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"},ri=z.enum(["Virtual","Crypto"]).catch("Virtual"),Ni={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},oi=z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),yt={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},_i=z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),df={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},ji=z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),hf={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Wi=z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),mf={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},Ii=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 Sl(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return Cl(e);let t=r.cordova?.platformId;return t?Cl(t):r.navigator?.userAgent??""?yt.Web:yt.Unknown}function Cl(r){let e=r.toLowerCase();return e==="android"?yt.Android:e==="ios"?yt.Ios:e==="web"?yt.Web:yt.Unknown}var j=z.union([z.number(),z.string()]).transform((r,e)=>{let t=typeof r=="string"?Number(r):r;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(r)}`}),z.NEVER)}),Y=z.union([z.number(),z.string()]).transform((r,e)=>{let t=typeof r=="number"?String(r):r.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid decimal: ${String(r)}`}),z.NEVER):t}),p=z.string();var oo=z.object({Type:oi.nullish(),CurrencyID:z.string().nullish(),Amount:j.nullish(),AmountUsd:z.number().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ProductID:z.string().nullish()}),ff=z.object({Type:Wi.nullish(),EntityID:z.string()}),gf=z.object({Address:ff.nullish(),Amount:j.nullish(),Source:z.string().nullish()}),ue=z.object({Entries:z.array(oo).nullish(),EventTokens:z.array(gf).nullish()}),xl=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Resources:ue.nullish()}),H=z.object({Standard:ue.nullish(),PremiumBonuses:z.array(z.unknown()).nullish(),PremiumTiers:z.array(xl).nullish()}),Pt=z.object({Standard:ue.nullish(),PremiumDiscounts:z.array(z.unknown()).nullish(),PremiumTiers:z.array(xl).nullish()}),M=z.object({Grant:H.nullish(),Consume:Pt.nullish()}),It=z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Transferred:ue.nullish()});var yf=z.object({ExperimentID:z.string().nullish(),Variants:z.array(z.string()).nullish()}).passthrough(),Rf={Completed:"Completed",Started:"Started",StepReached:"StepReached"},Cf=z.object({FlowIDs:z.array(z.string()).nullish(),Mode:z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:z.string().nullish(),Negate:z.boolean().nullish(),SkippedCountsAsCompleted:z.boolean().nullish()}).passthrough(),Z=z.object({Segments:z.array(z.string()).nullish(),MinPremiumTier:z.number().nullish(),RequiredPremiumIDs:z.array(z.string()).nullish(),MinLevel:z.number().nullish(),MaxLevel:z.number().nullish(),Countries:z.array(z.string()).nullish(),RegisteredWithinDays:z.number().nullish(),ActiveWithinDays:z.number().nullish(),Experiment:yf.nullish(),Tutorial:Cf.nullish(),Platforms:z.array(_i).nullish()}).passthrough();var Ce=z.object({TotalCap:z.number().nullish(),DailyCap:z.number().nullish(),DailyWeightCap:z.number().nullish(),PerActivationCap:z.number().nullish(),CooldownSeconds:z.number().nullish(),MaxPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish()}).passthrough();var Sf=z.object({OffsetSecondsFromParentStart:z.number().nullish(),DurationSeconds:z.number().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),xf=z.object({StartUtc:z.string().nullish(),EndUtc:z.string().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),bf=z.object({AnchorUtc:z.string().nullish(),MaxCycles:z.number().nullish(),PauseBetweenPhasesSec:z.number().nullish(),PauseBetweenCyclesSec:z.number().nullish()}).passthrough();z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();var Df=z.object({Reset:z.string().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:z.string().nullish(),PauseBetweenCyclesSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();z.object({SourceType:z.string().nullish(),TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),Outcome:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough();var ot=z.object({SourceType:z.string().nullish(),BaseWeight:z.number().nullish(),ScaleWithRollMultiplier:z.boolean().nullish(),TileTypeFilter:z.array(z.string()).nullish(),TileIndexFilter:z.array(z.number()).nullish(),ChanceOutcomeFilter:z.array(z.string()).nullish(),OutcomeFilter:z.array(z.string()).nullish(),Params:z.record(z.string(),z.string()).nullish(),Limits:Ce.nullish()}).passthrough(),ge=z.object({Mode:z.string().nullish(),IsActive:z.boolean().nullish(),Scheduled:xf.nullish(),Chain:bf.nullish(),Cyclic:Df.nullish(),ActivationTriggers:z.array(ot).nullish(),Relative:Sf.nullish()}).passthrough();var Pf={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},If=z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),vf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Tf=z.enum(["Step","Linear","Geometric"]).catch("Step"),Af=z.object({AtStep:z.number().nullish(),Value:z.number().nullish()}).passthrough(),_e=z.object({Base:z.number().nullish(),Shape:If.nullish(),PerStep:z.number().nullish(),PerStepRate:z.number().nullish(),GrowthRate:z.number().nullish(),Points:z.array(Af).nullish(),Interpolation:Tf.nullish(),TailGrowthRate:z.number().nullish(),MinResult:z.number().nullish(),MaxResult:z.number().nullish()}).passthrough();var kf=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Rewards:H.nullish()}).passthrough(),zf=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Multiplier:z.number().nullish()}).passthrough(),ao=z.object({Bundles:z.array(kf).nullish(),Multipliers:z.array(zf).nullish()}).passthrough();var wf=z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Qi=z.object({Source:wf.nullish(),SourceKey:z.string().nullish(),Curve:_e.nullish(),Anchor:z.number().nullish(),IncludeRewards:ue.nullish(),ExcludeRewards:ue.nullish()}).passthrough(),bl=z.object({ClaimedAt:z.string().nullish(),PremiumTiers:z.array(z.string()).nullish(),Unlocked:z.boolean().nullish()}).passthrough(),Fe=z.object({MilestoneID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredProgress:z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:ao.nullish(),SortOrder:z.number().nullish(),IsFeatured:z.boolean().nullish()}).passthrough(),ai=z.object({Milestones:z.record(z.string(),Fe).nullish()}).passthrough();var Q=z.object({PresetID:z.string().nullish(),Remove:z.array(z.string()).nullish()}).passthrough();var Mf=z.object({TargetCurrencyID:z.string().nullish(),Rate:z.number().nullish(),MaxConvertAmount:z.number().nullish()}).passthrough(),Kt=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxBalance:z.number().nullish(),MaxPerGrant:z.number().nullish(),DailyEarnCap:z.number().nullish(),BurnOnEventEnd:z.boolean().nullish(),BurnConversion:Mf.nullish()}).passthrough();var Of=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),Dl=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:Of.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(r=>r),K=z.object({ChangedInstances:z.record(z.string(),Dl).nullish(),RemovedInstanceIDs:z.array(z.string()).nullish()});var Te=r=>z.object({Id:z.string(),Success:z.boolean(),Error:z.string().nullish(),Data:r.nullish()}),Rt=r=>z.object({ServerTimeUtc:p,Items:z.array(Te(r)),Resources:M.nullish(),Inventory:K.nullish()});var Ef={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Pl=z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Uf=z.object({}).passthrough().transform(r=>r),qf=z.object({CycleID:z.string(),InstanceKey:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),CycleStartUtc:p.nullish(),CycleEndUtc:p.nullish(),PointsTotalEarned:j.nullish(),PointsCurrent:j.nullish(),ClaimedPointMilestoneIDs:z.array(z.string()).nullish(),NextMilestone:Fe.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),lo=z.object({QuestID:z.string(),CycleID:z.string().nullish(),ObjectiveID:z.string().nullish(),NewValue:j.nullish(),ObjectiveCompleted:z.boolean().nullish(),Status:Pl}),Il=z.object({State:Uf.nullish(),PointsTracks:z.record(z.string(),qf).nullish()}),uo=z.object({ServerTimeUtc:p,QuestID:z.string(),CycleID:z.string().nullish(),NewStatus:Pl.nullish(),Resources:M.nullish(),Inventory:K.nullish()}),co=z.object({ServerTimeUtc:p,CycleID:z.string(),MilestoneID:z.string(),PointsTotalEarned:j.nullish(),Resources:M.nullish(),Inventory:K.nullish(),NextMilestone:Fe.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),vl=z.object({ServerTimeUtc:p,CycleID:z.string(),GroupCompletionID:z.string(),GroupID:z.string().nullish(),CompletedGroupQuests:z.number().nullish(),RequiredGroupQuests:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Tl=z.object({MetricID:z.string(),Updates:z.array(lo).nullish()}),Al=z.array(Te(uo)),kl=z.array(Te(co)),Bf={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Lf=z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Gf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Ff=z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),zl=z.object({ObjectiveID:z.string().nullish(),Source:Lf.nullish(),MaxProgressPerCall:z.number().nullish(),MetricID:z.string().nullish(),Triggers:z.array(ot).nullish(),TargetValue:z.number().nullish(),AggregationMethod:z.string().nullish()}).passthrough(),po=z.object({Milestones:Q.nullish(),Linking:Q.nullish(),Availability:Q.nullish(),Reward:Q.nullish(),Objectives:Q.nullish()}).passthrough(),Vf=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),wl=z.object({CycleIDs:z.array(z.string()).nullish(),GroupID:z.string().nullish(),PhaseIDs:z.array(z.string()).nullish(),RequiredQuestIDs:z.array(z.string()).nullish(),PrerequisiteMode:Ff.nullish()}).passthrough(),Ml=z.object({Schedule:ge.nullish(),AccrueProgressWhenLocked:z.boolean().nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),Ol=z.object({Grant:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),Nf=z.object({QuestID:z.string().nullish(),Identity:Vf.nullish(),Linking:wl.nullish(),Availability:Ml.nullish(),Objectives:z.record(z.string(),zl).nullish(),Reward:Ol.nullish(),Presets:po.nullish()}).passthrough(),_f=z.object({CompletionID:z.string().nullish(),GroupID:z.string().nullish(),RequiredCompletedQuests:z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),jf=z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Gate:Z.nullish(),Milestones:z.record(z.string(),Fe).nullish(),Presets:po.nullish(),PointsToken:Kt.nullish()}).passthrough(),Wf=z.object({Milestones:z.record(z.string(),ai).nullish(),Linking:z.record(z.string(),wl).nullish(),Availability:z.record(z.string(),Ml).nullish(),Reward:z.record(z.string(),Ol).nullish(),Objectives:z.record(z.string(),z.record(z.string(),zl)).nullish()}).passthrough(),Qf=z.object({CycleID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:ge.nullish(),Milestones:z.record(z.string(),Fe).nullish(),Gate:Z.nullish(),PointsToken:Kt.nullish(),GroupCompletions:z.record(z.string(),_f).nullish(),Phases:z.record(z.string(),jf).nullish(),Presets:po.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Hi=z.object({Cycles:z.record(z.string(),Qf).nullish(),Quests:z.record(z.string(),Nf).nullish(),Presets:Wf.nullish()}).passthrough(),mt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var Kf={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},Hf=z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),$f={Never:"Never",OnRequest:"OnRequest",Always:"Always"},Jf=z.enum(["Never","OnRequest","Always"]).catch("Never"),Zf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},Yf=z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),Xf={GameLoop:"GameLoop"},eg={Raid:"Raid",Attack:"Attack"},tg=z.object({Title:z.string().nullish(),TitleKey:z.string().nullish(),Body:z.string().nullish(),BodyKey:z.string().nullish(),AnchorID:z.string().nullish(),HighlightTarget:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),UiHint:z.record(z.string(),z.string()).nullish()}).passthrough(),ig=z.object({Mode:Hf.nullish(),Triggers:z.array(ot).nullish(),TargetValue:z.number().nullish(),RequireAllTriggers:z.boolean().nullish()}).passthrough(),sg=z.object({Grant:H.nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),ng=z.object({TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),RandomActionType:z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),rg=z.object({Module:z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:ng.nullish(),MaxUses:z.number().nullish()}).passthrough(),og=z.object({Skippable:z.boolean().nullish(),TimeoutSeconds:z.number().nullish()}).passthrough(),ho=z.object({StepID:z.string().nullish(),Order:z.number().nullish(),Identity:tg.nullish(),Completion:ig.nullish(),Effects:sg.nullish(),Script:rg.nullish(),Policy:og.nullish()}).passthrough(),ag=z.object({DisplayName:z.string().nullish(),DisplayNameKey:z.string().nullish(),Description:z.string().nullish(),DescriptionKey:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),El=z.object({Schedule:ge.nullish(),Gate:Z.nullish(),RequiredFlowIDs:z.array(z.string()).nullish(),AutoStart:z.boolean().nullish(),StartTrigger:ot.nullish()}).passthrough(),Ul=z.object({Skippable:z.boolean().nullish(),SkippableFromOrder:z.number().nullish(),RestartPolicy:Jf.nullish(),ExpireAfterSeconds:z.number().nullish(),IsBlocking:z.boolean().nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),ql=z.object({Grant:H.nullish(),AutoClaim:z.boolean().nullish()}).passthrough(),lg=z.object({Availability:Q.nullish(),Policy:Q.nullish(),Reward:Q.nullish(),Steps:Q.nullish()}).passthrough(),ug=z.object({FlowID:z.string().nullish(),Identity:ag.nullish(),Availability:El.nullish(),Policy:Ul.nullish(),Steps:z.record(z.string(),ho).nullish(),Reward:ql.nullish(),Presets:lg.nullish()}).passthrough(),cg=z.object({BlockingFlowIDs:z.array(z.string()).nullish(),BlockedModules:z.array(z.string()).nullish(),BlockedActions:z.record(z.string(),z.array(z.string())).nullish(),BlockBeforeStart:z.boolean().nullish(),SkipLiftsBlock:z.boolean().nullish()}).passthrough(),pg=z.object({IsEnabled:z.boolean().nullish(),MaxActiveFlows:z.number().nullish(),Blocking:cg.nullish()}).passthrough(),dg=z.object({Availability:z.record(z.string(),El).nullish(),Policy:z.record(z.string(),Ul).nullish(),Reward:z.record(z.string(),ql).nullish(),Steps:z.record(z.string(),z.record(z.string(),ho)).nullish()}).passthrough(),Bl=z.object({Flows:z.record(z.string(),ug).nullish(),Settings:pg.nullish(),Presets:dg.nullish()}).passthrough(),hg=z.object({}).passthrough().transform(r=>r),Ll=z.object({FlowID:z.string(),Status:Yf,CurrentStepID:z.string().nullish(),CurrentStep:ho.nullish(),TotalSteps:z.number(),CompletedSteps:z.number(),CanSkip:z.boolean(),RewardClaimed:z.boolean(),RewardPending:z.boolean(),VariantID:z.string().nullish()}).passthrough(),$i=z.object({State:hg.nullish(),Flows:z.array(Ll).nullish(),UnlockedFeatures:z.array(z.string()).nullish()}).passthrough(),Et=z.object({Flow:Ll.nullish()}).passthrough(),Gl=z.object({FlowID:z.string().nullish(),Granted:M.nullish()}).passthrough(),Fl=z.array(Te(Et)),Vl=z.object({FlowID:z.string(),StepID:z.string(),Progress:z.number(),Target:z.number(),Completed: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 Ji(r){return Array.isArray(r)?r.filter(e=>e!==null).map(Ji):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,Ji(t)])):r}var Zi=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 Yi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Nl(r){return r===429||r>=500&&r<=599}function Xi(r,e=Math.random){let t=Math.min(500*Math.pow(2,r-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Ut(r){return new Promise(e=>setTimeout(e,r))}var _l=15e3;async function jl(r){try{let t=JSON.parse(await r.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(r.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Wl(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function Ql(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var mo=15,Kl=1e3,es=class{constructor(e=mo,t=()=>Date.now(),i=Ut){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]>=Kl;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(Kl-(e-this.starts[0])+5);}}};var mg=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function ui(r){if(!r)return null;let e=mg.exec(r);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new Ht(i),o=new Ht(s),c=o.minus(Ht.max(n,0));return c.lte(0)?null:{currencyID:t,required:o.toNumber(),available:n.toNumber(),missing:c.toNumber(),missingAmount:c.toFixed()}}var fg=12e3,gg=new Set(["RelatedEntityID"]);function yg(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[i,s]of Object.entries(e))gg.has(i)||(t[i]=s);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var Rg=z.object({Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().optional(),QuestProgress:z.array(lo).nullish(),TutorialProgress:z.array(Vl).nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish()}).passthrough(),ts=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Yi;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 Zi(e.throttleMs),this.pacer=new es(e.maxRequestsPerSecond??mo),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,s={}){let n=s.throttleKey??yg(e,t);if(!this.throttler.tryAcquire(n))return b("throttled","Throttled");if(!this.inflight.add(n))return b("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,c=JSON.stringify(t),h=s.ticket??null,R=s.silent??!1,V=s.timeoutMs??fg,ce=s.autoRetry??!0,Ae=!1,Re=!1,Ue=0;for(;;){let Dt;s.keepalive||await this.pacer.take();try{Dt=await this.doFetch(o,c,h,V,s.keepalive??!1);}catch{if(ce&&Ue<3){Ue++,await Ut(Xi(Ue));continue}return this.connectionFailure("Internet Connection Error",R)}let Xe=Dt.status;if(Xe>=200&&Xe<300){let re=!Re&&this.cryptoTopUpHandler!==null,ve=await this.parseSuccess(Dt,i,R,e,re);if(!ve.ok&&re){let pe=ui(ve.error);if(pe){if(Re=!0,await this.runTopUp(pe))continue;R||this.emitter.emit("error:global",ve.error);}}return ve}if(Xe===401){if(!Ae&&this.sessionRefreshHandler){Ae=!0;let re=null;try{re=await this.sessionRefreshHandler();}catch{re=null;}if(re){h=re;continue}}return this.emitter.emit("auth:unauthorized",void 0),b("unauthorized","Unauthorized")}if(Nl(Xe)){let re=Xe===429?await jl(Dt):null;if(re!==null&&re>_l)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(re/1e3)} s`,R);if(ce&&Ue<3){Ue++,await Ut(re!==null?Wl(re):Xe===429?Ql(Ue):Xi(Ue));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Xe})`,R)}let Si="";try{Si=await Dt.text();}catch{}if(Xe===409&&/operation in progress/i.test(Si)&&ce&&Ue<3){Ue++,await Ut(Xi(Ue));continue}return this.handleWebError(Si,Xe,R)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let o=new AbortController,c=setTimeout(()=>{o.abort();},s);try{let h={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(h.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:h,signal:o.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(c);}}async parseSuccess(e,t,i,s,n=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=Rg.safeParse(c);if(!h.success)return this.globalError("Malformed response envelope",i);if(!h.data.Success){let Re=h.data.Error??"Server returned Success=false",Ue=n&&ui(Re);return !i&&!Ue&&this.emitter.emit("error:global",Re),b("server",Re)}let R=h.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:h.data.StateEpoch??null,versions:R});let V=h.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);let ce=h.data.TutorialProgress;ce&&ce.length>0&&this.emitter.emit("tutorial:systemProgress",ce);let Ae=t.safeParse(h.data.Data);if(!Ae.success){let Re=t.safeParse(Ji(h.data.Data));Re.success&&(Ae=Re);}if(!Ae.success){let Re=`Validation error (${s}): ${Ae.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",Re),i||this.emitter.emit("error:global",Re),b("validation",Re)}return a(Ae.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),b("server","PLAY_ACCESS_REQUIRED");s=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),b("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),b("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),b("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 ci(r){return (typeof r=="string"?r:r.toISOString()).slice(0,10)}function vi(r){return `${ci(r)}T00:00:00.000Z`}function Hl(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function $l(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function yo(r,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;r.InventoryV2??={};let n=r.InventoryV2,o=i.toISOString(),c=new Map,h=new Map,R=new Map,V=new Map,ce=new Map,Ae=new Map,Re=new Map,Ue=new Map,Dt=e.Grant?.PremiumTiers??[],Xe=Dt.length;for(let re=0;;re++){let ve,pe;if(re===0)ve=e.Grant?.Standard?.Entries,pe=false;else if(re-1<Xe)ve=Dt[re-1]?.Resources?.Entries,pe=false;else if(re===1+Xe)ve=e.Consume?.Standard?.Entries,pe=true;else break;if(ve)for(let ae of ve){if(ae.Type==null)continue;let de=Math.max(0,ae.Amount??0);if(!(de<=0))switch(ae.Type){case "VirtualCurrency":{if(!ae.CurrencyID)continue;let he=pe?h:c;he.set(ae.CurrencyID,(he.get(ae.CurrencyID)??0)+de);break}case "CryptoCurrency":{if(!ae.CurrencyID)continue;let he=pe?V:R;he.set(ae.CurrencyID,(he.get(ae.CurrencyID)??new Ht(0)).plus(de));break}case "Item":{if(!ae.ItemID)continue;let he=Sg(t,ae.CatalogID,ae.ItemID),be=(he?he.IsStackable??true:true)?pe?Ae:ce:pe?Ue:Re;be.set(ae.ItemID,(be.get(ae.ItemID)??0)+de);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=c.size>0||h.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let re of new Set([...c.keys(),...h.keys()])){let ve=c.get(re)??0,pe=h.get(re)??0,ae=ve-pe,de=n.VirtualCurrencies[re];de?(de.Amount+=ae,de.UpdatedAt=o,de.Daily&&ci(de.Daily.PeriodStartUtc)===ci(i)?(de.Daily.Earned+=ve,de.Daily.Spent+=pe):de.Daily={PeriodStartUtc:vi(i),Earned:ve,Spent:pe}):n.VirtualCurrencies[re]={Amount:ae,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:vi(i),Earned:ve,Spent:pe}};}}if(s.ccChanged=R.size>0||V.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let re of new Set([...R.keys(),...V.keys()])){let ve=R.get(re)??new Ht(0),pe=V.get(re)??new Ht(0),ae=ve.minus(pe),de=n.CryptoCurrencies[re];de?(de.Amount=new Ht(de.Amount).plus(ae).toString(),de.UpdatedAt=o):n.CryptoCurrencies[re]={Amount:ae.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(s.itemsChanged=ce.size>0||Ae.size>0||Re.size>0||Ue.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let re=n.UnstackableItems,ve=new Set([...ce.keys(),...Ae.keys(),...Re.keys(),...Ue.keys()]);for(let pe of ve){let ae=(ce.get(pe)??0)-(Ae.get(pe)??0),de=(Re.get(pe)??0)-(Ue.get(pe)??0),he=ae+de,rt=n.Items[pe];rt?(ae!==0&&(rt.StackableAmount+=ae),de!==0&&(rt.UnstackableAmount+=de),he!==0&&(rt.TotalAmount+=he)):n.Items[pe]={StackableAmount:Math.max(0,ae),UnstackableAmount:Math.max(0,de),TotalAmount:Math.max(0,he)};}for(let[pe,ae]of Ue){if(ae<=0)continue;let de=Object.values(re).filter(he=>he.ItemID===pe&&he.EquippedSlot==null&&(he.ExpiresAt==null||new Date(he.ExpiresAt)>i)).sort(Cg).slice(0,ae).map(he=>he.ItemInstanceID);for(let he of de)delete re[he];}for(let[pe,ae]of Re){let de=xg(t,pe);for(let he=0;he<ae;he++){let rt=d();re[rt]={ItemInstanceID:rt,ItemID:pe,CatalogID:de,RemainingUses:1,AcquiredAt:o};}}}r.EventToken??={};let Si=r.EventToken;for(let re=0;;re++){let ve,pe;if(re===0)ve=e.Grant?.Standard?.EventTokens,pe=false;else if(re-1<Xe)ve=Dt[re-1]?.Resources?.EventTokens,pe=false;else if(re===1+Xe)ve=e.Consume?.Standard?.EventTokens,pe=true;else break;if(!(!ve||ve.length===0))for(let ae of ve){let de=ae.Address;if(!de||de.Type==null)continue;let he=ae.Amount??0;if(he<=0)continue;let rt=bg(Si,de.Type);if(!rt)continue;let be=rt[de.EntityID];be||(be={},rt[de.EntityID]=be),be.Balance??={Current:0,TotalEarned:0,TotalSpent:0},be.Daily??={Date:vi(i),TotalEarned:0},be.Meta??={};let xi=ae.Source&&ae.Source.length>0?ae.Source:"CustomAction";pe?(be.Balance.Current-=he,be.Balance.TotalSpent+=he):(be.Balance.Current+=he,be.Balance.TotalEarned+=he,ci(be.Daily.Date)!==ci(i)&&(be.Daily={Date:vi(i),TotalEarned:0}),be.Daily.TotalEarned+=he,be.Daily.EarnedBySource??={},be.Daily.EarnedBySource[xi]=(be.Daily.EarnedBySource[xi]??0)+he,be.Daily.TriggersBySource??={},be.Daily.TriggersBySource[xi]=(be.Daily.TriggersBySource[xi]??0)+1,be.Daily.LastTriggerBySource??={},be.Daily.LastTriggerBySource[xi]=o,be.Meta.JoinedAtUtc||(be.Meta.JoinedAtUtc=o),be.Meta.LastEarnedAtUtc=o),s.tokensChanged=true;}}return s}function Cg(r,e){return r.AcquiredAt!==e.AcquiredAt?r.AcquiredAt<e.AcquiredAt?-1:1:r.ItemInstanceID===e.ItemInstanceID?0:r.ItemInstanceID<e.ItemInstanceID?-1:1}function Sg(r,e,t){let i=r?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let n=s.Items?.[t];if(n)return n}}}function xg(r,e){let t=r?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function bg(r,e){switch(e){case "TimedEvent":return r.TimedEvent??={};case "Quest":return r.Quest??={};case "Leaderboard":return r.Leaderboard??={};case "CoopEvent":return r.CoopEvent??={};case "Season":return r.Season??={};default:return null}}function Jl(r,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},n=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let h of Object.values(s))h?.ItemID&&o.add(h.ItemID);for(let h of n){let R=r[h]?.ItemID;R&&o.add(R);}if(o.size===0)return i;let c=h=>n.has(h)||h in s;if(e){for(let[h,R]of Object.entries(e))h in r||c(h)||R&&o.has(R.ItemID)&&i.drop.push(h);for(let[h,R]of Object.entries(r))h in e||c(h)||R&&o.has(R.ItemID)&&(i.restore[h]=R);}return i}function Ro(r,e){return r===e||r.startsWith(`${e}:`)}var ss=class r{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let 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){r.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];r.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){r.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let s=yo(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let n=this.currentState,o={...n.InventoryV2?.UnstackableItems??{}},c=yo(n,e,i,s),h=Jl(o,n.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],ce=h.drop.length>0||Object.keys(h.restore).length>0||R.length>0||V.length>0;if(ce){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let Ae=n.InventoryV2.UnstackableItems;for(let Re of h.drop)delete Ae[Re];for(let[Re,Ue]of Object.entries(h.restore))Ae[Re]=Ue;for(let[Re,Ue]of R)Ae[Re]=Ue;for(let Re of V)delete Ae[Re];}this.emitResourceChanges(c,ce);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof Ht?t:new Ht(t),c=s===void 0?new Ht(0):s instanceof Ht?s:new Ht(s),h=i??new Date().toISOString(),R=n[e];R?(R.Amount=new Ht(R.Amount).plus(o).toString(),c.isZero()||(R.Frozen=new Ht(R.Frozen??0).plus(c).toString()),R.UpdatedAt=h):n[e]={Amount:o.toString(),Frozen:c.toString(),CreatedAt:h,UpdatedAt:h},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,n=s[e];n||(n={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=n),n.TotalPurchases+=t,n.LastPurchasedAt=i,i>=n.DailyResetUtc?(n.DailyPurchases=t,n.DailyResetUtc=Hl(i)):n.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let n=new Date().toISOString();for(let o of t)o.RuleID&&(s.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:n});}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));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let n=s.Cycles[t];if(!n)return;n.Quests??={};let o=n.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let n=s.PermanentQuests[e]??={QuestID:e,Status:i};n.Status=i,i==="Claimed"&&(n.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,n=t[s]??={};n.Balance??={Current:0,TotalEarned:0,TotalSpent:0},n.Balance.Current=i.PointsCurrent??0,n.Balance.TotalEarned=i.PointsTotalEarned??0,n.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(n.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let n=s.Steps[i.StepID]??={StepID:i.StepID};n.Progress=i.Progress,i.Completed&&(n.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let n=t.Cycles[i.CycleID];if(!n)continue;n.Quests??={},s=n.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let n=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};n.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(n.Completed=true,n.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(Ro(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[n,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((s?n!==s:!Ro(n,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let n=this.activeEventsCache?.ActiveEvents;if(n)for(let o of n)o.Type!==e||o.TimedEventID!==t||s&&o.TokenEntityID&&o.TokenEntityID!==s||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,s){if(!e)return;let n=this.ensureLeaderboardProgress(e);(n.ScoreCycleVersion??0)<s&&(n.ScoreEarnedThisCycle=0,n.ClaimedMilestoneIDs=[],n.BracketID=null),n.CurrentScore=t,n.ScoreEarnedThisCycle=(n.ScoreEarnedThisCycle??0)+i,n.ScoreCycleVersion=s,n.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let s=false;for(let n of Object.values(i))for(let o of Object.values(n.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[s,n]of Object.entries(e.ChangedInstances??{}))t[s]=n,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(i)){let n=i[s];n&&n.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,s,n){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,c={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")o.Private??={},o.Private[t]=c;else if(e==="Public")o.Public??={},o.Public[t]=c;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let s=i.BuildingStates.find(n=>n.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},n=s.PendingWithdrawals??[];t.size>0&&(n=n.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!n.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(n=[...n,i]),s.PendingWithdrawals=n;}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 ns=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 rs=class{user;config;constructor(e){this.user=new ss(e),this.config=new ns;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Dg(r){return r}var Pg=0,Ig=1500,vg=3,as=class{constructor(e,t,i=null,s="",n="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=s;this.loginMode=n;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 a(void 0);let i=Date.now(),s=[],n=[];for(let h of new Set(e)){let R=this.rules.get(h);if(R&&(t?.force||R.needsServer(i))){s.push(this.runRule(h,R));continue}(t?.force||!this.state.isStateFresh(h,t?.maxAgeMs))&&n.push(h);}let c=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(a(void 0))])).find(h=>!h.ok);return c&&!c.ok?c:a(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},Pg),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(s=>i=s);try{let s=this.state?await this.state.readStateSlice(e):a(void 0),n=s.ok?a(void 0):s;for(let o of t)o(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=os(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let R=this.fresh(s,i?.maxAgeMs);if(R)return a(R.data);let V=this.loginFailures.get(s);if(V)return this.loginFailures.delete(s),V;let ce=this.inflight.get(s);if(ce)return ce}let n=this.generation.get(s)??0,o=Date.now(),h=t().then(R=>{if(!R.ok)return R;let V=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:Co(e,R.data,V)}),R;let ce=this.entries.get(s);if(ce&&ce.storedAt>=o)return R;let Ae=Co(e,R.data,V);return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:Math.min(Ae??1/0,V+Ig)}),R}).finally(()=>{this.inflight.get(s)===h&&this.inflight.delete(s);});return this.inflight.set(s,h),h}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let s=t.Key?t.Key:void 0,n=os(i.view,s);if(!t.Success){this.loginFailures.set(n,b("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(n),i.apply(o.data,s),this.put(i.view,o.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let n=Zl({Name:s,Key:t});this.used.get(n)?.n!==this.session&&(this.used.set(n,{Name:s,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>vg||this.used.set(Zl(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(os(e,t))?.data}put(e,t,i){this.register(e);let s=os(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:Co(e,t,n)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===i||s.startsWith(`${i}|`))&&this.drop(s);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let s=Date.now();if(!(i.expiresAt!==null&&s>=i.expiresAt)&&!(t!==void 0&&s-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(s=>t.has(s))&&this.invalidate(i);}};function os(r,e){return e===void 0?r.key:`${r.key}|${e}`}function Zl(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function Co(r,e,t){let i=r.expiresAt?.(e)??null,s=r.ttlMs!==void 0?t+r.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var ls=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 Tg(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 Tg(r){return r!==null&&Object.values(ze).includes(r)}var Ag=8,kg=100,zg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,Yl=["GameLoop"];function wg(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var us=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=ze.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let s=this.authContext;if(!s)return c;let n=this.baseRequest();n.UserID=s.userID,n.ClientSessionTicket=s.clientSessionTicket,n.WalletAddress=e,n.NetworkID=t,i&&(n.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(n);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return c;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(i);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.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 b("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let s=await this.ctx.api.authentication.loginWithEmail(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(ze.Email);return n.ok&&this.keepEmailCredentials(e,t),n}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 s=await this.ctx.api.authentication.registerWithEmail(i);return s.ok?(this.pendingRegistration={email:e,password:t},a({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(ze.Email);return n.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,n}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?a(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 b("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(ze.Apple)):s}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=i,s.Platform=this.ctx.platform.getPlatform(),s.Device=this.ctx.platform.getDeviceModel(),s.DeviceID=this.ctx.platform.getDeviceID();let n=await this.ctx.api.authentication.loginWithWallet(s);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(ze.Wallet)):n}async loginWithSsoCode(e){if(!e)return b("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 b("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 s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=i,this.ctx.api.authentication.resetPassword(s)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==ze.None?e:ze.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let s=await this.ctx.api.authentication.refreshSession(i);return s.ok?(this.applyRefresh(s.data),"ok"):(wg(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case ze.Email:return this.loginWithEmail(t,i);case ze.Device:case ze.None:return this.loginWithDeviceID();case ze.Telegram:return this.loginWithTelegram();default:return Promise.resolve(b("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 n(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let s=await this.ctx.api.authentication.resolvePlatformGameSession(i);return s.ok?(this.applyAuthContext(s.data),this.platformGameSession=!0,s.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==ze.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===ze.None)return null;this.refreshing=true;try{return (await this.replay(e,this.sessionEmail||this.ctx.authStore.savedEmail,this.sessionPassword||this.ctx.authStore.savedPassword)).ok&&this.authContext?this.authContext.clientSessionTicket:null}catch{return null}finally{this.refreshing=false;}}logout(){this.authContext=null,this.playAccessStatus=null,this.forgetSession(),this.ctx.authStore.clear(),this.ctx.data.reset(),this.ctx.emitter.emit("auth:loggedOut",void 0);}static isValidEmail(e){return e.length>0&&zg.test(e)}static isValidPasswordLength(e){return e.length>=Ag&&e.length<=kg}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(Yl,Yl);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 Mg="idos:cfg",pi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Xl(t)}`:e&&e.length>0?`f:${Xl(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${Mg}:${this.titleId}:${e}`}};function Xl(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var eu="idos:loc",di=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[s,n]of Object.entries(t))typeof n=="number"&&n>0&&(i[s]=n);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 `${eu}:${this.titleId}:${e}`}versionsKey(){return `${eu}:${this.titleId}:versions`}};var Og="idos:sec",cs=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 `${Og}:${this.titleId}`}};var Eg="idos:state",ps=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,s){if(!(!e||!t))try{let n={e:t,v:i,s};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}keyOf(e){return `${Eg}:${this.titleId}:${e}`}};function Ug(r,e){if(!r)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return r;let i={};for(let[s,n]of Object.entries(r))t.has(s.toLowerCase())||(i[s]=n);return i}function So(r,e,t,i){let s={...r??{}};if(!e||!t||!i)return s;for(let[n,o]of Object.entries(t))i[n]===o&&n in e&&(s[n]=e[n]);return s}function qg(r){return {...r??{}}}function xo(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.StateEpoch:null}var ds=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let s=this.confirmedAt[e];return s===void 0?false:t===void 0||i-s<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=Ug(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 n=Object.keys(this.versions);this.reset(e),this.notify(n);}return}let i=Date.now(),s=[];for(let[n,o]of Object.entries(t)){let c=this.versions[n];c!==o&&(c!==void 0&&o===c+1?(this.versions[n]=o,this.confirmedAt[n]=i):(delete this.versions[n],delete this.confirmedAt[n]),s.push(n),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=qg(t);let s=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=s;this.dirty=true;let n=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&n.add(o);this.notify([...n]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[n,o]of Object.entries(t??{}))this.versions[n]!==o&&s.push(n),this.versions[n]=o,this.confirmedAt[n]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var tu=b("server","Title configuration is unavailable (CDN and API both failed)."),hs=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:d()}:null}get configCache(){return this.cache??=new pi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new di(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new cs(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new ds(new ps(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 c;let t=pi.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let n=await this.ctx.api.user.getClientState(e);if(!n.ok)return n;let o=await this.resolveTitleConfig(n.data,t,i,{Fields:e.TitleFields});return o==null?tu:(this.finishStateHandshake(n.data,s),await this.restoreSections(n.data.TitleConfigVersion,o),await this.applyClientState(n.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(n.data.Views),await this.applyLocalization(n.data.Localization),await this.flushState(s),n)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let n=this.stateStore.currentEpoch;n&&(e.KnownStateEpoch=n);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=So(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=xo(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,i,s){let n=e.TitleConfigVersion;if(i&&n&&i.v===n)return i.c;if(e.TitleConfigUrl){let c=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(c!=null)return n&&await this.configCache.write(t,n,c),c}let o=await this.fetchConfigFromApi(s);return o!=null?(n&&await this.configCache.write(t,n,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return c;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=pi.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let c$1=await this.ctx.api.user.getClientStateExcept(i);if(!c$1.ok)return c$1;let h=await this.resolveTitleConfig(c$1.data,s,n,{ExcludeFields:t??[]});return h==null?tu:(this.finishStateHandshake(c$1.data,o),await this.restoreSections(c$1.data.TitleConfigVersion,h),await this.applyClientState(c$1.data,h,e,t),this.ctx.cache.acceptLoginViews(c$1.data.Views),await this.applyLocalization(c$1.data.Localization),await this.flushState(o),c$1)}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let i=t,s={};for(let[n,o]of Object.entries(await this.sectionCache.read(e)))i[n]==null&&(s[n]=o);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((n,o)=>{i[n]!=null||o==null||(s[n]=o,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let n=await this.fetchLocalizationFromApi(t,s?.v??0);return n??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let n=s.data;if(n.NotModified)return null;let o=n.Entries??{},c=n.Version??0,h=n.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)):c}async getUserState(e){let t=this.baseRequest();if(!t)return c;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let n=So(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let o=i.sent??{},c$1=Object.entries(s.data.StateVersions??{}).filter(([R,V])=>o[R]!==V||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(n,c$1);let h=xo(s.data);return h&&(this.stateStore.afterSliceRead(h,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return c;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 c;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 c;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let s=this.baseRequest();if(!s)return c;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=i;let n=await this.ctx.api.user.addUsageTime(s);return n.ok&&this.ctx.emitter.emit("user:usageTimeAdded",n.data),n}async deleteUserAccount(){let e=this.baseRequest();if(!e)return c;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 c;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,s){let n=i?.includes("GameLoop")===true,o=s?.includes("GameLoop")===true,c=n?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 R=this.ctx.data.user.state;n&&R&&R.GameLoop==null&&(R.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 fs=class{constructor(e){this.ctx=e;}ctx;async convert(e,t,i,s,n,o){if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(n<=0)return b("client","Amount must be positive.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===dt.Crypto||i===dt.Crypto)return b("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return c;let c$1={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(n)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${s}_${d()}`},h=await this.ctx.api.currency.convert(c$1);if(h.ok){let R=h.data,V={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.SourceID,Amount:R.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.TargetID,Amount:R.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return h}async cryptoConvert(e,t,i,s,n,o){let c$1=n instanceof Ht?n:new Ht(n);if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(c$1.lte(0))return b("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===dt.Virtual&&i===dt.Virtual)return b("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===dt.Virtual&&!c$1.isInteger())return b("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return c;let h={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:c$1.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${s}_${d()}`},R=await this.ctx.api.currency.cryptoConvert(h);if(R.ok){let V=R.data,ce=[],Ae=[];if(V.SourceType===dt.Virtual&&ce.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===dt.Virtual&&Ae.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),ce.length>0||Ae.length>0){let Re={Consume:ce.length>0?{Standard:{Entries:ce}}:null,Grant:Ae.length>0?{Standard:{Entries:Ae}}:null};this.ctx.data.user.applyResourceOperation(Re,this.ctx.data.config.itemDefinitions);}V.SourceType===dt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new Ht(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===dt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new Ht(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return R}};var gs=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i,s){let n=e.trim();if(!n)return b("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:n,SelectedOptionID:i,CreditsConfirmationID:s,RelatedEntityID:`upgrade_item_${n}_${d()}`};t&&t.length>0&&(o.FodderInstanceIDs=[...t]);let c$1=await this.ctx.api.item.upgradeLevel(o);return c$1.ok&&!c$1.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(c$1.data.ItemInstanceID??n,c$1.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",c$1.data)),c$1}async upgradeLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let s of i.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var iu=z.object({OptionID:z.string().nullish(),Name:z.string().nullish(),Cost:Pt.nullish(),AllowedPlatforms:z.array(_i).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),le=z.record(z.string(),iu),Bg=z.object({Store:ji,Receipt:z.string(),Signature:z.string().nullish()}).passthrough();var Ti={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},me=z.object({ConfirmationID:z.string(),Url:z.string(),Status:z.string(),PriceCredits:z.number(),ExpiresAt:p}).passthrough(),su=z.object({Linked:z.boolean(),Credits:z.number(),TopUpUrl:z.string().nullish()}).passthrough(),Lg={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"},bo=z.object({ServerTimeUtc:p,OfferID:z.string(),Count:z.number(),Resources:M.nullish(),Inventory:K.nullish(),CreditsConfirmation:me.nullish()}),nu=z.array(Te(bo)),Gg=z.object({OfferID:z.string(),TotalPurchases:z.number(),DailyPurchases:z.number(),DailyResetUtc:p,LastPurchasedAt:p}),Fg=z.object({SlotKey:z.string(),InstanceKey:z.string(),OfferID:z.string().nullish(),Purchases:z.number(),LastPurchasedAt:p}),ru=z.object({Purchases:z.record(z.string(),Gg).nullish(),Rotations:z.record(z.string(),Fg).nullish()}).passthrough().transform(r=>r),vt=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),ys=z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Vg={Fixed:"Fixed",Title:"Title",Player:"Player"},Ng=z.object({OfferID:z.string().nullish(),Weight:z.number().nullish(),Gate:Z.nullish()}).passthrough(),ou=z.object({Mode:z.string().nullish(),OfferID:z.string().nullish(),Pool:z.array(Ng).nullish(),Salt:z.string().nullish(),PerInstanceCap:z.number().nullish()}).passthrough(),_g=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Rotation:Q.nullish()}).passthrough(),jg=z.object({SlotID:z.string().nullish(),Identity:vt.nullish(),Availability:ys.nullish(),Rotation:ou.nullish(),Presets:_g.nullish()}).passthrough(),Wg=z.object({Identity:Q.nullish(),Availability:Q.nullish()}).passthrough(),Qg=z.object({SectionID:z.string().nullish(),Identity:vt.nullish(),Availability:ys.nullish(),Slots:z.record(z.string(),jg).nullish(),UniqueOffersInSection:z.boolean().nullish(),Presets:Wg.nullish()}).passthrough(),au=z.object({Sections:z.record(z.string(),Qg).nullish()}).passthrough(),Kg=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Layout:Q.nullish()}).passthrough(),Hg=z.object({StoreID:z.string().nullish(),Identity:vt.nullish(),Availability:ys.nullish(),Layout:au.nullish(),Presets:Kg.nullish()}).passthrough(),lu=z.object({Options:le.nullish(),CompareAt:z.record(z.string(),Pt).nullish()}).passthrough(),uu=z.object({Grant:H.nullish()}).passthrough(),cu=z.object({Schedule:ge.nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),$g=z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish(),Availability:Q.nullish()}).passthrough(),Jg=z.object({OfferID:z.string().nullish(),Identity:vt.nullish(),Pricing:lu.nullish(),Reward:uu.nullish(),Availability:cu.nullish(),Presets:$g.nullish()}).passthrough(),Zg=z.object({Identity:z.record(z.string(),vt).nullish(),Availability:z.record(z.string(),ys).nullish(),Layout:z.record(z.string(),au).nullish(),Rotation:z.record(z.string(),ou).nullish(),Pricing:z.record(z.string(),lu).nullish(),Reward:z.record(z.string(),uu).nullish(),OfferAvailability:z.record(z.string(),cu).nullish()}).passthrough(),Rs=z.object({Stores:z.record(z.string(),Hg).nullish(),StoreOffers:z.record(z.string(),Jg).nullish(),Presets:Zg.nullish()}).passthrough(),Yg=z.object({PurchasedTotal:z.number(),PurchasedToday:z.number(),PurchasedThisRotation:z.number(),RemainingTotal:z.number().nullish(),RemainingToday:z.number().nullish(),IsFirstPurchaseAvailable:z.boolean(),SoldOut:z.boolean(),AvailableAtUtc:p.nullish()}).passthrough(),Xg=z.object({OptionID:z.string(),Name:z.string().nullish(),Cost:Pt.nullish(),CompareAtCost:Pt.nullish(),DiscountPercent:z.number().nullish(),IsFree:z.boolean(),IsAdPaid:z.boolean(),IsStorePaid:z.boolean(),IsCreditsPaid:z.boolean().nullish(),CreditsPrice:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),ey=z.object({OfferID:z.string(),Identity:vt.nullish(),PriceOptions:z.array(Xg).nullish(),Rewards:H.nullish(),State:Yg.nullish()}).passthrough(),ty=z.object({SlotID:z.string(),Identity:vt.nullish(),SortOrder:z.number(),RotationMode:z.string().nullish(),RotationInstanceKey:z.string().nullish(),RefreshesAtUtc:p.nullish(),RemainingThisRotation:z.number().nullish(),Offer:ey.nullish()}).passthrough(),iy=z.object({SectionID:z.string(),Identity:vt.nullish(),SortOrder:z.number(),Slots:z.array(ty).nullish()}).passthrough(),sy=z.object({StoreID:z.string(),Identity:vt.nullish(),SortOrder:z.number(),ScheduleInstanceKey:z.string().nullish(),ExpiresAtUtc:p.nullish(),Sections:z.array(iy).nullish()}).passthrough(),Cs=z.object({ServerTimeUtc:p,Stores:z.array(sy).nullish(),AdCreditBalance:z.number()}).passthrough(),Tt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},ny="OFFER_NOT_IN_ROTATION";var pu="Store",du={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=null;for(let t of r.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},Ss=class{constructor(e){this.ctx=e;e.cache.bindLoginView(du,{schema:Cs,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return b("client","OfferID is required.");if(t<1)return b("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return c;let n={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${s.userID}_${d()}`},o=await this.ctx.api.store.purchase(n);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;this.ctx.data.user.patchStorePurchase(e,t,c.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",c);}return o}async purchaseWithCredits(e,t=1,i={}){return await this.ctx.credits.pay(s=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:s}),{onConfirmation:i.onConfirmation,signal:i.signal,pollMs:i.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):c}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):c}async purchaseBatch(e){if(!e||e.length===0)return b("client","purchases is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||!n.Data.OfferID||(this.ctx.data.user.patchStorePurchase(n.Data.OfferID,n.Data.Count,n.Data.ServerTimeUtc),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(pu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(pu,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(du,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=s.RefreshesAtUtc;n&&(e===null||Date.parse(n)<Date.parse(e))&&(e=n);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 xs=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let i=await e(void 0);if(!i.ok||!i.data.CreditsConfirmation)return i;let s=i.data.CreditsConfirmation,n=()=>e(s.ConfirmationID);if(v()){let h=await w({titleID:this.ctx.settings.titleID,confirmationID:s.ConfirmationID});if(h.ok)return await n();if(h.error==="DECLINED")return b("server","CREDITS_CONFIRMATION_DECLINED");if(h.error==="NOT_ENOUGH_CREDITS")return b("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(s);let o=Math.max(1e3,t.pollMs??2500),c=Date.parse(s.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return b("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>c)return b("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(V=>setTimeout(V,o));let h=await this.ctx.store.getCreditsConfirmation(s.ConfirmationID);if(!h.ok)continue;let R=h.data.Status;if(R!==Ti.Pending)return R===Ti.Declined?b("server","CREDITS_CONFIRMATION_DECLINED"):R===Ti.Expired?b("server","CREDITS_CONFIRMATION_EXPIRED"):await n()}}};var bs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return c;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return c;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?a(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return b("client","Receipt is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},n=await this.ctx.api.purchase.validatePurchase(s);return n.ok&&this.applyValidation(n.data),n}async buyWithTelegramStars(e,t){if(!e)return b("client","productID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(i);return s.ok&&t?.open!==false&&this.ctx.platform.openInvoice(s.data.InvoiceLink),s}async validatePurchasesBatch(e){if(!e||e.length===0)return b("client","receipts is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let s of i.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var hu=3,ry=700,Ds=class{constructor(e){this.ctx=e;s()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return ui(e)}platformTopUp=async e=>{let t$1=this.ctx.auth.context?.userID;if(!t$1)return false;let i=await t({titleID:this.ctx.settings.titleID,userID:t$1,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<=hu;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===hu)break;await Ut(ry);}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===Ni.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!==Ni.CryptoCurrency||!i.CurrencyID)continue;let s=Number(i.Amount??0);if(!(s>0))continue;let n=this.cryptoBalance(i.CurrencyID);return n>=s?null:{currencyID:i.CurrencyID,required:s,available:n,missing:s-n}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var mu="Lootbox",Ps=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(mu,e);if(t){let n={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection(mu,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s,n){if(!e)return b("client","LootboxID is required.");if(t<1)return b("client","Count must be at least 1.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,CreditsConfirmationID:n,RelatedEntityID:`lootbox_${e}_${i??"default"}_${d()}`},c$1=await this.ctx.api.lootbox.open(o);if(c$1.ok&&!c$1.data.CreditsConfirmation){let h=c$1.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$1}};var Do="Reward";function Po(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Is=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(Do)?.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(Do,e);if(t){let n={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(Do,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 c;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${d()}`},s=await this.ctx.api.reward.claimDailyReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchDailyCalendarState(n.CalendarID,n.DailyState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",n);}return s}async collectIdleAccrual(e){if(!Po(e))return b("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${d()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let s=i.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return i}async claimComebackReward(e){if(!Po(e))return b("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${d()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return i}async claimReward(e){if(!Po(e))return b("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${d()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return i}};var vs="Tutorial",fu={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"]},Ts=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fu,{schema:$i,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(vs)?.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(vs,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(vs,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(fu,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return c;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}_${d()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return b("client","FlowID is required.");if(!t||t.length===0)return b("client","stepIDs is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${d()}`},n=await this.ctx.api.tutorial.completeStepsBatch(s);return n.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",n.data)),n}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 b("client","FlowID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${d()}`},s=await this.ctx.api.tutorial.claimFlowReward(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let s=e?.trim();if(!s)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:s},o=await t(n);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,s){let n=e?.trim(),o=t?.trim();if(!n)return b("client","FlowID is required.");if(!o)return b("client","StepID is required.");if(!this.ctx.auth.context)return c;let c$1={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:o};s?.relatedEntityID&&(c$1.RelatedEntityID=s.relatedEntityID);let h=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,R=await i(c$1);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(n,o,h,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(vs)?.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 As=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 b("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","campaignID is required.");if(!t)return b("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return c;s.CampaignID=e,s.WalletAddress=t,i&&(s.Amount=i);let n=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return n.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",n.data),n}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var qe=z.object({Username:z.string().nullish(),Country:z.string().nullish(),AvatarUrl:z.string().nullish(),Premium:z.boolean().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),BoardRank:z.number().nullish()}).passthrough();var oy={Global:"Global",Announcement:"Announcement",Group:"Group"},yu=z.enum(["Global","Announcement","Group"]).catch("Global"),ay={None:"None",Language:"Language",Region:"Region"},ly=z.enum(["None","Language","Region"]).catch("None"),uy={Anyone:"Anyone",Friends:"Friends"},cy=z.enum(["Anyone","Friends"]).catch("Anyone"),py={Reject:"Reject",Mask:"Mask"},dy=z.enum(["Reject","Mask"]).catch("Reject"),hy={Player:"Player",Publisher:"Publisher",System:"System"},my=z.enum(["Player","Publisher","System"]).catch("Player"),fy={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var gy=z.object({DisplayNameKey:z.string().nullish(),SortOrder:z.number().nullish(),IconPath:z.string().nullish(),JoinedByDefault:z.boolean().nullish()}).passthrough(),Ru=z.object({Gate:Z.nullish(),Schedule:ge.nullish()}).passthrough(),Cu=z.object({Gate:Z.nullish(),Limits:Ce.nullish(),MaxLength:z.number().nullish()}).passthrough(),Su=z.object({HotTailSize:z.number().nullish(),HistoryHours:z.number().nullish()}).passthrough(),yy=z.object({Availability:Q.nullish(),Write:Q.nullish(),Retention:Q.nullish()}).passthrough(),Ry=z.object({ChannelID:z.string().nullish(),Identity:gy.nullish(),Type:yu.nullish(),GroupSource:z.string().nullish(),Partitioning:ly.nullish(),Capacity:z.number().nullish(),Availability:Ru.nullish(),Write:Cu.nullish(),Retention:Su.nullish(),Presets:yy.nullish()}).passthrough(),Cy=z.object({IsEnabled:z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:cy.nullish(),Limits:Ce.nullish(),MaxLength:z.number().nullish(),HistoryHours:z.number().nullish(),MaxConversations:z.number().nullish()}).passthrough(),Sy=z.object({BlockedTerms:z.array(z.string()).nullish(),BlockedTermAction:dy.nullish(),MaxIgnoreListSize:z.number().nullish(),ReportsEnabled:z.boolean().nullish(),ReportLimits:Ce.nullish()}).passthrough(),xy=z.object({MinIntervalSeconds:z.number().nullish(),MaxMessagesPerPoll:z.number().nullish(),MaxHistoryPageSize:z.number().nullish()}).passthrough(),by=z.object({Availability:z.record(z.string(),Ru).nullish(),Write:z.record(z.string(),Cu).nullish(),Retention:z.record(z.string(),Su).nullish()}).passthrough(),xu=z.object({IsEnabled:z.boolean().nullish(),Channels:z.record(z.string(),Ry).nullish(),Direct:Cy.nullish(),Moderation:Sy.nullish(),Polling:xy.nullish(),Presets:by.nullish()}).passthrough(),Dy=z.object({LastReadAt:z.string().nullish(),LastReadMessageID:z.string().nullish(),Left:z.boolean().nullish()}).passthrough(),gu=z.object({LastAt:z.string().nullish(),DailyCount:z.number().nullish(),DailyResetUtc:z.string().nullish(),TotalCount:z.number().nullish(),LastTextHash:z.string().nullish()}).passthrough();z.object({MutedUntil:z.string().nullish(),MuteReason:z.string().nullish(),Ignored:z.array(z.string()).nullish(),Channels:z.record(z.string(),Dy).nullish(),Limits:z.record(z.string(),gu).nullish(),ReportLimits:gu.nullish()}).passthrough();var Io=z.object({RoomID:z.string().nullish(),SentAt:z.string().nullish(),MessageID:z.string().nullish()}).passthrough(),ks=z.object({RoomID:z.string().nullish(),ChannelID:z.string().nullish(),MessageID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderProfile:qe.nullish(),AuthorType:my.nullish(),Text:z.string().nullish(),SentAt:z.string().nullish()}).passthrough(),Py=z.object({ChannelID:z.string().nullish(),RoomID:z.string().nullish(),DisplayNameKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),Type:yu.nullish(),CanWrite:z.boolean().nullish(),WriteBlockedReason:z.string().nullish(),SlowModeSeconds:z.number().nullish(),MaxLength:z.number().nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),zs=z.object({Channels:z.array(Py).nullish(),PollIntervalSeconds:z.number().nullish(),MutedUntil:z.string().nullish(),MuteReason:z.string().nullish()}).passthrough(),Iy=z.object({RoomID:z.string().nullish(),Messages:z.array(ks).nullish(),NextCursor:Io.nullish(),UnreadCount:z.number().nullish(),ServedFromDatabase:z.boolean().nullish()}).passthrough(),bu=z.object({Rooms:z.array(Iy).nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),Du=z.object({RoomID:z.string().nullish(),Messages:z.array(ks).nullish(),NextBefore:Io.nullish()}).passthrough(),Pu=z.object({Message:ks.nullish(),Moderated:z.boolean().nullish()}).passthrough(),Iu=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:qe.nullish(),MaxLength:z.number().nullish()}).passthrough(),vy=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:qe.nullish(),LastMessage:ks.nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),vu=z.object({Conversations:z.array(vy).nullish()}).passthrough(),hi=z.object({Ignored:z.array(z.string()).nullish(),Cursor:Io.nullish(),Joined:z.boolean().nullish()}).passthrough(),Tu=z.object({ReportID:z.string().nullish(),AlreadyReported: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 Au="Chat",ku={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ku,{schema:zs,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(Au,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Au,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(ku,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return c;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 c;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let s of i.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return i}async getHistory(e,t,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),i&&(s.Limit=i),this.ctx.api.chat.getHistory(s)):c}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return c;s.ChannelID=e,s.Text=t,i&&(s.Locale=i);let n=await this.ctx.api.chat.sendMessage(s);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.Text=t;let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):c}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):c}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(i);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):c}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):c}async reportMessage(e,t,i,s){let n=this.ctx.authedRequest();return n?(n.RoomID=e,n.MessageID=t,n.Reason=i,s&&(n.Comment=s),this.ctx.api.chat.reportMessage(n)):c}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):c}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):c}resetCursors(){this.cursors.clear();}};var Ty={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},Ay=z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),ky={Player:"player",Title:"title",Creator:"creator"},mi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},zu=z.object({Configured:z.boolean().nullish(),PublicKey:z.string().nullish()}).passthrough(),zy=z.object({TitleID:z.string().nullish(),Topic:z.string().nullish()}).passthrough(),vo=z.object({EndpointHash:z.string().nullish(),Transport:Ay.nullish(),Locale:z.string().nullish(),Topics:z.array(zy).nullish()}).passthrough(),wu=z.object({Configured:z.boolean().nullish(),Subscriptions:z.array(vo).nullish()}).passthrough(),At={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var wy="IDOS_PLATFORM_PUSH_REQUEST",My="IDOS_PLATFORM_PUSH_RESPONSE",Oy=12e4;function Mu(r){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let s=false,n=h=>{s||(s=true,window.removeEventListener("message",o),clearTimeout(c),i(h));},o=h=>{let R=h?.data;!R||R.type!==My||R.requestId!==t||f.includes(h.origin)&&n(R.ok===true);},c=setTimeout(()=>n(false),Oy);window.addEventListener("message",o);for(let h of f)try{e.postMessage({type:wy,requestId:t,titleID:r},h);}catch{}})}var Ms=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),s=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,i.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return At.Unsupported;if(this.isEmbedded())return At.Embedded;if(!this.isSupported())return At.Unsupported;let t=Notification.permission;return t==="denied"?At.Blocked:t!=="granted"?At.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?At.Subscribed:At.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return b("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Mu(this.ctx.settings.titleID)?a({Where:"portal",Subscription:null}):b("client","The portal did not complete the subscription.");if(!this.isSupported())return b("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return b("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:Ey(t.PublicKey)}),c$1=this.ctx.authedRequest();if(!c$1)return c;let h=o.toJSON();c$1.PushEndpoint=h.endpoint,c$1.PushP256dh=h.keys?.p256dh,c$1.PushAuth=h.keys?.auth,c$1.PushTransport="WebPush",c$1.PushLocale=e.locale??navigator.language,c$1.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(c$1);return R.ok?(this.ctx.emitter.emit("push:subscribed",R.data),a({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return c;if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return b("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):c}async unsubscribeByHash(e){if(!e)return b("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return c;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 Ey(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return i}var Os=Object.freeze({}),Es=class{constructor(e){this.ctx=e;}ctx;table={...Os};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new di(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),s=this.lookup(i)??this.lookup(e);return s===void 0?this.onMissing(e):t?Uy(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Os},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 c;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:o}=i.data,c$1=null;if(o){let h=await this.loadTableFromApi(o);h.ok&&(c$1=h.data.table);}return this.table=n,this.fallbackTable=c$1,this.currentFallbackLocale=o,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:o,entryCount:Object.keys(n).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):c}reset(){this.table={...Os},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:d()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return c;t.Locale=e;let i=await this.cache.read(Ou(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let n=s.data,o=n.Locale??Ou(e),c$1=n.Version??0;if(n.NotModified){let R=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:R?.t??{...Os},fallbackLocale:n.FallbackLocale??null}}}let h=n.Entries??{};return c$1>0&&await this.cache.write(o,c$1,h),{ok:true,data:{locale:o,table:h,fallbackLocale:n.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let s=this.pluralCategory(i),n=`${e}.${s}`;if(this.lookup(n)!==void 0)return n;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 Uy(r,e){return r.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function Ou(r){return r.trim().replace(/_/g,"-").toLowerCase()}var To="Quest",qy={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:r=>{let e=Date.now(),t=null,i=[...Object.values(r.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(r.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let n=Date.parse(s??"");!Number.isNaN(n)&&n>e&&(t===null||n<t)&&(t=n);}return t}},Us=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let s=e.cache.configSection(To)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(s)){let c=Date.parse(n[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(To,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(To,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(qy,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return c;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let s=i.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","QuestID is required.");if(!this.ctx.auth.context)return c;let s=t&&t.trim().length>0?t.trim():void 0,n={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${d()}`},o=await this.ctx.api.quest.claimQuestReward(n);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 b("client","quests is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchQuestStatus(n.Data.QuestID,n.Data.CycleID,"Claimed"),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${d()}`},o=await this.ctx.api.quest.claimMilestoneReward(n);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 b("client","milestones is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchMilestoneClaimed(n.Data.CycleID,n.Data.MilestoneID),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${d()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(n);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 b("client","MetricID is required.");if(t<0)return b("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},n=await this.ctx.api.quest.addQuestProgress(s);return n.ok&&(this.ctx.data.user.patchQuestProgressUpdates(n.data.Updates),this.ctx.emitter.emit("quest:progressAdded",n.data)),n}};var Eu=z.object({}).passthrough().transform(r=>r);var By=z.object({Order:z.number().nullish(),Type:z.string().nullish(),DurationSec:z.number().nullish(),BonusMultiplier:z.number().nullish()}).passthrough(),Ly=z.object({Schedule:z.array(By).nullish(),RepeatCycle:z.boolean().nullish(),MaxCycles:z.number().nullish()}).passthrough(),Gy=z.object({IsActive:z.boolean().nullish(),CurrentPhaseEndUtc:p.nullish(),NextBonusStartUtc:p.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentPhaseIndex:z.number().nullish(),ActiveBonusMultiplier:z.number().nullish()}).passthrough(),Fy=z.object({Milestones:Q.nullish()}).passthrough(),Ao=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Category:z.string().nullish(),Token:Kt.nullish(),TokenSources:z.array(ot).nullish(),ClaimMode:z.string().nullish(),Milestones:z.record(z.string(),Fe).nullish(),Presets:Fy.nullish(),BonusWindow:Ly.nullish()}).passthrough(),Vy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Content:Ao.nullish(),ClaimGraceHours:z.number().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Ny=z.object({TimedEventID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:ge.nullish(),Content:Ao.nullish(),Events:z.array(Vy).nullish(),Gate:Z.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),_y=z.object({MaxConcurrentEvents:z.number().nullish()}).passthrough(),jy=z.object({Milestones:z.record(z.string(),ai).nullish()}).passthrough(),qs=z.object({Definitions:z.record(z.string(),Ny).nullish(),Settings:_y.nullish(),Presets:jy.nullish()}).passthrough(),Wy=z.object({Type:Ii,TimedEventID:z.string(),CurrentChainedEventID:z.string().nullish(),Content:Ao.nullish(),Progress:Eu.nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),NextMilestone:Fe.nullish(),BonusWindow:Gy.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentEventOrder:z.number().nullish(),TotalEventsInChain:z.number().nullish(),TokenEntityID:z.string().nullish()}).passthrough(),Bs=z.object({ActiveEvents:z.array(Wy).nullish()}).passthrough(),Uu=z.object({Tokens:z.record(z.string(),Eu).nullish()}),ko=z.object({Type:Ii.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),zo=z.object({Type:Ii.nullish(),LteID:z.string().nullish(),MilestoneID:z.string().nullish(),TokenEntityID:z.string().nullish(),Rewards:M.nullish(),Inventory:K.nullish()}),Qy=z.object({Type:Ii.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),wo=z.array(Te(zo)),qu=z.array(Te(ko)),Bu=z.array(Te(Qy)),ut={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Lu="TimedEvent",Gu={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:r=>{let e=null;for(let t of r.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Ls=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Gu,{schema:Bs,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(Gu,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return c;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(Lu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Lu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,s,n,o,c$1=1){if(!t)return b("client","LteID is required.");if(!i)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c;let h={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:o,RollMultiplier:c$1},R=await this.ctx.api.timedEvent.grantTokens(h);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",R.data)),R}async spendTokens(e,t,i){if(!t)return b("client","LteID is required.");if(i<=0)return b("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},n=await this.ctx.api.timedEvent.spendTokens(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",n.data)),n}async claimMilestone(e,t,i){if(!t||!i)return b("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},n=await this.ctx.api.timedEvent.claimMilestone(s);if(n.ok){let o=n.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 n}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c;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 c;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 b("client","spends is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return b("client","grants is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let s=i.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var Ky=z.object({UserID:z.string(),Score:j.nullish(),Rank:z.number().nullish(),LastScoreUpdateUtc:p.nullish(),IpHash:z.string().nullish(),PublicProfile:qe.nullish(),SeasonTierAtCycleEnd:z.number().nullish()}).passthrough(),Ai=z.object({LeaderboardID:z.string(),CycleVersion:z.number().nullish(),TotalParticipants:j.nullish(),CycleEndUtc:p.nullish(),TopUsers:z.array(Ky).nullish(),BracketID:z.string().nullish()}),Hy=z.object({CycleKey:z.string().nullish(),CycleEndUtc:p.nullish(),ClaimDeadlineUtc:p.nullish(),MilestoneTokensEarned:j.nullish(),ClaimableMilestoneIDs:z.array(z.string()).nullish(),CycleIndex:z.number().nullish(),ChainedEventID:z.string().nullish()}).passthrough(),Gs=z.object({LeaderboardID:z.string(),CurrentScore:j.nullish(),LastKnownRank:z.number().nullish(),HasUnclaimedReward:z.boolean().nullish(),UnclaimedRewardRank:z.number().nullish(),ScoreEarnedThisCycle:j.nullish(),MilestoneTokensEarned:j.nullish(),TokenEntityID:z.string().nullish(),NextMilestone:Fe.nullish(),HasUnclaimedMilestone:z.boolean().nullish(),GrantedPremiumTiers:z.record(z.string(),z.array(z.string())).nullish(),ClaimableGraceCycles:z.array(Hy).nullish()}),Fs=z.object({LeaderboardID:z.string(),NewScore:j,CycleVersion:z.number()}),Vs=z.object({ServerTimeUtc:p,LeaderboardID:z.string(),Rank:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Ns=z.object({ServerTimeUtc:p,LeaderboardID:z.string(),MilestoneID:z.string(),Resources:M.nullish(),Inventory:K.nullish()}),Fu=z.array(Te(Ai)),_s=z.array(Te(Gs)),Vu=z.array(Te(Vs)),Nu=z.array(Te(Ns)),_u=z.array(Te(Fs)),$y=z.object({LeaderboardID:z.string(),CycleReward:Te(Vs).nullish(),Milestones:z.array(Te(Ns)).nullish()}),ju=z.array($y),Jy=z.object({LeaderboardID:z.string(),Leaderboard:Te(Ai).nullish(),Progress:Te(Gs).nullish()}),Wu=z.array(Jy),Zy=z.string(),Qu=z.object({Rank:z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:ao.nullish()}).passthrough(),Yy=z.object({RankRewards:z.array(Qu).nullish()}).passthrough(),Xy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),eR=z.object({Milestones:Q.nullish(),RankRewards:Q.nullish()}).passthrough(),tR=z.object({LeaderboardID:z.string(),DisplayName:z.string().nullish(),ScoreDisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),IsEnabled:z.boolean().nullish(),ScoreAggregation:Zy.nullish(),Schedule:ge.nullish(),ChainEvents:z.array(Xy).nullish(),Gate:Z.nullish(),TopUsersLimit:z.number().nullish(),MinScoreToEnterTop:z.number().nullish(),BracketSize:z.number().nullish(),LinkedSeasonChainID:z.string().nullish(),RankRewards:z.array(Qu).nullish(),Milestones:z.record(z.string(),Fe).nullish(),Presets:eR.nullish(),MilestoneClaimMode:z.string().nullish(),MilestoneClaimGraceHours:z.number().nullish(),ScoreSources:z.array(ot).nullish()}).passthrough(),iR=z.object({Milestones:z.record(z.string(),ai).nullish(),RankRewards:z.record(z.string(),Yy).nullish()}).passthrough(),js=z.object({Definitions:z.record(z.string(),tR).nullish(),Presets:iR.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 Ku="Leaderboard",Hu={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"]},Ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Hu,{schema:_s,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Ku,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ku,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","LeaderboardID is required.");if(t<=0)return b("client","Score must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(i);if(s.ok){let n=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),n.NewScore,t,n.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",n);}return s}async submitScoreFromSource(e,t,i,s,n=1){if(!e)return b("client","LeaderboardID is required.");if(!t)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},c$1=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(c$1.ok){let h=c$1.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),h.NewScore,h.NewScore,h.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",h);}return c$1}async claimCycleReward(e){if(!e)return b("client","LeaderboardID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return i}async claimMilestone(e,t,i){if(!e||!t)return b("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},n=await this.ctx.api.leaderboard.claimMilestone(s);if(n.ok){let o=n.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 n}async getFriendsLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c;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(b("client","leaderboardIDs is required.")):this.ctx.cache.read(Hu,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return b("client","scores is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let n=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(n),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of s.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(n,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 b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let s of i.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var Mo=z.object({}).passthrough().transform(r=>r),Qs=z.object({SeasonChainID:z.string(),CycleIndex:z.number().nullish(),Season:z.lazy(()=>Yu).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:j.nullish(),UserState:Mo.nullish(),NextTier:z.lazy(()=>Zu).nullish()}).passthrough(),$u=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),AmountGranted:j.nullish(),NewStatusTokens:j.nullish(),OldTier:z.number().nullish(),NewTier:z.number(),TierUp:z.boolean().nullish()}),Oo=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),TierNumber:z.number(),Resources:M.nullish(),Inventory:K.nullish()}),Ju=Rt(Oo);var Zu=z.object({Tier:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredTokens:j.nullish(),TierReachedReward:H.nullish()}).passthrough(),Yu=z.object({SeasonID:z.string().nullish(),Order:z.number().nullish(),DurationSec:j.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(Zu).nullish(),LinkedCollectionID:z.string().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough();var sR=z.object({SeasonChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:ge.nullish(),Seasons:z.array(Yu).nullish(),GrantTokensAccessMode:z.string().nullish(),Gate:Z.nullish()}).passthrough(),Ks=z.object({Chains:z.record(z.string(),sR).nullish()}).passthrough(),Bt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Xu="Season",ec={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=Date.parse(r.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Hs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ec,{schema:Qs,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Xu,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Xu,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(ec,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(b("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","SeasonChainID is required.");if(t<=0)return b("client","Amount must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${d()}`},s=await this.ctx.api.season.grantStatusTokens(i);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","TierNumber must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${d()}`},s=await this.ctx.api.season.claimTierReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",n);}return s}async claimTierRewardsBatch(e,t){if(!e)return b("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return b("client","TierNumbers is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${d()}`},n=await this.ctx.api.season.claimTierRewardsBatch(s);if(n.ok){let o=n.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 n}};var tc="Premium",$s=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(tc,e);if(t){let n={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",n),a(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(tc,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(i);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,i="Default",s=1,n){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,CreditsConfirmationID:n,RelatedEntityID:`premium_purchase_${e}_${t}`},c$1=await this.ctx.api.premium.purchaseItemOrCurrency(o);if(c$1.ok&&!c$1.data.CreditsConfirmation){let h=c$1.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$1}async purchaseRealMoney(e,t,i,s,n,o,c$1,h){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!s||!n)return b("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return c;let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:o,PackageName:c$1,AppStoreEnvironment:h,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(R);if(V.ok){let ce=V.data;ce.Premium&&this.ctx.data.user.applyPremium(ce.Premium),this.ctx.data.user.applyResourceOperation(ce.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",ce);}return V}};var Js=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ItemInstanceID:z.string().nullish(),Level:z.number().nullish(),EquippedAt:p.nullish()}),Eo=z.object({CharacterID:z.string(),Level:z.number().nullish(),Experience:j.nullish(),Power:z.number().nullish(),StatLevels:z.record(z.string(),z.number()).nullish(),Equipment:z.record(z.string(),Js).nullish(),UpdatedAt:p.nullish()}).passthrough(),ic=z.object({Characters:z.record(z.string(),Eo).nullish()}),Uo=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),StatID:z.string(),StatLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),qo=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),NewLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),sc=z.object({ServerTimeUtc:p,CharacterID:z.string(),Equipment:z.record(z.string(),Js).nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),nc=z.object({ServerTimeUtc:p,CharacterID:z.string(),ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),nR=z.object({ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish()}),rc=z.object({ServerTimeUtc:p,Characters:z.record(z.string(),nR).nullish(),Inventory:K.nullish()}),Bo=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),Power:z.number().nullish(),Resources:M.nullish()}),oc=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),SkinID:z.string(),Resources:M.nullish(),Inventory:K.nullish(),Equipped:z.boolean().nullish(),EquipError:z.string().nullish(),Equipment:Js.nullish(),Power:z.number().nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish()}),ac=z.object({ServerTimeUtc:p,CharacterID:z.string(),SkinID:z.string(),Equipped:Js.nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),lc=z.object({ServerTimeUtc:p,CharacterID:z.string(),Cleared:z.boolean().nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),rR=z.object({SkinID:z.string(),IsDefault:z.boolean().nullish(),Misconfigured:z.string().nullish(),Owned:z.boolean().nullish(),OwnedCopies:z.number().nullish(),IsWorn:z.boolean().nullish(),MeetsRequirements:z.boolean().nullish(),SoldDirectly:z.boolean().nullish(),OnSale:z.boolean().nullish(),SaleEndsAtUtc:p.nullish(),GateOpen:z.boolean().nullish(),Purchasable:z.boolean().nullish(),PriceOptions:le.nullish()}),oR=z.object({CharacterID:z.string(),CharacterOpen:z.boolean().nullish(),DefaultSkinID:z.string().nullish(),WornSkinID:z.string().nullish(),Skins:z.array(rR).nullish()}),uc=z.object({ServerTimeUtc:p,Characters:z.record(z.string(),oR).nullish()}),cc=Rt(Bo),pc=Rt(qo),dc=Rt(Uo),Lo=z.object({RequiredStatID:z.string(),RequiredLevel:z.number()}).passthrough(),hc=z.object({StatID:z.string(),TypeID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),MaxLevel:z.number().nullish(),Weight:z.number().nullish(),PriceOptions:le.nullish(),CostCurve:_e.nullish(),BaseStatValue:z.number().nullish(),ValueCurve:_e.nullish(),RankCurve:_e.nullish(),Requirements:z.array(Lo).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),aR=z.object({SlotID:z.string(),MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Lo).nullish(),AllowedRarityIDs:z.array(z.string()).nullish(),AllowedItemTags:z.array(z.string()).nullish(),MinItemLevel:z.number().nullish(),MaxItemLevel:z.number().nullish()}).passthrough(),mc=z.object({Slots:z.record(z.string(),aR).nullish()}).passthrough(),fc=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Lore:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),lR=z.object({ClassID:z.string().nullish(),RarityID:z.string().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),uR=z.object({UnlockedByDefault:z.boolean().nullish(),PriceOptions:le.nullish()}).passthrough(),cR=z.object({Stats:Q.nullish(),Levels:Q.nullish(),Equipment:Q.nullish()}).passthrough(),gc=z.object({MaxRank:z.number().nullish(),FirstPaidRank:z.number().nullish(),PriceOptions:le.nullish(),CostCurve:_e.nullish()}).passthrough(),Go="@skin";function pR(r){return !!r&&r.startsWith("@")}var dR=z.object({CatalogID:z.string().nullish(),ItemID:z.string()}).passthrough(),hR=z.object({PriceOptions:le.nullish(),Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),mR=z.object({MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Lo).nullish()}).passthrough(),fR=z.object({SkinID:z.string().nullish(),Identity:fc.nullish(),Item:dR.nullish(),Sale:hR.nullish(),Requirements:mR.nullish()}).passthrough(),gR=z.object({DefaultSkinID:z.string().nullish(),Definitions:z.record(z.string(),fR).nullish()}).passthrough(),yR=z.object({CharacterID:z.string(),Identity:fc.nullish(),Classification:lR.nullish(),Unlock:uR.nullish(),Presets:cR.nullish(),Equipment:mc.nullish(),Stats:z.record(z.string(),hc).nullish(),RankLadder:gc.nullish(),RankStatCurve:_e.nullish(),StatMaxLevelCurve:_e.nullish(),Skins:gR.nullish()}).passthrough(),RR=z.object({Stats:z.record(z.string(),hc).nullish()}).passthrough(),CR=z.object({RankLadder:gc.nullish()}).passthrough(),SR=z.object({Equipment:mc.nullish()}).passthrough(),xR=z.object({Stats:z.record(z.string(),RR).nullish(),Levels:z.record(z.string(),CR).nullish(),Equipment:z.record(z.string(),SR).nullish()}).passthrough(),Zs=z.object({Definitions:z.record(z.string(),yR).nullish(),Presets:xR.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"},bR="SKIN_ALREADY_OWNED";var Fo="Character",Ys=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Fo)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,n])=>n?.Unlock?.UnlockedByDefault===true&&!i[n.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(Fo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Fo,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${d()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok&&!s.data.CreditsConfirmation){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",n);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return b("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${d()}`,SelectedOptionID:i?.selectedOptionID,CreditsConfirmationID:i?.creditsConfirmationID,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok&&!n.data.CreditsConfirmation){let o=n.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 n}async upgradeCharacterLevel(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${d()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok&&!s.data.CreditsConfirmation){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,o=>{o.Level=n.NewLevel,n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",n);}return s}async equipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(i);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(i);if(s.ok){let n=s.data;this.applyUnequipChangesLocally(e,n),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:n.ClearedSlotIDs??[],power:n.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${d()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok&&!n.data.CreditsConfirmation){let o=n.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 n}async equipSkin(e,t,i){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},n=await this.ctx.api.character.equipSkin(s);if(n.ok){let o=n.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return n}async unequipSkin(e){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let s=i.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):c}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,Go,t??null),n.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return b("client","characterIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level??=1,n.StatLevels??={},n.Equipment??={},s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level=s.NewLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(n.StatLevels??={},n.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.StatLevels??={},n.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[s,n]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,s,n);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let n of i)s.patchCharacterEquipment(e,n,null);s.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,s]of Object.entries(e.Characters??{})){for(let n of s.ClearedSlotIDs??[])t.patchCharacterEquipment(i,n,null);t.patchCharacter(i,n=>{s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=e.ServerTimeUtc;});}}};var yc="Match",Xs=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,o){let c$1=this.ctx.auth.context;if(!c$1)return c;let h={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:o,RelatedEntityID:`pvp_create_${c$1.userID}_${d()}`},R=await this.ctx.api.match.createMatch(h);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",R.data)),R}async updateMatch(e,t={}){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(i);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,s){let n=this.ctx.auth.context;if(!n)return c;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${d()}`},c$1=await this.ctx.api.match.instantBattle(o);if(c$1.ok){let h=c$1.data,R=this.ctx.data.config.itemDefinitions;if(h.Resources)this.ctx.data.user.applyResourceOperation(h.Resources,R);else if(h.ResourcesDual){let V=h.ResourcesDual;V.FromUserID===n.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,R):V.ToUserID===n.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",h);}return c$1}async saveStrategy(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let s=this.ctx.authedRequest();if(!s)return c;s.Page=e,s.PageSize=t,s.Statuses=i;let n=await this.ctx.api.match.getMyMatches(s);return n.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",n.data),n}async getAvailableMatches(e=0,t=20,i=false){let s=this.ctx.authedRequest();if(!s)return c;s.Page=e,s.PageSize=t,s.OnlyPublic=i;let n=await this.ctx.api.match.getAvailableMatches(s);return n.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",n.data),n}async getDefinitions(e){let t=this.ctx.cache.configSection(yc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(yc,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var Rc="Craft",en=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Rc,e);if(t){let n={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(Rc,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n,o){if(!e)return b("client","CraftID is required.");let c$1=this.ctx.auth.context;if(!c$1)return c;let h={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,CreditsConfirmationID:o,RelatedEntityID:`craft_${e}_${c$1.userID}_${d()}`},R=await this.ctx.api.craft.craft(h);return R.ok&&!R.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",R.data)),R}};var Lt=z.lazy(()=>z.union([z.string(),z.number(),z.boolean(),z.null(),z.array(Lt),z.record(z.string(),Lt)]));var Gt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Cc=z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),$t={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function ki(r){return r!==$t.Pending&&r!==$t.Running}var DR={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 PR(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var IR=z.object({Url:z.string().nullish(),ContentType:z.string().nullish(),Variant:z.string().nullish()}),vR=z.object({Code:z.string().nullish(),Message:z.string().nullish()}),tn=z.object({CreditsConfirmation:me.nullish(),GenerationID:z.string(),FeatureKey:z.string().nullish(),Modality:Cc.nullish(),Status:z.string(),Progress:z.number().nullish(),OutputText:z.string().nullish(),OutputJson:z.record(z.string(),Lt).nullish(),Assets:z.array(IR).nullish(),Error:vR.nullish(),Charge:M.nullish(),PlayerRefunded:z.boolean().nullish(),Reused:z.boolean().nullish(),Reward:M.nullish(),Context:z.record(z.string(),Lt).nullish(),PaymentSettled:z.boolean().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish()}),Sc=z.object({Data:z.array(tn).nullish(),Skip:z.number().nullish(),Limit:z.number().nullish()}),TR=z.object({Name:z.string().nullish(),Type:z.string().nullish(),Required:z.boolean().nullish(),MaxLength:z.number().nullish(),Enum:z.array(z.string()).nullish()}).passthrough(),AR=z.object({Modality:Cc.nullish(),Async:z.boolean().nullish(),Limits:Ce.nullish(),PriceOptions:le.nullish(),Tags:z.array(z.string()).nullish(),HistoryMessages:z.number().nullish(),MaxTokens:z.number().nullish(),AllowImages:z.boolean().nullish(),MaxInputImages:z.number().nullish(),MaxInputImageBytes:z.number().nullish(),AllowedImageTypes:z.array(z.string()).nullish(),MaxImages:z.number().nullish(),AllowEdit:z.boolean().nullish(),AllowReferenceImage:z.boolean().nullish(),MaxPromptChars:z.number().nullish(),LockBehavior:z.boolean().nullish(),ImageSize:z.string().nullish(),VideoSize:z.string().nullish(),VideoSeconds:z.number().nullish(),Voice:z.string().nullish(),AudioFormat:z.string().nullish(),MusicFormat:z.string().nullish(),ThreeDOperation:z.string().nullish(),ThreeDAnimations:z.array(z.string()).nullish(),Reward:H.nullish(),PromptVariables:z.array(TR).nullish(),AllowFreePrompt:z.boolean().nullish()}).passthrough(),xc=z.object({Enabled:z.boolean().nullish(),Features:z.record(z.string(),AR).nullish()}).passthrough(),Ne={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",kR=/^[A-Za-z0-9_-]{1,128}$/,zR=2e3,wR=5e3,MR=30*6e4;function OR(r,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,r);e?.addEventListener("abort",i,{once:true});})}var sn=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),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(bc,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,i){return this.generate(e,{Text:t},i,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):c}async getGeneration(e){if(!e)return b("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):c}isTerminal(e){return ki(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 b("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??MR),n=Math.max(1,t.intervalMs??zR),o=Math.max(n,t.maxIntervalMs??wR);for(;!ki(i.Status);){if(t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");if(Date.now()+n>s)return b("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await OR(n,t.signal),t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");let c=await this.pollFor(i);if(n=Math.min(o,Math.round(n*1.5)),!c.ok){if(c.reason==="connection")continue;return c}i=c.data,ki(i.Status)||t.onUpdate?.(i);}return a(i)}pollFor(e){switch(e.Modality){case Gt.Text:return this.getText(e.GenerationID);case Gt.Image:return this.getImage(e.GenerationID);case Gt.Audio:return this.getAudio(e.GenerationID);case Gt.Music:return this.getMusic(e.GenerationID);case Gt.Video:return this.getVideo(e.GenerationID);case Gt.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,s){if(!e)return b("client","FeatureKey is required.");let n=i?.relatedEntityID;if(n!==void 0&&!kR.test(n))return b("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,Variables:i?.variables,Context:i?.context,RelatedEntityID:n??d()},c$1=await s(o);return c$1.ok&&!c$1.data.CreditsConfirmation&&(await this.reconcileCharge(c$1.data,true),this.emitView(c$1.data)),c$1}async poll(e,t){if(!e)return b("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.GenerationID=e;let s=await t(i);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===$t.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===$t.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===$t.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Vo="Collection",nn=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(Vo),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let n=e.cache.configSection("Season");return Object.values(n?.Chains??{}).some(c=>(c?.Seasons??[]).some(h=>!!h?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Vo,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Vo,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,s){let n=this.ctx.auth.context;if(!n)return c;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${d()}`},c$1=await this.ctx.api.collection.openPack(o);return c$1.ok&&!c$1.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(c$1.data.Resources,c$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",c$1.data)),c$1}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return c;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${d()}`},o=await this.ctx.api.collection.openCollectionChest(n);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 c;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${d()}`},n=await this.ctx.api.collection.useCollectibleJoker(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",n.data)),n}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${d()}`},n=await this.ctx.api.collection.claimSetReward(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",n.data)),n}async claimSetRewardsBatch(e){if(!e||e.length===0)return b("client","sets is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${d()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,n,o=false){let c$1=this.ctx.auth.context;if(!c$1)return c;let h={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${c$1.userID}_${s}_${d()}`},R=await this.ctx.api.collection.sendTradeOffer(h);return R.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",R.data)),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${d()}`},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 c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${d()}`},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 c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${d()}`},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 c;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 c;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 ER=z.object({}).passthrough().transform(r=>r),UR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},qR={Active:"Active",Left:"Left",Replaced:"Replaced"},BR=z.object({ObjectIndex:z.number().nullish(),ObjectCompletionRewardClaimed:z.boolean().nullish()}).passthrough(),LR=z.object({UserID:z.string().nullish(),PublicData:qe.nullish(),BuildObjectsProgress:BR.nullish(),IsBot:z.boolean().nullish(),SpinsCount:z.number().nullish(),TokensSpent:z.number().nullish(),MemberStatus:z.string().nullish(),GrandPrizeClaimed:z.boolean().nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),GR=z.object({Index:z.number().nullish(),OwnerUserID:z.string().nullish(),CurrentProgress:z.number().nullish(),MaxProgress:z.number().nullish(),IsCompleted:z.boolean().nullish()}).passthrough(),FR=z.object({Objects:z.array(GR).nullish()}).passthrough(),Dc=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),CoopChainID:z.string().nullish(),CoopEventID:z.string().nullish(),CycleIndex:z.number().nullish(),Members:z.array(LR).nullish(),BuildObjectsState:FR.nullish(),Status:z.string().nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:z.number().nullish()}).passthrough(),Pc=z.object({CoopChainID:z.string(),CycleIndex:z.number().nullish(),EventOrder:z.number().nullish(),EventDef:z.lazy(()=>Ic).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:z.number().nullish()}).passthrough(),VR=z.string(),No=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Weight:z.number().nullish(),MinProgress:z.number().nullish(),MaxProgress:z.number().nullish()}).passthrough(),NR=z.object({Index:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxProgress:z.number().nullish(),CompletionReward:H.nullish()}).passthrough(),_R=z.object({Objects:z.array(NR).nullish(),PriceOptions:le.nullish(),SpinnerTable:z.array(No).nullish(),MaxSpinsPerCall:z.number().nullish()}).passthrough(),Ic=z.object({CoopEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),EventType:VR.nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),BuildObjects:_R.nullish(),GrandPrize:H.nullish()}).passthrough(),jR=z.object({CoopChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:ge.nullish(),Events:z.array(Ic).nullish(),Gate:Z.nullish()}).passthrough(),rn=z.object({ServerTimeUtc:p.nullish(),UserState:ER.nullish(),ActiveGroup:Dc.nullish()}),_o=z.object({ServerTimeUtc:p.nullish(),Group:Dc.nullish(),SecondsRemaining:j.nullish()}),vc=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),Resources:M.nullish(),ObjectIndex:z.number().nullish(),Sector:No.nullish(),RequestedSpins:z.number().nullish(),SpinsUsed:z.number().nullish(),Sectors:z.array(No).nullish(),ProgressDelta:z.number().nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),ObjectCompleted:z.boolean().nullish(),AllObjectsCompleted:z.boolean().nullish()}),jo=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Tc=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),on=z.object({Chains:z.record(z.string(),jR).nullish()}).passthrough(),ft={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Ac="CoopEvent",kc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},an=class{constructor(e){this.ctx=e;e.cache.bindLoginView(kc,{schema:rn,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ac,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ac,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return b("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;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(kc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","CoopChainID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let s=i.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,s,n){if(!e||!t)return b("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,CreditsConfirmationID:n,RelatedEntityID:d()},c$1=await this.ctx.api.coopEvent.spin(o);return c$1.ok&&!c$1.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(c$1.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",c$1.data)),c$1}async claimObjectReward(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c;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 b("client","GroupID is required.");if(!this.ctx.auth.context)return c;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 c;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 WR={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},QR={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},KR=z.object({NodeID:z.string().nullish(),Status:z.string().nullish(),ExecutionCount:z.number().nullish(),UnlockedAtUtc:p.nullish(),CompletedAtUtc:p.nullish(),LastExecutedAtUtc:p.nullish(),NextAvailableAtUtc:p.nullish(),LastExecutionRefID:z.string().nullish()}).passthrough(),HR=z.object({TrackID:z.string().nullish(),CurrentValue:z.number().nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),zc=z.object({OfferID:z.string().nullish(),InstanceKey:z.string().nullish(),SourceOfferVersion:z.number().nullish(),Status:z.string().nullish(),ActivatedAtUtc:p.nullish(),ExhaustedAtUtc:p.nullish(),ExpiredAtUtc:p.nullish(),DismissedAtUtc:p.nullish(),ShowCount:z.number().nullish(),LastShownAtUtc:p.nullish(),Nodes:z.record(z.string(),KR).nullish(),Tracks:z.record(z.string(),HR).nullish(),SelectedChoiceNodeID:z.string().nullish()}).passthrough(),$R=z.object({SlotID:z.string().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),ActiveOfferID:z.string().nullish(),ActiveOfferStartedAtUtc:p.nullish(),ActiveOfferExpiresAtUtc:p.nullish(),ActiveOffer:zc.nullish(),NextCycleStartsAtUtc:p.nullish(),LastUpdatedUtc:p.nullish(),DismissSkipAvailableAtUtc:p.nullish(),LastDismissedAtUtc:p.nullish(),ActiveScheduleInstanceKey:z.string().nullish()}).passthrough(),JR=z.object({TotalExecutions:z.number().nullish(),DailyExecutions:z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),ZR=z.object({TotalActivations:z.number().nullish(),TotalExhausted:z.number().nullish(),TotalExpired:z.number().nullish(),TotalDismissed:z.number().nullish(),TotalShows:z.number().nullish(),LastShownAtUtc:p.nullish(),LastActivatedAtUtc:p.nullish(),LastExhaustedAtUtc:p.nullish(),NodeCounts:z.record(z.string(),JR).nullish()}).passthrough(),YR=z.object({Slots:z.record(z.string(),$R).nullish(),OfferHistory:z.record(z.string(),ZR).nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),XR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},eC={Eq:"Eq",Gte:"Gte",Lte:"Lte"},tC=z.object({Order:z.number().nullish(),OfferID:z.string().nullish(),DurationSec:z.number().nullish(),DelayBeforeActivationSec:z.number().nullish()}).passthrough(),ln=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),wc=z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Mc=z.object({AllowDismissSkip:z.boolean().nullish(),DismissSkipDelaySec:z.number().nullish()}).passthrough(),iC=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Behaviour:Q.nullish()}).passthrough(),sC=z.object({SlotID:z.string().nullish(),Enabled:z.boolean().nullish(),Identity:ln.nullish(),Availability:wc.nullish(),Behaviour:Mc.nullish(),Queue:z.array(tC).nullish(),Presets:iC.nullish()}).passthrough(),nC=z.object({ViewsRequiredToComplete:z.number().nullish(),MaxViewsPerActivation:z.number().nullish(),GrantRewardsPerView:z.boolean().nullish()}).passthrough(),rC=z.object({RewardedVideo:nC.nullish()}).passthrough(),oC=z.object({TrackID:z.string().nullish(),Operator:z.string().nullish(),Value:z.number().nullish()}).passthrough(),aC=z.object({Identity:Q.nullish(),Graph:Q.nullish(),Milestones:Q.nullish()}).passthrough(),lC=z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish()}).passthrough(),uC=z.object({TrackID:z.string().nullish(),Amount:z.number().nullish(),RespectBounds:z.boolean().nullish()}).passthrough(),cC=z.object({TrackID:z.string().nullish(),DisplayName:z.string().nullish(),StartValue:z.number().nullish(),MinValue:z.number().nullish(),MaxValue:z.number().nullish(),ClampToMin:z.boolean().nullish(),ClampToMax:z.boolean().nullish(),HiddenFromUI:z.boolean().nullish()}).passthrough(),pC=z.object({RequiredCompletedNodeIDs:z.array(z.string()).nullish(),RequiredAnyCompletedNodeIDs:z.array(z.string()).nullish(),RequiredTracks:z.array(oC).nullish(),VisibleWhileLocked:z.boolean().nullish()}).passthrough(),Oc=z.object({Options:le.nullish()}).passthrough(),Ec=z.object({Grants:H.nullish(),TrackChanges:z.array(uC).nullish(),MilestonePoints:z.number().nullish()}).passthrough(),dC=z.object({NodeID:z.string().nullish(),Type:z.string().nullish(),Identity:ln.nullish(),Pricing:Oc.nullish(),Reward:Ec.nullish(),Action:rC.nullish(),UnlockRules:pC.nullish(),NextNodeIDs:z.array(z.string()).nullish(),ChoiceGroupID:z.string().nullish(),Limits:Ce.nullish(),HideWhenCompleted:z.boolean().nullish(),ExhaustOfferOnComplete:z.boolean().nullish(),Presets:lC.nullish()}).passthrough(),Uc=z.object({RootNodeIDs:z.array(z.string()).nullish(),Nodes:z.array(dC).nullish(),Tracks:z.array(cC).nullish(),ExhaustedWhenAllTerminalNodesCompleted:z.boolean().nullish()}).passthrough(),qc=z.object({Milestones:z.record(z.string(),Fe).nullish(),ClaimMode:z.string().nullish(),Token:Kt.nullish()}).passthrough(),Bc=z.object({OfferID:z.string().nullish(),Version:z.number().nullish(),Enabled:z.boolean().nullish(),Identity:ln.nullish(),Graph:Uc.nullish(),Milestones:qc.nullish(),Presets:aC.nullish()}).passthrough(),hC=z.object({Identity:z.record(z.string(),ln).nullish(),Availability:z.record(z.string(),wc).nullish(),Behaviour:z.record(z.string(),Mc).nullish(),Graph:z.record(z.string(),Uc).nullish(),Milestones:z.record(z.string(),qc).nullish(),Pricing:z.record(z.string(),Oc).nullish(),Reward:z.record(z.string(),Ec).nullish()}).passthrough(),Wo=z.object({Slots:z.record(z.string(),sC).nullish(),Offers:z.record(z.string(),Bc).nullish(),Presets:hC.nullish()}).passthrough(),Lc=z.object({DealOfferDefinitions:Wo.nullish()}),Gc=z.object({DealOffers:YR.nullish()}),mC=z.object({EntityID:z.string().nullish(),TotalEarned:z.number().nullish(),ClaimedIDs:z.array(z.string()).nullish(),ReachedUnclaimedIDs:z.array(z.string()).nullish()}).passthrough(),fC=z.object({SlotID:z.string().nullish(),SortOrder:z.number().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),OfferDef:Bc.nullish(),ActivationState:zc.nullish(),IsNewActivation:z.boolean().nullish(),ComputedExpiresAtUtc:p.nullish(),Cost:Pt.nullish(),Milestone:mC.nullish(),ScheduleInstanceKey:z.string().nullish()}).passthrough(),un=z.object({Slots:z.array(fC).nullish()}),Fc=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),NodeID:z.string().nullish(),NodeCompleted:z.boolean().nullish(),OfferExhausted:z.boolean().nullish(),Idempotent:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Vc=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),Nc=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),_c=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),jc=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),ClaimedIDs:z.array(z.string()).nullish(),Rejected:z.record(z.string(),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 gC="DealOffer",Wc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},cn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Wc,{schema:un,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(gC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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(Wc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${d()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,s){if(!e||!t)return b("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return c;let n=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:n??`deal_exec_${e}_${t}_${d()}`},c$1=await this.ctx.api.dealOffer.executeNode(o);return c$1.ok&&!c$1.data.CreditsConfirmation&&(c$1.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(c$1.data.Resources,c$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",c$1.data)),c$1}async recordShow(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${d()}`},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 b("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${d()}`},s=await this.ctx.api.dealOffer.claimMilestone(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${d()}`},n=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",n.data)),n}};var Qc="Referral",pn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Qc,e);if(t){let n={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",n),a(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Qc,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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=Qt.parseReferralCode(e)?.toUpperCase();if(!t)return b("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},n=await this.ctx.api.referral.activateReferralCode(s);if(n.ok){let o=n.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 n}async claimInviteReward(e){let t=e.trim();if(!t)return b("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},n=await this.ctx.api.referral.claimInviteReward(s);if(n.ok){let o=n.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 n}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return b("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},n=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(n.ok){let o=n.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 n}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return c;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 yC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Kc=z.enum(["System","Reward","Gift","Social"]).catch("System"),RC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},CC=z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),SC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},xC=z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),st={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},bC={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"},DC=100,PC=z.object({Subject:z.string().nullish(),Body:z.string().nullish()}).passthrough(),Hc=z.object({FeatureID:z.string().nullish(),Args:z.record(z.string(),z.string()).nullish(),Url:z.string().nullish(),Label:z.string().nullish()}).passthrough(),IC=z.object({Texts:z.record(z.string(),PC).nullish(),Category:Kc.nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Hc.nullish(),SenderName:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),vC=z.object({Enabled:z.boolean().nullish(),Grant:ue.nullish(),Cost:ue.nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:p.nullish(),SenderGate:Z.nullish(),TemplateID:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),TC=z.object({Type:z.string().nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxAmountPerGift:z.number().nullish()}).passthrough(),AC=z.object({Enabled:z.boolean().nullish(),AllowedResources:z.array(TC).nullish(),MaxEntriesPerGift:z.number().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:p.nullish(),FeePercent:z.number().nullish(),FeeCost:ue.nullish(),SenderGate:Z.nullish(),ExpirationDays:z.number().nullish(),TemplateID:z.string().nullish()}).passthrough(),$c=z.object({Enabled:z.boolean().nullish(),Capacity:z.number().nullish(),RewardLetterDays:z.number().nullish(),PlainLetterDays:z.number().nullish(),ClaimedRetentionDays:z.number().nullish(),DefaultLanguage:z.string().nullish(),Templates:z.record(z.string(),IC).nullish(),Gifts:z.object({Social:z.record(z.string(),vC).nullish(),Transfer:AC.nullish()}).passthrough().nullish(),Integrations:z.object({Leaderboard:z.boolean().nullish(),CoopEvent:z.boolean().nullish(),Season:z.boolean().nullish(),Referral:z.boolean().nullish()}).passthrough().nullish()}).passthrough(),kC=z.object({MessageID:z.string(),Source:CC,Category:Kc,TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Hc.nullish(),SenderName:z.string().nullish(),SenderUserID:z.string().nullish(),SenderAvatarUrl:z.string().nullish(),SenderNote:z.string().nullish(),Rewards:H.nullish(),HasRewards:z.boolean().nullish(),IsTransfer:z.boolean().nullish(),SentAt:p,ExpiresAt:p.nullish(),ReadAt:p.nullish(),ClaimedAt:p.nullish()}).passthrough(),zC=z.object({MessageID:z.string(),Module:xC,Key:z.string(),TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish()}).passthrough(),Qo=z.object({ID:z.string(),Error:z.string().nullish()}).passthrough(),Jc=z.object({ServerTimeUtc:p.nullish(),Messages:z.array(kC).default([]),NextCursor:z.string().nullish(),PendingRewards:z.array(zC).nullish(),UnreadCount:z.number().nullish(),UnclaimedCount:z.number().nullish(),DeliveredNow:z.number().nullish()}).passthrough(),dn=z.object({ServerTimeUtc:p.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Ko=z.object({ServerTimeUtc:p.nullish(),AffectedCount:z.number().default(0),Failed:z.array(Qo).default([]),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),wC=z.object({MessageID:z.string(),Rewards:ue.nullish()}).passthrough(),hn=z.object({ServerTimeUtc:p.nullish(),Claimed:z.array(wC).default([]),Failed:z.array(Qo).default([]),Resources:M.nullish(),Inventory:K.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Zc=z.object({ServerTimeUtc:p.nullish(),GiftID:z.string().nullish(),Sent:z.array(z.string()).default([]),Failed:z.array(Qo).default([]),Resources:M.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:p.nullish()}).passthrough(),Yc=z.object({ServerTimeUtc:p.nullish(),MessageID:z.string().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish(),RecipientReceives:ue.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:p.nullish(),IdempotentReplay:z.boolean().nullish()}).passthrough(),Xc=z.object({ServerTimeUtc:p.nullish(),ResetsAt:p.nullish(),Social:z.record(z.string(),z.object({IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ReceivedInPeriod:z.number().default(0),SentTo:z.array(z.string()).default([]),ResetsAt:p.nullish()}).passthrough()).default({}),Transfer:z.object({Enabled:z.boolean().default(false),IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ResetsAt:p.nullish()}).passthrough().nullish()}).passthrough();var Ho="Mailbox",$o={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},mn=class{constructor(e){this.ctx=e;e.cache.bindLoginView($o,{schema:dn,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($o,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Ho)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Ho,e);if(t)return a(t);let i=this.request();if(!i)return c;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(Ho,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return c;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($o,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return c;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 c;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 b("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):c}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return b("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):c}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):c}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 c;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return b("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return b("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return c;let n=await this.ctx.api.mailbox.sendGift(s);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",n.data)),n}async sendTransfer(e,t,i){if(!e?.trim())return b("client","RecipientUserID is required.");if(!i?.requestID?.trim())return b("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return c;let n=await this.ctx.api.mailbox.sendTransfer(s);return n.ok&&(n.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(n.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",n.data)),n}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):c}};var fn={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},Jo="idos-app",ep=z.object({ServerTimeUtc:z.string().nullish(),Allowed:z.boolean(),DenyReason:z.string().nullish(),Message:z.string().nullish(),RetryAfterSeconds:z.number().nullish(),RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),AdUnitID:z.string().nullish(),Type:z.string().nullish(),ExpiresAtUtc:z.string().nullish(),CreditsToAward:z.number().nullish(),RequiresServerSideVerification:z.boolean().nullish()}),tp=z.object({ServerTimeUtc:z.string().nullish(),RequestID:z.string().nullish(),Status:z.string(),CreditsAwarded:z.number().nullish(),RetryAfterSeconds:z.number().nullish(),ExpiresAtUtc:z.string().nullish(),AlreadyProcessed:z.boolean().nullish(),GrantedWithoutSsv:z.boolean().nullish(),Resources:M.nullish()});var Zo={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},MC=5*6e4;function gn(){return s()}async function Yo(r){let e=await j$1(Zo.request,Zo.response,{titleID:r.titleID,userID:r.userID,requestID:r.requestID,placementID:r.placementID,adUnitID:r.adUnitID??null},{answerTimeoutMs:MC});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var OC=new Set(["CANCELLED","DECLINED","CLOSED"]),EC=45e3,UC=r=>new Promise(e=>setTimeout(e,r)),yn=class{constructor(e){this.ctx=e;}ctx;get available(){return gn()}async showRewarded(e){if(!gn())return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let i=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!i.ok)return {status:"unavailable",reason:i.error};let s=i.data;if(!s.Allowed)return {status:"denied",reason:s.DenyReason??void 0,retryAfterSeconds:s.RetryAfterSeconds??void 0};if(s.ProviderID!==Jo||!s.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let n=await Yo({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:s.RequestID,placementID:e,adUnitID:s.AdUnitID});return n.ok?this.awaitReward(s.RequestID,n.via):{status:OC.has(n.error??"")?"cancelled":"unavailable",reason:n.error}}async awaitReward(e,t){let i=Date.now()+EC;for(;;){let s=this.ctx.authedRequest();if(!s)return {status:"pending",via:t};let n=await this.ctx.api.advertising.completeView({...s,RequestID:e});if(n.ok&&n.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:n.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((n.ok?n.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>i)return {status:"pending",via:t,reason:n.ok?void 0:n.error};await UC(o);}}};var qC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},BC={Title:"Title",Platform:"Platform"},ip=z.object({UserID:z.string(),PublicData:qe.nullish(),Source:z.enum(["Title","Platform"]).nullish()}),zi=z.object({Friends:z.array(ip).nullish()}),LC=z.object({FriendsCount:z.number().nullish(),IncomingRequestsCount:z.number().nullish(),OutgoingRequestsCount:z.number().nullish()}),wi=z.object({TargetUserID:z.string().nullish(),Status:z.string().nullish(),Target:ip.nullish(),Counters:LC.nullish()}),GC={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},FC={Like:"Like",Favorite:"Favorite"},VC={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},NC={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},_C={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},jC=z.object({Key:z.string().nullish(),DisplayName:z.string().nullish(),AvatarUrl:z.string().nullish()}).passthrough(),WC=z.object({Id:z.string(),Verb:z.string().nullish(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),Count:z.number().nullish(),LastActors:z.array(jC).nullish(),Payload:z.object({Title:z.string().nullish(),Excerpt:z.string().nullish(),ImageUrl:z.string().nullish()}).passthrough().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),OccurredAt:p.nullish(),OwnerImpact:M.nullish(),IsBlocked:z.boolean().nullish(),TargetObjectName:z.string().nullish()}).passthrough(),sp=z.object({Items:z.array(WC).nullish(),HasMore:z.boolean().nullish(),NextBeforeUpdatedAt:z.string().nullish(),NextBeforeID:z.string().nullish(),UnreadCount:z.number().nullish(),SeenAt:p.nullish()}).passthrough(),Mi=z.object({UnreadCount:z.number().nullish(),SeenAt:p.nullish()}).passthrough(),QC=z.object({Likes:z.number().nullish(),Favorites:z.number().nullish(),Followers:z.number().nullish(),Following:z.number().nullish(),Comments:z.number().nullish(),Replies:z.number().nullish(),Posts:z.number().nullish(),Dislikes:z.number().nullish()}).passthrough(),Ft=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Counts:QC.nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish(),Following:z.boolean().nullish(),Blocked:z.boolean().nullish()}).passthrough(),np=z.object({Items:z.array(Ft).nullish()}).passthrough(),Xo={HasMore:z.boolean().nullish(),NextCursorAt:z.string().nullish(),NextCursorID:z.string().nullish()},KC=z.object({UserID:z.string(),PublicData:qe.nullish(),Mutual:z.boolean().nullish(),Since:p.nullish()}).passthrough(),Rn=z.object({Items:z.array(KC).nullish(),...Xo}).passthrough(),HC=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Kind:z.string().nullish(),At:p.nullish()}).passthrough(),rp=z.object({Items:z.array(HC).nullish(),...Xo}).passthrough(),Cn=z.object({CommentID:z.string(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),ParentCommentID:z.string().nullish(),AuthorUserID:z.string().nullish(),AuthorPublicData:qe.nullish(),Text:z.string().nullish(),Status:z.string().nullish(),Pinned:z.boolean().nullish(),CreatedAt:p.nullish(),EditedAt:p.nullish(),Likes:z.number().nullish(),Replies:z.number().nullish(),Liked:z.boolean().nullish(),IsMine:z.boolean().nullish()}).passthrough(),op=z.object({Items:z.array(Cn).nullish(),...Xo,TotalCount:z.number().nullish()}).passthrough(),ap=z.object({CommentID:z.string().nullish(),Deleted:z.boolean().nullish()}).passthrough(),lp=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish(),AutoHidden:z.boolean().nullish()}).passthrough(),up=z.object({CommentsEnabled:z.boolean().nullish(),CommentableTypes:z.array(z.string()).nullish(),CommentMaxLength:z.number().nullish(),CommentMaxLinks:z.number().nullish()}).passthrough(),$C="FRIENDS_FROM_PLATFORM",JC={Off:"Off",Default:"Default",Always:"Always"},ZC={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},cp=z.object({Profile:z.enum(["Off","Default","Always"]).nullish(),Friends:z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:z.boolean().nullish()}).passthrough(),Se={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 ea={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Sn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ea,{schema:Mi,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 c;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 c;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 b("client","TargetUserID is required.");if(!this.ctx.auth.context)return c;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 b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c;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 b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c;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 b("client","FriendUserID is required.");if(!this.ctx.auth.context)return c;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 c;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(ea,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return c;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 c;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(ea,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)):c}async getEntityStates(e,t){if(!t?.length)return b("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):c}async addComment(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i?.trim())return b("client","Text is required.");n.Text=i,n.ParentCommentID=s;let o=await this.ctx.api.social.addComment(n);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return b("client","CommentID is required.");if(!t?.trim())return b("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return c;i.CommentID=e,i.Text=t;let s=await this.ctx.api.social.editComment(i);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return b("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=i.parentCommentID,this.applyPage(s,i.cursor,i.limit),this.ctx.api.social.getComments(s))}async report(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i)return b("client","ReportReason is required.");n.ReportReason=i,n.ReportComment=s;let o=await this.ctx.api.social.report(n);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,s){let n=this.targetRequest(t,i);if("ok"in n)return n;n.ReactionKind=s;let o=await this.ctx.api.social[e](n);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):c}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 b("client","EntityType is required.");if(!t)return b("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):c}};var pp="TimedBoost";function YC(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var xn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(pp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(pp,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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(!YC(i))return b("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${i}_${d()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok&&!n.data.CreditsConfirmation){let o=n.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 n}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return c;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 zt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},XC={Client:"Client",Server:"Server",System:"System"},eS=z.enum(["Client","Server","System"]).catch("Client"),tS=z.object({Value:z.string().nullish(),UpdatedAt:p.nullish(),Version:z.number().nullish(),LastWriter:eS.nullish(),ExpiresAt:p.nullish()}).passthrough(),bn=z.record(z.string(),tS),dp=z.object({Version:z.number().nullish(),Private:bn.nullish(),Public:bn.nullish(),ReadOnly:bn.nullish()}),ta=z.object({UserID:z.string().nullish(),Version:z.number().nullish(),Public:bn.nullish()}),ia=z.object({ServerTimeUtc:p.nullish(),Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:p.nullish()}),iS=z.object({Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:p.nullish()}),hp=z.object({ServerTimeUtc:p.nullish(),Results:z.array(iS).nullish()}),mp=z.object({ServerTimeUtc:p.nullish(),DeletedCount:z.number().nullish()}),fp=z.object({Results:z.array(ta).nullish(),NotFoundUserIDs:z.array(z.string()).nullish()}),sS={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},nS=z.enum(["String","Int","Bool","Json"]).catch("String"),rS=z.object({KeyID:z.string(),Bucket:z.string().nullish(),ValueType:nS.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),Dn=z.object({Keys:z.record(z.string(),rS).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),gt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var oS="UserCustomData";function gp(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Pn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(oS,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,zt.Private)}async setPublicData(e,t){return this.setData(e,t,zt.Public)}async setData(e,t,i){let s=e.trim();if(!gp(s))return b("client",'KeyID is required and must not contain "." or "$".');if(t==null)return b("client","Value is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},c$1=await(i===zt.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(c$1.ok){let h=c$1.data;this.ctx.data.user.patchUserCustomDataKey(i,h.KeyID,t,h.Version??0,h.ExpiresAt),this.ctx.emitter.emit(i===zt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",h);}return c$1}async deleteKey(e,t){let i=e.trim();if(!gp(i))return b("client",'KeyID is required and must not contain "." or "$".');if(t!==zt.Private&&t!==zt.Public)return b("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},n=await this.ctx.api.userCustomData.deleteKey(s);return n.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),n}async batchSet(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let n=s.Bucket??zt.Private,o=e.find(c=>c.Bucket===n&&c.KeyID===s.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(n,s.KeyID,o.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return b("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return c;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 aS="TitleCustomDataDefinitions",yp=50;function lS(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function sa(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function uS(r){let e={};for(let[t,i]of Object.entries(r))sa(i)||(e[t]=i);return e}var In=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(aS,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return c;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(n=>n.trim()).filter(n=>n.length>0);if(!t.length)return b("client","At least one KeyID is required.");if(t.some(n=>!lS(n)))return b("client",'KeyID must not contain "." or "$".');if(t.length>yp)return b("client",`At most ${yp} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return c;i.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!sa(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!sa(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 vn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 c;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 c;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var cS=15,pS="GameLoop",Rp="BoardDefinition",Tn=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 c;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(pS,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(Rp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),a(i);let s=this.ctx.authedRequest();if(!s)return c;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(Rp,n.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n.data)),n}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return b("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return c;i.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let n=s.data,o=$l(new Date,cS);this.ctx.data.user.patchBoardState(c=>{c.Position=n.NewPosition,c.CyclesCompleted=(c.CyclesCompleted??0)+(n.CyclesCompletedDelta??0),c.LastRollAtUtc=new Date().toISOString(),n.ActionRequired&&n.ActionData?c.Pending={Type:n.ActionRequired,TargetUserID:n.ActionData.TargetUserID,TargetPublicData:n.ActionData.PublicData,TargetBuildingStates:n.ActionData.TargetBuildingStates??void 0,TargetHasShield:n.ActionData.TargetHasShield??void 0,RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:o}:n.SpecialModeOffer&&(c.Pending={Type:"SPECIAL",RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:n.SpecialModeOffer.ModeID??void 0,Choices:n.SpecialModeOffer.Choices??void 0}});}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),n.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",n);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.IsBotTarget&&n.Operation?this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs):!n.IsBotTarget&&n.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(n.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",n);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return b("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${d()}`},n=await this.ctx.api.gameLoop.boardLoopRaid(s);if(n.ok){let o=n.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 n}async boardLoopRaidFast(e){if(!e.length)return b("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(s.ok){let n=s.data;n.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(n)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",n);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return b("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let n=s.data;n.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(n.BuiltIndex,o=>{n.NewLevel!=null&&(o.Level=n.NewLevel),o.IsDamaged=false,n.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",n);}return s}async boardSpecialChoose(e,t,i){if(!e)return b("client","choiceID must not be empty.");let s=this.ctx.auth.context;if(!s)return c;let n={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:i,RelatedEntityID:`special_choose_${s.userID}_${d()}`},o=await this.ctx.api.gameLoop.boardSpecialChoose(n);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(R=>{R.ChoiceID=e,R.ChosenMode=c.Mode??"Timed",R.StartedAtUtc=c.StartedAtUtc??null,R.DurationSeconds=c.DurationSeconds??null,R.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 c;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let n=s.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=n.AdViewsUsed??0,o.AccumulatedMultiplier=n.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",n);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${d()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",n);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 b("client","milestoneID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return c;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 c;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 An=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let n=e.trim();if(!n)return b("client","FunctionName is required.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},c$1=await this.ctx.api.cloudCode.execute(o);return c$1.ok&&this.ctx.emitter.emit("cloudCode:executed",c$1.data),c$1}};var Cp=z.object({ServerTimeUtc:p,SourceType:ri,SourceID:z.string(),TargetType:ri,TargetID:z.string(),SourceSpent:j,FeeAmount:j,RateApplied:Y,TargetCredited:j}),Sp=z.object({ServerTimeUtc:p,SourceType:ri,SourceID:z.string(),TargetType:ri,TargetID:z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),kn={Convert:"Convert",CryptoConvert:"CryptoConvert"},dS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},xp=z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),hS={Automatic:"Automatic",Manual:"Manual"},mS=z.enum(["Automatic","Manual"]).catch("Automatic"),fS=z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),InitialDeposit:z.number().nullish(),MinBalance:z.number().nullish(),MaxBalance:z.number().nullish(),DailyEarnLimit:z.number().nullish(),DailySpendLimit:z.number().nullish()}).passthrough(),gS=z.object({Rate:z.number().nullish(),Max:z.number().nullish(),Period:z.number().nullish()}).passthrough(),yS=z.object({IsTradable:z.boolean().nullish(),IsPurchasable:z.boolean().nullish(),IsRefundable:z.boolean().nullish()}).passthrough(),RS=z.object({TargetCurrencyType:ri.nullish(),TargetCurrencyID:z.string(),Rate:Y.nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish(),DailyLimit:z.number().nullish()}).passthrough(),bp=z.object({Enabled:z.boolean().nullish(),RateMode:mS.nullish(),Fee:z.number().nullish(),Targets:z.array(RS).nullish()}).passthrough(),Dp=z.object({CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough(),CS=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Economy:fS.nullish(),Recharge:gS.nullish(),Conversion:bp.nullish(),Permissions:yS.nullish(),Audit:Dp.nullish(),Status:xp.nullish()}).passthrough(),SS=z.object({NetworkID:z.string(),ContractAddress:z.string().nullish(),Decimals:z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),xS=z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),bS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),SpendableInGame:z.boolean().nullish(),ConvertibleToVirtual:z.boolean().nullish()}).passthrough(),DS=z.object({Mode:z.string().nullish(),FundingNetworkID:z.string().nullish(),PerPlayerDailyTokens:z.number().nullish(),TitleDailyTokens:z.number().nullish(),RefuseOverCap:z.boolean().nullish()}).passthrough(),na=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),DisplayDecimals:z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),UsdPriceRefreshMinutes:z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:z.array(SS).nullish(),Limits:xS.nullish(),Permissions:bS.nullish(),Conversion:bp.nullish(),Audit:Dp.nullish(),Status:xp.nullish(),ServerGrantPolicy:DS.nullish(),UnbackedRewardCurrencyID:z.string().nullish()}).passthrough(),zn=z.object({VirtualCurrencies:z.record(z.string(),CS).nullish(),CryptoCurrencies:z.record(z.string(),na).nullish()}).passthrough();var PS={EVM:"EVM",Solana:"Solana"},IS=z.enum(["EVM","Solana"]).catch("EVM"),vS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},TS=z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),AS={Token:"Token",Nft:"Nft"},Pp=z.enum(["Token","Nft"]).catch("Token"),kS={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},zS=z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),wS={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},MS=z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),OS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},ra=z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),Ip={GameTopUp:"game_topup",CommunityReward:"community_reward"};function wn(r){let e=r?.trim();return e||Ip.GameTopUp}var ES={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},vp=z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),US=z.object({ContractAddress:z.string().nullish(),ItemCatalogID:z.string().nullish(),DisplayName:z.string().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),Tp=z.object({Ios:z.boolean().nullish(),Android:z.boolean().nullish(),Web:z.boolean().nullish()}).passthrough(),qS=z.object({NetworkID:z.string().nullish(),DisplayName:z.string().nullish(),Type:IS.nullish(),ChainID:z.number().nullish(),ChainTicker:z.string().nullish(),RewardPoolAddress:z.string().nullish(),VaultDepositAddress:z.string().nullish(),ChainConfigVersion:z.number().nullish(),RequiredConfirmations:z.number().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:Tp.nullish(),NftCollections:z.array(US).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RpcUrl:z.string().nullish(),GasPrice:z.number().nullish(),NftBridgeAddress:z.string().nullish(),SignatureEpoch:z.number().nullish()}).passthrough(),BS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:Tp.nullish()}).passthrough(),LS=z.object({MinAccountAgeDays:z.number().nullish(),MultiAccountCheckEnabled:z.boolean().nullish(),BanOnSharedWithdrawalAddress:z.boolean().nullish(),PendingWithdrawalTtlHours:z.number().nullish()}).passthrough(),GS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},FS=z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Ap=z.object({Enabled:z.boolean().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:FS.nullish(),DenyMessage:z.string().nullish()}).passthrough(),VS=z.object({Enabled:z.boolean().nullish(),WalletConnectProjectId:z.string().nullish(),ShowOnLoginScreen:z.boolean().nullish()}).passthrough(),NS={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Oi=z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),_S=z.object({Mode:Oi.nullish(),TokenGates:z.array(Ap).nullish()}).passthrough(),oa=z.object({SystemState:BS.nullish(),Networks:z.record(z.string(),qS).nullish(),AccountSafety:LS.nullish(),WalletLogin:VS.nullish(),PlayAccess:_S.nullish(),IframeConnectHosts:z.array(z.string()).nullish()}).passthrough(),jS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),LinkedAt:p.nullish(),LastUsedAt:p.nullish(),LinkType:TS.nullish(),IsSignatureVerified:z.boolean().nullish()}).passthrough(),kp=z.object({TitleTransactionID:z.string().nullish(),Type:Pp.nullish(),NetworkID:z.string().nullish(),AssetID:z.string().nullish(),Amount:Y.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),WS=z.object({Status:zS.nullish(),Tier:MS.nullish(),VerifiedAt:p.nullish(),ExpiresAt:p.nullish(),RejectedAt:p.nullish(),ProviderReference:z.string().nullish(),RejectionReason:z.string().nullish()}).passthrough(),QS=z.object({CurrencyID:z.string().nullish(),Deposits:z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),KS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:z.record(z.string(),QS).nullish()}).passthrough(),HS=z.object({NetworkID:z.string().nullish(),ItemCatalogID:z.string().nullish(),Deposits:z.number().nullish(),Withdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),$S=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),PerCollection:z.record(z.string(),HS).nullish()}).passthrough(),JS=z.object({Tokens:KS.nullish(),Nfts:$S.nullish()}).passthrough(),aa=z.object({CurrencyID:z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Vt=z.object({Granted:z.boolean(),Mode:Oi.nullish(),Error:z.string().nullish(),WalletRequired:z.boolean().nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),GrantedUntil:p.nullish(),Balances:z.array(aa).nullish()}).passthrough(),ZS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:p.nullish(),Passed:z.boolean().nullish(),GrantedUntil:p.nullish(),Error:z.string().nullish(),Balances:z.array(aa).nullish()}).passthrough(),YS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CanUnlink:z.boolean().nullish()}).passthrough(),zp=z.object({Mode:Oi.nullish(),TokenGates:z.array(Ap).nullish(),WalletLoginEnabled:z.boolean().nullish(),CanLinkWallet:z.boolean().nullish(),WalletsFromPlatformProfile:z.boolean().nullish(),LinkedWallets:z.array(YS).nullish(),Status:Vt.nullish()}).passthrough(),XS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:p.nullish(),LoggedInAt:p.nullish(),GatePassed:z.boolean().nullish(),GatedBalances:z.array(aa).nullish()}).passthrough(),ex=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),UnlinkedAt:p.nullish()}).passthrough(),tx=z.object({Version:z.number().nullish(),Stats:JS.nullish(),LinkedWallets:z.record(z.string(),jS).nullish(),LastWalletLogin:XS.nullish(),PlayAccess:ZS.nullish(),PendingWithdrawals:z.array(kp).nullish(),Kyc:WS.nullish(),FirstActivityAt:p.nullish(),LastActivityAt:p.nullish(),IsFlagged:z.boolean().nullish(),FlagReason:z.string().nullish(),UnlinkedWallets:z.array(ex).nullish()}).passthrough(),ix=z.object({CurrencyID:z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:p}).passthrough(),fi=z.object({CryptoBalances:z.record(z.string(),ix).nullish(),PendingAdded:kp.nullish(),PendingRemovedIDs:z.array(z.string()).nullish()}).passthrough(),sx=z.object({Amount:Y,Frozen:Y,CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough().transform(r=>r),nx=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:vp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:ra.nullish(),SignatureData:z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),TokenID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:p.nullish(),BurnAmount:z.number().nullish(),RefundedAt:p.nullish(),RefundCheckedAt:p.nullish()}).passthrough(),rx=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:vp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:ra.nullish(),SignatureData:z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),NFTID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),SkinID:z.string().nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:p.nullish()}).passthrough(),wp=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),la=z.object({TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),ContractAddress:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(wp).nullish(),Signature:z.string().nullish()}).passthrough(),ua=z.object({Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),ProgramID:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(wp).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),Mp=z.object({Blockchain:oa.nullish(),CryptoCurrencies:z.record(z.string(),na).nullish()}).passthrough(),Op=z.object({State:tx.nullish(),CryptoBalances:z.record(z.string(),sx).nullish()}).passthrough(),Ep=z.object({ServerTimeUtc:p.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:fi.nullish()}).passthrough(),Up=z.object({ServerTimeUtc:p.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}).passthrough(),qp=z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:p.nullish(),EvmSignature:la.nullish(),SolanaSignature:ua.nullish(),StateDelta:fi.nullish(),ChainID:z.number().nullish()}).passthrough(),Bp=z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish(),EvmSignature:la.nullish(),SolanaSignature:ua.nullish(),StateDelta:fi.nullish(),Inventory:K.nullish()}).passthrough(),Lp=z.object({TokenTransactions:z.array(nx).nullish(),NFTTransactions:z.array(rx).nullish(),RefundedIDs:z.array(z.string()).nullish()}).passthrough(),ca=z.object({ServerTimeUtc:p.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:z.string().nullish()}).passthrough(),Gp=z.object({TitleTransactionID:z.string().nullish(),Kind:Pp.nullish(),EvmSignature:la.nullish(),SolanaSignature:ua.nullish()}).passthrough(),Fp=z.object({TitleTransactionID:z.string().nullish(),OnChainTxHash:z.string().nullish(),Status:ra.nullish(),StateDelta:fi.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",Vp="Blockchain:Definitions",Mn=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Vp,e);if(t)return a(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return c;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(ox,n.data.Blockchain),this.ctx.data.config.patchSection(Vp,n.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",n.data)),n)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,i,s,n){if(!e)return b("client","CurrencyID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return c;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=s,o.Category=wn(n);let c$1=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return c$1.ok&&(this.ctx.data.user.applyBlockchainStateDelta(c$1.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",c$1.data)),c$1}async requestNFTWithdrawal(e,t,i,s,n,o,c$1){if(!e)return b("client","ItemID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let h=this.ctx.authedRequest();if(!h)return c;h.ItemID=e,h.NetworkID=t,h.WalletAddress=i,h.Amount=s,h.Category=wn(n),o!==void 0&&(h.Level=o),c$1&&(h.ItemInstanceID=c$1);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(h);return R.ok&&(this.ctx.data.user.applyBlockchainStateDelta(R.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",R.data)),R}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","TitleTransactionID is required.");if(!t)return b("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.TitleTransactionID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return c;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 c;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var ax={Head:"Head",Torso:"Torso",Legs:"Legs"},On=z.enum(["Head","Torso","Legs"]).catch("Head"),lx={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},pa=z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),_p=z.object({AttackTarget:On,DefenseTarget:On});var ux=z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),cx=z.object({RoundIndex:z.number().nullish(),AttackerID:z.string().nullish(),DefenderID:z.string().nullish(),AttackZone:On.nullish(),DefenseZone:On.nullish(),HitType:ux.nullish(),DamageDealt:z.number().nullish(),DefenderHpRemaining:z.number().nullish()}).passthrough(),px=z.object({MaxHp:z.number().nullish(),CurrentHp:z.number().nullish(),Damage:z.number().nullish(),AttackSpeed:z.number().nullish(),CritChance:z.number().nullish(),CritMultiplier:z.number().nullish(),Armor:z.number().nullish(),DodgeChance:z.number().nullish()}).passthrough(),dx=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(r=>r),Np=z.object({UserID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),SelectedCharacter:Eo.nullish(),BattleStrategy:z.array(_p).nullish(),UnstackableItems:z.record(z.string(),dx).nullish(),Stats:px.nullish()}).passthrough(),hx=z.object({WinnerUserID:z.string().nullish(),LoserUserID:z.string().nullish(),Entry:ue.nullish(),NetReward:ue.nullish(),BattleLog:z.array(cx).nullish(),IsDraw:z.boolean().nullish(),P1BattleProfile:Np.nullish(),P2BattleProfile:Np.nullish()}).passthrough(),jp=z.object({MatchID:z.string(),TitleID:z.string().nullish(),RuleID:z.string().nullish(),CreatedAt:p.nullish(),CreatorID:z.string().nullish(),CreatorCharacterID:z.string().nullish(),CreatorStrategy:z.array(_p).nullish(),TargetUserID:z.string().nullish(),Entry:ue.nullish(),CreationCostPaid:ue.nullish(),RefundCreationCostOnCancel:z.boolean().nullish(),ExpiresAt:p.nullish(),JoinedByUserID:z.string().nullish(),JoinedByCharacterID:z.string().nullish(),JoinedAt:p.nullish(),Status:pa.nullish(),WinnerUserID:z.string().nullish(),CompletedAt:p.nullish(),IsRewardDistributed:z.boolean().nullish(),RewardDistributedAt:p.nullish()}).passthrough(),Wp=z.object({Status:pa,MatchID:z.string(),Entry:ue.nullish(),Resources:M.nullish()}),Qp=z.object({Match:jp.nullish()}),Kp=z.object({MatchID:z.string(),Status:pa,Resources:M.nullish()}),Hp=z.object({Battle:hx.nullish(),Resources:M.nullish(),ResourcesDual:It.nullish()}),da=z.object({Matches:z.array(jp).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}),xt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var mx=z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var fx=z.enum(["Constant","Variable","Curve"]).catch("Constant"),gx=z.object({HealthStatID:z.string().nullish(),DamageStatID:z.string().nullish(),ArmorStatID:z.string().nullish(),AttackSpeedStatID:z.string().nullish(),CritChanceStatID:z.string().nullish(),CritDamageStatID:z.string().nullish(),DodgeStatID:z.string().nullish(),AllMightStatID:z.string().nullish()}).passthrough(),yx=z.enum(["Flat","PercentReduction"]).catch("Flat"),Rx=z.object({MaxRounds:z.number().nullish(),BlockDamageMultiplier:z.number().nullish(),MinHitDamage:z.number().nullish(),DefaultCritMultiplier:z.number().nullish(),MaxCritChance:z.number().nullish(),MaxDodgeChance:z.number().nullish(),ArmorMode:yx.nullish(),MaxArmorReduction:z.number().nullish()}).passthrough(),Cx=z.object({Kind:fx.nullish(),Constant:z.number().nullish(),VariableID:z.string().nullish(),Argument:z.string().nullish(),Curve:_e.nullish(),OnePlus:z.boolean().nullish()}).passthrough(),Sx=z.object({Coefficient:z.number().nullish(),Factors:z.array(Cx).nullish()}).passthrough(),Jt=z.object({Terms:z.array(Sx).nullish()}).passthrough(),xx=z.object({Health:Jt.nullish(),Damage:Jt.nullish(),Armor:Jt.nullish(),AttackSpeed:Jt.nullish(),CritChance:Jt.nullish(),CritDamage:Jt.nullish(),Dodge:Jt.nullish()}).passthrough(),$p=z.object({StatMapping:gx.nullish(),Combat:Rx.nullish(),Formula:xx.nullish()}).passthrough(),bx=z.object({BurnRate:z.number().nullish()}).passthrough(),Ei=z.object({Kind:mx.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),TokenType:Wi.nullish(),EntityID:z.string().nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish()}).passthrough(),Jp=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Ei).nullish(),MaxPositions:z.number().nullish()}).passthrough(),Zp=z.object({PriceOptions:le.nullish(),RefundCostOnCancel:z.boolean().nullish(),MaxOpenMatches:z.number().nullish(),OfferLifetimeSeconds:z.number().nullish(),Limits:Ce.nullish(),AllowPrivateMatches:z.boolean().nullish(),MaxMatchesPerOpponentPerDay:z.number().nullish()}).passthrough(),Dx=z.object({RuleID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Economy:bx.nullish(),Entry:Jp.nullish(),Creation:Zp.nullish(),Settings:$p.nullish()}).passthrough(),Px=z.object({Rules:z.record(z.string(),Dx).nullish(),Defaults:$p.nullish(),EntryDefaults:Jp.nullish(),CreationDefaults:Zp.nullish()}).passthrough(),ha=z.object({InstantBattle:Px.nullish()}).passthrough(),Yp=ha;var Ix={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},ma=z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),vx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},fa=z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),Tx={Burn:"Burn",Ledger:"Ledger"},Ax=z.enum(["Burn","Ledger"]).catch("Burn"),Un={Item:"Item",VirtualCurrency:"VirtualCurrency"},ga=z.enum(["Item","VirtualCurrency"]).catch("Item"),kx=z.object({Percent:z.number().nullish(),MinPerPosition:j.nullish()}).passthrough(),qn=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Ei).nullish(),MaxPositions:z.number().nullish()}).passthrough(),ya=z.object({Percent:z.number().nullish(),MinPerPosition:j.nullish(),Sink:Ax.nullish(),LedgerAccountID:z.string().nullish(),PerCatalogOverrides:z.record(z.string(),kx).nullish(),ApplyToDirectTrades:z.boolean().nullish()}).passthrough(),zx=z.object({AllowedCatalogIDs:z.array(z.string()).nullish(),DeniedCatalogIDs:z.array(z.string()).nullish(),DeniedItemIDs:z.array(z.string()).nullish(),AllowUnstackableWithState:z.boolean().nullish(),AllowedCurrencyIDs:z.array(z.string()).nullish(),DeniedCurrencyIDs:z.array(z.string()).nullish()}).passthrough(),wx=z.object({Enabled:z.boolean().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),MaxActiveListings:z.number().nullish(),CreateLimits:Ce.nullish(),BuyLimits:Ce.nullish(),ListingFeeOptions:le.nullish(),RefundListingFeeOnCancel:z.boolean().nullish()}).passthrough(),Mx=z.object({Enabled:z.boolean().nullish(),MinDurationHours:z.number().nullish(),MaxDurationHours:z.number().nullish(),AntiSnipeWindowSeconds:z.number().nullish(),AntiSnipeExtensionSeconds:z.number().nullish(),MaxAntiSnipeExtensions:z.number().nullish(),MinBidStepPercent:z.number().nullish(),MinBidStepAbsolute:j.nullish(),BidLimits:Ce.nullish()}).passthrough(),Ox=z.object({Enabled:z.boolean().nullish(),MaxActiveOrders:z.number().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),CreateLimits:Ce.nullish(),FillLimits:Ce.nullish()}).passthrough(),Ex=z.object({Enabled:z.boolean().nullish(),OfferExpirationHours:z.number().nullish(),MaxPendingOutgoing:z.number().nullish(),AllowGifts:z.boolean().nullish(),CreateLimits:Ce.nullish()}).passthrough(),Ux=z.object({Enabled:z.boolean().nullish()}).passthrough(),Ra=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:ge.nullish(),PricePolicy:qn.nullish(),Commission:ya.nullish(),Tradability:zx.nullish(),Listings:wx.nullish(),Auctions:Mx.nullish(),BuyOrders:Ox.nullish(),DirectTrades:Ex.nullish(),Matching:Ux.nullish()}).passthrough(),Xp=z.object({BidIndex:z.number().nullish(),UserID:z.string().nullish(),Amount:j.nullish(),Settled:z.boolean().nullish(),SettledAt:p.nullish()}).passthrough(),qx=z.object({BidAxisType:oi.nullish(),BidCurrencyID:z.string().nullish(),BidCatalogID:z.string().nullish(),BidItemID:z.string().nullish(),StartingBid:j.nullish(),CurrentBid:j.nullish(),CurrentBidderID:z.string().nullish(),BidCount:z.number().nullish(),ExtensionCount:z.number().nullish(),PendingRefunds:z.array(Xp).nullish()}).passthrough(),En=z.object({LastAt:p.nullish(),DailyCount:z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),Bx=z.object({Create:En.nullish(),Buy:En.nullish(),Sell:En.nullish(),Bid:En.nullish()}).passthrough(),Lx=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),Gx=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:Lx.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(r=>r),wt=z.object({OfferID:z.string().nullish(),OfferType:ma.nullish(),Status:fa.nullish(),CreatorUserID:z.string().nullish(),CreatorPublicData:qe.nullish(),TargetUserID:z.string().nullish(),GoodsType:ga.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:j.nullish(),GoodsInstances:z.array(Gx).nullish(),Price:ue.nullish(),Auction:qx.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),Fx=z.object({GoodsType:ga.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),CountsByType:z.partialRecord(ma,j).nullish()}).passthrough(),ed=z.object({Definitions:Ra.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish()}).passthrough(),Ca=z.object({Offers:z.array(wt).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),td=z.object({Groups:z.array(Fx).nullish()}).passthrough(),id=z.object({Offer:wt.nullish()}).passthrough(),ct=z.object({OfferID:z.string().nullish(),Status:fa.nullish(),Settlement:It.nullish(),Resources:M.nullish(),CommissionTaken:ue.nullish()}).passthrough(),Ui=z.object({OfferID:z.string().nullish(),Offer:wt.nullish(),Resources:M.nullish(),Matched:z.boolean().nullish(),Settlement:ct.nullish()}).passthrough(),sd=z.object({OfferID:z.string().nullish(),CurrentBid:j.nullish(),BidCount:z.number().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish()}).passthrough(),Bn=z.object({MyOffers:z.array(wt).nullish(),MyBids:z.array(wt).nullish(),MyBuyOrders:z.array(wt).nullish(),IncomingTrades:z.array(wt).nullish(),OutgoingTrades:z.array(wt).nullish(),Claimables:z.array(wt).nullish(),DrainedRefunds:z.array(Xp).nullish(),Limits:Bx.nullish()}).passthrough(),Vx=z.object({OfferID:z.string().nullish(),OfferType:ma.nullish(),FinalStatus:fa.nullish(),SellerUserID:z.string().nullish(),BuyerUserID:z.string().nullish(),GoodsType:ga.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:j.nullish(),PricePaid:ue.nullish(),CommissionTaken:ue.nullish(),CompletedAt:p.nullish(),MyRole:z.string().nullish()}).passthrough(),nd=z.object({Entries:z.array(Vx).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Me={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 Nx="Marketplace",rd={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"]},Ln=class{constructor(e){this.ctx=e;e.cache.bindLoginView(rd,{schema:Bn,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(Nx,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,s=20){if(!e)return b("client","ItemID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.ItemID=e,n.OfferTypeFilter=t,n.ContinuationToken=i,n.PageSize=s;let o=await this.ctx.api.marketplace.getOffersByItem(n);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let s=this.ctx.authedRequest();if(!s)return c;s.ItemID=e,s.ContinuationToken=t,s.PageSize=i;let n=await this.ctx.api.marketplace.getBuyOrders(s);return n.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",n.data),n}getMyState(e,t){return this.ctx.cache.read(rd,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return c;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let s=this.ctx.authedRequest();if(!s)return c;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let n=await this.ctx.api.marketplace.getHistory(s);return n.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",n.data),n}async createListing(e,t,i,s,n,o,c$1){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let h=this.ctx.authedRequest();if(!h)return c;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.PriceBundle=s,h.DurationHours=n,h.ItemInstanceIDs=o,h.SelectedOptionID=c$1;let R=await this.ctx.api.marketplace.createListing(h);return this.applyCreateOfferResult(R,"marketplace:listingCreated"),R}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,s,n,o,c$1={}){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");let h=this.ctx.authedRequest();if(!h)return c;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.BidAxisType=s,h.BidCurrencyID=c$1.bidCurrencyID,h.BidCatalogID=c$1.bidCatalogID,h.BidItemID=c$1.bidItemID,h.StartingBid=n,h.DurationHours=o,h.ItemInstanceIDs=c$1.itemInstanceIDs,h.SelectedOptionID=c$1.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(h);return this.applyCreateOfferResult(R,"marketplace:auctionCreated"),R}async placeBid(e,t){if(!e)return b("client","OfferID is required.");if(!t||t<=0)return b("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return c;i.OfferID=e,i.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,s,n){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return c;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=s,o.DurationHours=n;let c$1=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(c$1,"marketplace:buyOrderCreated"),c$1}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,s,n){if(!e)return b("client","TargetUserID is required.");if(!t)return b("client","CatalogID is required.");if(!i)return b("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return c;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=s,o.RequestedBundle=n;let c$1=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(c$1,"marketplace:directTradeCreated"),c$1}async respondDirectTrade(e,t){if(!e)return b("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.OfferID=e,i.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(i);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.OfferID=e;let n=await t(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,n.data)),n}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=Un.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Un.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):b("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 Gn=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return b("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let s=await this.ctx.api.multiplayer.createRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.RoomID=e,s.TargetUserID=t,s.Ban=i;let n=await this.ctx.api.multiplayer.kickMember(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",n.data),n}async unbanMember(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return c;i.Page=e,i.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(i);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,i,s){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");if(!i)return b("client","SignalKind is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.TargetUserID=t,n.SignalKind=i,n.Payload=s;let o=await this.ctx.api.multiplayer.sendSignal(n);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(i);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,i){if(!e)return b("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.RoomID=e,s.Ready=t,s.MemberState=i;let n=await this.ctx.api.multiplayer.setMemberState(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",n.data),n}};var od=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Fn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;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)):c}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 b("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):c}async getCreatorProfile(e,t,i){if(!e)return b("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):c}async publish(e){if(!e.files||e.files.length===0)return b("client","At least one file is required.");let t=new Map,i=e.files.map((h,R)=>{if("sourceAssetUrl"in h)return {Role:h.role,ContentType:h.contentType,SourceAssetUrl:h.sourceAssetUrl};let V=ad(h.data,h.contentType);return t.set(R,V),{Role:h.role,ContentType:h.contentType,Size:V.size}}),s=e.thumbnail?ad(e.thumbnail.data,e.thumbnail.contentType):null,n=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!n.ok)return n;let o=n.data.Uploads??[];for(let h=0;h<o.length;h++){let R=o[h];if(!R||R.ServerCopy||!R.Url)continue;let V=t.get(h);if(!V)return b("client",`No bytes for file #${h+1}.`);let ce=await this.putBytes(R.Url,V,R.ContentType??V.type);if(!ce.ok)return ce}let c=n.data.ThumbnailUpload;if(c?.Url&&s){let h=await this.putBytes(c.Url,s,c.ContentType??s.type);if(!h.ok)return h}return this.ctx.credits.pay(h=>this.publishUploaded({CreditsConfirmationID:h,ContentID:n.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}):c}async publishUploaded(e){if(!e.ContentID)return b("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return c;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&!i.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let s=await this.ctx.api.workshop.updateContent(i);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getMyContent(s)):c}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let s=await this.ctx.api.workshop.acquire(i);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let s of t.data.Files??[])if(s.Url)try{let n=await this.ctx.fetchImpl(s.Url);if(!n.ok)return b("connection",`Download failed (HTTP ${n.status}).`);i.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await n.arrayBuffer()});}catch(n){return b("connection",`Download failed: ${n instanceof Error?n.message:String(n)}${od}`)}return a({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)):c}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):c}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${od}`)}}contentRequest(e){if(!e)return b("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):c}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 ad(r,e){return r instanceof Blob?r:typeof r=="string"?new Blob([new TextEncoder().encode(r)],{type:e}):r instanceof Uint8Array?new Blob([r.slice().buffer],{type:e}):new Blob([r],{type:e})}var _x={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},jx=z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Wx={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},ld=z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),Qx={Everyone:"Everyone",Owner:"Owner",Server:"Server"},ud=z.enum(["Everyone","Owner","Server"]).catch("Everyone"),Kx={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},Hx=z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),$x={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},Jx=z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),Zx={Count:"Count",Sum:"Sum"},Yx=z.enum(["Count","Sum"]).catch("Count"),Xx={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},eb=z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),tb={Strict:"Strict",Loose:"Loose"},ib=z.enum(["Strict","Loose"]).catch("Strict"),sb=z.object({Kind:Jx,Collection:z.string().nullish(),Validate:z.boolean().nullish()}),nb=z.object({Type:ld,ItemType:ld.nullish(),Ref:sb.nullish(),Required:z.boolean().optional(),Default:z.string().nullish(),Min:z.number().nullish(),Max:z.number().nullish(),MaxLength:z.number().nullish(),MaxItems:z.number().nullish(),Enum:z.array(z.string()).nullish(),Unique:z.boolean().optional(),UniqueIgnoreCase:z.boolean().optional(),Indexed:z.boolean().optional(),Visibility:ud.optional(),ClientWritable:z.boolean().nullish(),Immutable:z.boolean().optional(),Description:z.string().nullish(),AllowedMimeTypes:z.array(z.string()).nullish(),MaxFileBytes:z.number().nullish()}),rb=z.object({ID:z.string(),Components:z.array(z.object({Field:z.string(),Descending:z.boolean().optional()})).default([])}),Vn=z.object({Mode:Hx,Role:z.string().nullish(),MembersField:z.string().nullish()}),ob=z.object({Read:z.array(Vn).nullish(),Create:z.array(Vn).nullish(),Update:z.array(Vn).nullish(),Delete:z.array(Vn).nullish()}),Sa=z.object({Cost:ue.nullish(),Grant:ue.nullish()}),ab=z.object({ID:z.string(),SortKey:z.string(),PartitionField:z.string().nullish(),PageSize:z.number().optional(),MaxItems:z.number().optional(),PublishItems:z.boolean().optional()}),lb=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Namespace:z.string().nullish(),Tags:z.array(z.string()).nullish(),Enabled:z.boolean().nullish(),Kind:jx,Mode:ib.optional(),SchemaVersion:z.number().optional(),Fields:z.record(z.string(),nb).nullish(),SortKeys:z.array(rb).nullish(),Access:ob.nullish(),Limits:z.object({MaxItemBytes:z.number().nullish(),MaxItemsPerOwner:z.number().nullish(),TtlSeconds:z.number().nullish()}).nullish(),OnOwnerDeleted:eb.optional(),Counters:z.array(z.object({ID:z.string(),Kind:Yx,SumField:z.string().nullish(),GroupBy:z.string().nullish(),Visibility:ud.optional()})).nullish(),Economy:z.object({OnCreate:Sa.nullish(),OnUpdate:Sa.nullish(),OnDelete:Sa.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:z.array(ab).nullish(),AnonymousSearch:z.boolean().nullish(),Integrations:z.object({QuestMetricOnCreate:z.string().nullish(),QuestMetricOnUpdate:z.string().nullish(),QuestMetricOnDelete:z.string().nullish(),AnalyticsEventOnCreate:z.string().nullish(),AnalyticsEventOnUpdate:z.string().nullish(),AnalyticsEventOnDelete:z.string().nullish(),TriggerOnCreate:z.string().nullish(),TriggerOnUpdate:z.string().nullish(),TriggerOnDelete:z.string().nullish()}).nullish(),Moderation:z.object({BlockedTerms:z.array(z.string()).nullish()}).nullish()}),cd=z.object({Enabled:z.boolean().optional(),Collections:z.record(z.string(),lb).default({})}),ub=z.object({FileID:z.string(),Url:z.string(),ContentType:z.string().nullish(),Size:z.number()}),pd=z.object({FileID:z.string(),UploadUrl:z.string(),ContentType:z.string(),MaxBytes:z.number(),ExpiresAt:z.string()}),gi=z.object({Collection:z.string(),ItemID:z.string(),OwnerUserID:z.string().nullish(),Data:z.record(z.string(),z.unknown()).default({}),Version:z.number(),CreatedAt:z.string(),UpdatedAt:z.string(),ExpireAt:z.string().nullish(),Expanded:z.record(z.string(),z.unknown()).nullish(),Files:z.record(z.string(),ub).nullish()}),xa=z.object({Item:gi}),dd=z.object({Items:z.array(gi).default([]),Missing:z.array(z.string()).default([])}),ba=z.object({Items:z.array(gi).default([]),NextCursor:z.string().nullish()}),hd=z.object({Count:z.number(),Capped:z.boolean().optional()}),Da=z.object({Item:gi,AlreadyExists:z.boolean().optional(),Economy:M.nullish()}),md=z.object({ItemID:z.string(),Deleted:z.boolean(),Economy:M.nullish()}),fd=z.object({CounterID:z.string(),Group:z.unknown().optional(),Value:z.number()}),gd=z.object({Results:z.array(z.object({Op:z.string(),Collection:z.string(),ItemID:z.string(),Item:gi.nullish(),Deleted:z.boolean().optional()})).default([])}),yd=z.object({Roles:z.array(z.string()).default([])}),Rd=z.object({Views:z.record(z.string(),z.string()).default({}),ItemUrlTemplate:z.string().nullish()}),Cd=z.object({Version:z.string(),Collection:z.string(),View:z.string(),SortKey:z.string().nullish(),PageSize:z.number(),UpdatedAt:z.string(),BaseUrl:z.string(),Partitions:z.record(z.string(),z.object({Segment:z.string(),Pages:z.number(),Total:z.number()})).default({})}),Sd=z.object({Page:z.number(),HasMore:z.boolean(),Items:z.array(gi).default([])}),cb={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 pb=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Dd=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Ia=100,xd=25,bd=100;function db(r,e,t){return {Field:r,Op:e,Value:t}}var Nn=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(c)}get(e,t,i={}){let s=nt(e)??qi(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.get({...n,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let s=nt(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(o=>Dd.test(o)))];return n.length?n.length>bd?Promise.resolve(b("client",`At most ${bd} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:n,Expand:i.expand})):Promise.resolve(b("client","At least one valid item id is required."))}query(e,t={},i={}){let s=nt(e)??Pa(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.query({...n,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),n=[],o=t.Cursor;for(;;){let c=await this.query(e,{...t,Cursor:o,Limit:t.Limit??Ia},i);if(!c.ok)return c;if(n.push(...c.data.Items),o=c.data.NextCursor??void 0,!o||n.length>=s)return a(n.slice(0,s))}}count(e,t={}){let i=nt(e)??Pa(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,i={}){let s=nt(e)??(i.itemID?qi(i.itemID):null);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.create({...n,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,s={}){let n=nt(e)??qi(t);return n?Promise.resolve(n):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=nt(e)??qi(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.delete({...n,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(b("client","Operations are empty."));if(e.length>xd)return Promise.resolve(b("client",`At most ${xd} operations per batch.`));let t=e.map(i=>nt(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let s=nt(e);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.getCounter({...n,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,s){let n=nt(e);return n?Promise.resolve(n):t?s>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(b("client","File size must be positive.")):Promise.resolve(b("client","Field is required."))}async uploadFile(e,t,i,s={}){let n=s.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,n,i.size);if(!o.ok)return o;let c=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||n);return c.ok?o:c}async getPublicViews(e){let t=nt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return a(i);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,i={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let n=s.data.Views[t];if(!n)return b("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(n,Cd);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 a({pointer:o.data,page:{Page:h,HasMore:false,Items:[]}});let R=await this.fetchJson(`${o.data.BaseUrl}${c.Segment}/page-${h}.json`,Sd);return R.ok?a({pointer:o.data,page:R.data}):R}getPublic(e,t){let i=nt(e)??qi(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=nt(e)??Pa(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(c)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return b("connection","Internet Connection Error")}if(!i.ok)return b("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return b("server","CDN answer is not JSON.")}let n=t.safeParse(s);return n.success?a(n.data):b("server","CDN answer has an unexpected shape.")}};function nt(r){return pb.test(r??"")?null:b("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function qi(r){return Dd.test(r??"")?null:b("client",`Item id '${r}' is invalid.`)}function Pa(r){return r.Limit!=null&&(r.Limit<1||r.Limit>Ia)?b("client",`Limit must be 1..${Ia}.`):(r.Where?.length??0)>8?b("client","At most 8 filters per query."):null}var va={Open:"Open",Declared:"Declared"},hb=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Blocked:z.boolean().nullish(),Highlight:z.number().nullish()}).passthrough(),mb=z.object({ParamName:z.string().nullish(),DisplayName:z.string().nullish()}).passthrough(),Pd=z.object({Enabled:z.boolean().nullish(),EventNaming:z.string().nullish(),Events:z.record(z.string(),hb).nullish(),Dimensions:z.array(mb).nullish(),RetentionDays:z.number().nullish(),AutomaticEvents:z.boolean().nullish()}).passthrough(),Nt={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_"]},_n=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,fb={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},gb=z.object({Index:z.number().nullish(),Name:z.string().nullish(),Reason:z.string().nullish()}).passthrough(),Id=z.object({Accepted:z.number().nullish(),Dropped:z.array(gb).nullish(),Duplicate:z.boolean().nullish(),Disabled:z.boolean().nullish()}).passthrough(),Ta={LogEvents:"LogEvents"};function vd(r,e=0){let t=r??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let c=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:c==="iPad"?"tablet":"phone",deviceModel:c}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let c=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:c&&c!=="K"&&c!=="wv"?c:void 0}}let n=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(n)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(n[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 Td(r){let e=typeof navigator>"u"?void 0:navigator,t=vd(e?.userAgent??"",e?.maxTouchPoints??0),i={};r.appVersion&&(i.AppVersion=r.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let s=r.locale||e?.language;return s&&(i.Language=s),i}var yb=25,Rb=3e4,Ad=1800*1e3,kd=500,Cb=5,Sb=1e3,xb=3600*1e3,zd="idos_analytics_queue",Aa="idos_analytics_pending",ka="idos_analytics_opt_out",wd="idos_analytics_first_open",Md="idos_analytics_last_activity",Od="idos_analytics_last_context",Ed="idos_analytics_owner",jn=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"||!_n.test(e)?b("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):bb(e)?b("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 b("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Nt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return a(null);if(this.config()?.Enabled===false)return this.clear(),a(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return a(null);this.pending={BatchID:d(),Events:this.queue.splice(0,bt.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return c;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>=Cb)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(ka);return}this.write(ka,"1"),this.clear();}get isEnabled(){return this.read(ka)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(Ed);e&&t&&t!==e&&this.clear(),e&&this.write(Ed,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Rb),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(Md)??"0");this.read(wd)||(this.write(wd,new Date().toISOString()),this.enqueue(Nt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Od);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Nt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Nt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Od,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Ad)&&this.enqueue(Nt.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>=Ad&&this.enqueue(Nt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,s){if(!this.isEnabled||this.disabledByServer)return a(null);let n=this.config();if(n?.Enabled===false)return a(null);if(s&&n?.AutomaticEvents===false)return a(null);if(n?.Events?.[e]?.Blocked)return b("client",`Event "${e}" is blocked by the title.`);if(!s&&n?.EventNaming?.toLowerCase()===va.Declared.toLowerCase()&&!n.Events?.[e])return b("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return b("client","value must be a finite number.");let o=Db(t);if(o.error)return b("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>=yb&&this.flush(),a(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},Sb));}dropStale(){let e=Date.now()-(bt.maxEventAgeMs-xb);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??=Td({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(zd);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(Aa);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(zd,this.queue),this.pending?this.writeJson(Aa,this.pending):this.remove(Aa);}touch(){this.write(Md,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 bb(r){let e=r.toLowerCase();return bt.reservedPrefixes.some(t=>e.startsWith(t))}function Db(r){if(!r)return {};let e=Object.keys(r);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(!_n.test(i))return {error:`Invalid parameter name "${i}".`};let s=r[i];typeof s=="string"?t[i]=s.length>bt.maxStringValueLength?s.slice(0,bt.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var Pb="idos_experiments",Wn=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 c;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let n=Number(s);return s.trim()!==""&&Number.isFinite(n)?n:i}if(typeof i=="boolean"){let n=s.trim().toLowerCase();return n==="true"||n==="1"?true:n==="false"||n==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,n]of t){let o=this.views.get(s);(!o||o.VariantID!==n.VariantID||o.Status!==n.Status)&&i.push(n);}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 `${Pb}:${this.ctx.settings.titleID}`}};function _t(r,e,t,i){let n=`api/v2/${r&&r.length>0?r:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return _t(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,s){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...s,ticket:t.ClientSessionTicket})}};var Qn=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Ta.LogEvents,e,Id,{silent:true})}};var Ib=z.object({VariantID:z.string().nullish(),DisplayName:z.string().nullish(),Weight:z.number().nullish(),IsControl:z.boolean().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),vb={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Tb=z.object({MetricID:z.string().nullish(),Kind:z.string().nullish(),EventName:z.string().nullish(),IsPrimary:z.boolean().nullish()}).passthrough(),Ab=z.object({ExperimentID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),IsEnabled:z.boolean().nullish(),Schedule:ge.nullish(),Gate:Z.nullish(),Variants:z.array(Ib).nullish(),Salt:z.string().nullish(),LayerID:z.string().nullish(),StickyAssignment:z.boolean().nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Goals:z.array(Tb).nullish(),ActivationEvent:z.string().nullish(),RolloutVariantID:z.string().nullish()}).passthrough(),Ud=z.object({Experiments:z.record(z.string(),Ab).nullish()}).passthrough(),kb={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},zb=z.object({ExperimentID:z.string().nullish(),VariantID:z.string().nullish(),Status:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),qd=z.object({Experiments:z.array(zb).nullish(),IsAbTestingAvailable:z.boolean().nullish()}).passthrough(),za={GetExperiments:"GetExperiments"};var Kn=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(za.GetExperiments,e,qd)}};var Bd=z.object({PlatformUserID:z.string().nullish(),PlatformAuthToken:z.string().nullish(),PlatformAuthTokenExpiration:p.nullish(),TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:p,PlayAccess:Vt.nullish(),RefreshToken:z.string().nullish(),RefreshTokenExpiration:p.nullish()}),Ld=z.object({TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:p,RefreshToken:z.string(),RefreshTokenExpiration:p.nullish(),PlayAccess:Vt.nullish()}),wb=z.object({ReturnMode:z.string().nullish(),UrlScheme:z.string().nullish(),UserCodeSupported:z.boolean().nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),Gd=z.object({Google:z.object({Enabled:z.boolean().nullish(),WebClientID:z.string().nullish(),PlatformFallback:z.boolean().nullish(),AndroidClientID:z.string().nullish(),IosClientID:z.string().nullish(),DesktopClientID:z.string().nullish()}).passthrough().nullish(),Apple:z.object({Enabled:z.boolean().nullish(),BundleID:z.string().nullish(),ServiceID:z.string().nullish()}).passthrough().nullish(),PlayAccessMode:Oi.nullish(),WalletLoginNetworks:z.array(z.object({NetworkID:z.string().nullish(),Type:z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:z.boolean().nullish(),NativeSso:wb.nullish()}).passthrough(),Fd=z.object({Linked:z.boolean().nullish(),Challenge:z.string().nullish(),ExpiresAt:p.nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),PlayAccess:Vt.nullish()}).passthrough(),Vd=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CooldownUntil:p.nullish(),PlayAccess:Vt.nullish()}).passthrough(),Nd=z.object({CodeTtlMinutes:z.number().nullish(),ResendCooldownSeconds:z.number().nullish()}),Le=z.object({IsCompleted:z.boolean().nullish(),ServerTime:p.nullish()}),_d=z.object({Message:z.string(),ExpiresAt:p}),Be={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 Hn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return _t(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,Bd,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Be.RefreshSession),e,Ld,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Be.GetAuthOptions),e,Gd,{ticket:null})}linkWallet(e){return this.ctx.transport.post(_t(this.ctx.settings.titleID,"Authentication",Be.LinkWallet,e.UserID??""),e,Fd,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(_t(this.ctx.settings.titleID,"Authentication",Be.UnlinkWallet,e.UserID??""),e,Vd,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Be.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Be.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Be.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Be.LoginWithGoogle,e)}loginWithApple(e){return this.login(Be.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Be.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(Be.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Be.RegisterWithEmail),e,Nd,{ticket:null})}confirmEmailRegistration(e){return this.login(Be.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Be.ResendVerificationCode),e,Le,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Be.RequestWalletChallenge),e,_d,{ticket:null})}loginWithWallet(e){return this.login(Be.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Be.ForgotPassword),e,Le,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Be.ResetPassword),e,Le,{ticket:null})}};var Mb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},jd=z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Ob=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),IsEnabled:z.boolean().nullish(),Order:z.number().nullish()}).passthrough(),Wd=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),Locales:z.record(z.string(),Ob).nullish(),MissingKeyMode:jd.nullish(),MaxEntriesPerLocale:z.number().nullish(),MaxValueLengthBytes:z.number().nullish()}).passthrough(),Eb=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish()}).passthrough(),Qd=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish(),Fallback:Eb.nullish()}).passthrough(),$n={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Ub=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),Order:z.number().nullish(),Version:z.number().nullish()}).passthrough(),Kd=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),MissingKeyMode:jd.nullish(),ResolvedLocale:z.string().nullish(),Locales:z.array(Ub).nullish()}).passthrough(),Hd=z.object({RequestedLocale:z.string().nullish(),Locale:z.string().nullish(),Version:z.number().nullish(),NotModified:z.boolean().nullish(),Entries:z.record(z.string(),z.string()).nullish(),FallbackLocale:z.string().nullish(),FallbackVersion:z.number().nullish()}).passthrough();var wa=z.object({TitleConfigVersion:z.string().nullish(),TitleConfigUrl:z.string().nullish(),User:z.unknown().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish(),Localization:Qd.nullish(),Views:z.array(z.object({Name:z.string(),Key:z.string().nullish(),Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(r=>r),$d=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish()}).passthrough().transform(r=>r),Jd=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),User:z.unknown().nullish()}).passthrough().transform(r=>r),Zd=z.object({}).passthrough().transform(r=>r),Yd=z.object({}).passthrough().transform(r=>r),Xd=z.object({Today:z.number(),Yesterday:z.number(),CurrentWeek:z.number(),CurrentMonth:z.number(),Total:z.number(),TotalSessions:z.number(),FirstActiveAt:p.nullish(),LastActiveAt:p.nullish(),LongestSessionEverSeconds:z.number().nullish(),CurrentWeekActiveHoursMask:z.number().nullish(),CurrentMonthActiveHoursMask:z.number().nullish(),ReactivationCount:z.number().nullish(),History:z.record(z.string(),z.unknown()).nullish()}).passthrough(),eh=z.object({Username:z.string()}),pt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Jn=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(pt.GetClientState,e,wa)}getClientStateExcept(e){return this.send(pt.GetClientStateExcept,e,wa)}getStateVersions(e){return this.send(pt.GetStateVersions,e,$d)}getUserState(e){return this.send(pt.GetUserState,e,Jd)}getInventory(e){return this.send(pt.GetInventory,e,Zd)}getEventTokens(e){return this.send(pt.GetEventTokens,e,Yd)}getUsageTime(e){return this.send(pt.GetUsageTime,e,Xd)}addUsageTime(e){return this.send(pt.AddUsageTime,e,Le,{silent:true})}deleteUserAccount(e){return this.send(pt.DeleteUserAccount,e,Le)}changeUsername(e){return this.send(pt.ChangeUsername,e,eh)}};var Zn=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(kn.Convert,e,Cp)}cryptoConvert(e){return this.send(kn.CryptoConvert,e,Sp)}};var qb=z.object({ItemInstanceID:z.string(),Units:z.number(),Level:z.number()}),Ma=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Level:z.number(),Resources:M.nullish(),FodderConsumed:z.array(qb).nullish()}),th=z.array(Te(Ma)),Yn={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Bb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},Lb=z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Gb={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Fb=z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Vb=z.object({ContractAddress:z.string().nullish(),TokenID:z.string().nullish(),TokenStandard:z.string().nullish(),MaxLevel:z.number().nullish()}).passthrough(),Nb=z.object({Networks:z.record(z.string(),Vb).nullish(),MetadataUrl:z.string().nullish()}).passthrough(),_b=z.object({FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),jb=z.object({MinCharacterLevel:z.number().nullish(),UseRequirements:z.record(z.string(),z.number()).nullish(),AllowedCharacterIDs:z.array(z.string()).nullish(),AllowedSlotIDs:z.array(z.string()).nullish(),IdleRateBonus:z.number().nullish()}).passthrough(),Wb=z.object({ValuationMode:Lb.nullish(),WeightCurve:_e.nullish(),Selection:Fb.nullish()}).passthrough(),Qb=z.object({MaxLevel:z.number().nullish(),PriceOptions:le.nullish(),CostCurve:_e.nullish(),FlatBonusCurve:_e.nullish(),PercentBonusCurve:_e.nullish(),PowerCurve:_e.nullish(),Fodder:Wb.nullish()}).passthrough(),Kb=z.object({RarityID:z.string().nullish(),CollectionID:z.string().nullish(),AuthorID:z.string().nullish()}).passthrough(),Hb=z.object({ItemID:z.string(),CatalogID:z.string(),ItemClass:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),CustomData:z.record(z.string(),z.string()).nullish(),IsStackable:z.boolean().nullish(),IsTradable:z.boolean().nullish(),Weight:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),NFT:Nb.nullish(),Stats:_b.nullish(),Equipment:jb.nullish(),Upgrade:Qb.nullish(),Metadata:Kb.nullish(),ExpirationDurationSeconds:z.number().nullish(),MaxSupply:z.number().nullish()}).passthrough(),$b=z.object({Items:z.record(z.string(),Hb).nullish()}).passthrough(),Xn=z.object({Catalogs:z.record(z.string(),$b).nullish()}).passthrough();function De(r){return z.unknown().transform((e,t)=>{let i=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(i!=null){let n=me.safeParse(i);return n.success?{...e,CreditsConfirmation:n.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${n.error.message}`}),z.NEVER)}let s=r.safeParse(e);return s.success?s.data:(t.addIssue({code:"custom",message:s.error.message}),z.NEVER)})}var er=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(Yn.UpgradeLevel,e,De(Ma))}upgradeLevelsBatch(e){return this.send(Yn.UpgradeLevelsBatch,e,th)}};var tr=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(Tt.Purchase,e,bo)}purchaseBatch(e){return this.send(Tt.PurchaseBatch,e,nu)}getDefinitions(e){return this.send(Tt.GetDefinitions,e,Rs)}getUserState(e){return this.send(Tt.GetUserState,e,ru)}getStorefront(e){return this.send(Tt.GetStorefront,e,Cs)}getCreditsConfirmation(e){return this.send(Tt.GetCreditsConfirmation,e,me)}getCreditsBalance(e){return this.send(Tt.GetCreditsBalance,e,su)}};var Jb={Apple:"Apple",Google:"Google"},ir=z.object({PremiumID:z.string().nullish(),PurchaseDate:z.string().nullish(),ExpirationDate:z.string().nullish(),TransactionID:z.string().nullish(),IsAutoRenewEnabled:z.boolean().nullish()}).passthrough(),sr=z.object({Subscriptions:z.record(z.string(),ir).nullish(),ActivatedTrialIDs:z.array(z.string()).nullish(),MaxActiveTier:z.number().nullish()}).passthrough().transform(r=>r),Zb=z.object({PremiumID:z.string().nullish(),DisplayName:z.string().nullish(),Tier:z.number().nullish(),DurationDays:z.number().nullish(),TrialDurationDays:z.number().nullish(),PriceOptions:le.nullish(),Benefits:z.record(z.string(),z.string()).nullish()}).passthrough(),Ea=z.object({Definitions:z.record(z.string(),Zb).nullish()}).passthrough(),ih=z.object({Premium:Ea.nullish()}),sh=z.object({ServerTimeUtc:p.nullish(),Premium:sr.nullish()}),nr=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),Premium:sr.nullish(),Subscription:ir.nullish(),Resources:M.nullish()}),Zt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var Yb={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},Xb=z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),nh=z.object({StartUtc:p.nullish(),EndUtc:p.nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),Ua=z.object({ResourceAction:z.string().nullish(),RevokeEntitlement:z.boolean().nullish(),BlockFuturePurchases:z.boolean().nullish()}).passthrough(),eD=z.object({PremiumID:z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:z.number().nullish(),RevokeOnRefund:z.boolean().nullish()}).passthrough(),tD=z.object({Rewards:Q.nullish(),Rules:Q.nullish(),Refund:Q.nullish()}).passthrough(),iD=z.object({ProductID:z.string().nullish(),Name:z.string().nullish(),Type:Xb.nullish(),Enabled:z.boolean().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:z.number().nullish(),TelegramStarsPrice:z.number().nullish(),Rules:nh.nullish(),Refund:Ua.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Subscription:eD.nullish(),Presets:tD.nullish()}).passthrough(),sD=z.object({StoreID:z.string().nullish(),Enabled:z.boolean().nullish(),PackageName:z.string().nullish(),VerificationMode:z.string().nullish(),PlayPublicKey:z.string().nullish(),RequireCertificateChain:z.boolean().nullish(),SecretName:z.string().nullish(),IssuerID:z.string().nullish(),KeyID:z.string().nullish(),AcknowledgePurchases:z.boolean().nullish(),NotificationPackageName:z.string().nullish()}).passthrough(),nD=z.object({Rewards:H.nullish()}).passthrough(),rD=z.object({Rules:nh.nullish()}).passthrough(),oD=z.object({Refund:Ua.nullish()}).passthrough(),aD=z.object({Rewards:z.record(z.string(),nD).nullish(),Rules:z.record(z.string(),rD).nullish(),Refund:z.record(z.string(),oD).nullish()}).passthrough(),lD=z.object({MaxPurchaseAgeDays:z.number().nullish(),AllowSandbox:z.boolean().nullish(),RequirePackageMatch:z.boolean().nullish(),MaxReceiptsPerBatch:z.number().nullish(),RefundCheckHorizonDays:z.number().nullish(),RejectCrossUserReceipts:z.boolean().nullish()}).passthrough(),uD=z.object({Enabled:z.boolean().nullish(),Products:z.record(z.string(),iD).nullish(),Stores:z.record(z.string(),sD).nullish(),Presets:aD.nullish(),Validation:lD.nullish(),Refund:Ua.nullish()}).passthrough(),rh=z.object({ProductID:z.string().nullish(),TotalPurchases:z.number().nullish(),DailyPurchases:z.number().nullish(),DailyResetUtc:p.nullish(),LastPurchasedAt:p.nullish(),Owned:z.boolean().nullish(),Refunded:z.boolean().nullish(),PurchaseBlocked:z.boolean().nullish(),Store:z.string().nullish(),LastTransactionID:z.string().nullish()}).passthrough(),oh=z.object({ProductID:z.string().nullish(),PremiumID:z.string().nullish(),Store:z.string().nullish(),OriginalTransactionID:z.string().nullish(),LastTransactionID:z.string().nullish(),ExpiresAt:p.nullish(),AutoRenew:z.boolean().nullish(),Status:z.string().nullish(),RenewalCount:z.number().nullish(),LastStoreCheckAt:p.nullish(),LastStoreCheckError:z.string().nullish(),UpdatedAt:p.nullish()}).passthrough(),cD=z.object({Products:z.record(z.string(),rh).nullish(),LifetimeSpendUsdCents:z.number().nullish(),Subscriptions:z.record(z.string(),oh).nullish(),LastRefundCheckAt:p.nullish(),TotalPurchases:z.number().nullish(),FirstPurchaseAt:p.nullish(),LastPurchaseAt:p.nullish()}).passthrough(),pD=z.object({ProductID:z.string(),Available:z.boolean(),Owned:z.boolean(),Blocked:z.boolean(),Reason:z.string().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish()}).passthrough(),ah=z.object({ServerTimeUtc:p,Purchase:uD.nullish(),Availability:z.array(pD).nullish()}),lh=z.object({ServerTimeUtc:p,Purchase:cD.nullish()}),dD={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},hD=z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),qa=z.object({ServerTimeUtc:p,Store:ji.nullish(),ProductID:z.string().nullish(),TransactionID:z.string().nullish(),Status:hD.nullish(),Granted:z.boolean().nullish(),Quantity:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish(),ProductState:rh.nullish(),Premium:sr.nullish(),Subscription:ir.nullish(),SubscriptionMirror:oh.nullish()}).passthrough(),uh=z.object({ServerTimeUtc:p,ProductID:z.string().nullish(),Stars:z.number().nullish(),InvoiceLink:z.string(),ExpiresAt:p.nullish()}).passthrough(),ch=Rt(qa),Yt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var rr=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(Yt.GetDefinitions,e,ah)}getUserState(e){return this.send(Yt.GetUserState,e,lh)}validatePurchase(e){return this.send(Yt.ValidatePurchase,e,qa)}validatePurchasesBatch(e){return this.send(Yt.ValidatePurchasesBatch,e,ch)}createTelegramInvoice(e){return this.send(Yt.CreateTelegramInvoice,e,uh)}};var mD=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),ph=z.object({Reward:H.nullish(),Weight:z.number().nullish(),AmountRange:mD.nullish()}).passthrough(),yi=z.object({SlotID:z.string().nullish(),MinRolls:z.number().nullish(),MaxRolls:z.number().nullish(),Pool:z.array(ph).nullish()}).passthrough(),Ri=z.object({RuleID:z.string().nullish(),Threshold:z.number().nullish(),Pool:z.array(ph).nullish()}).passthrough(),fD=z.object({RewardSlots:z.array(yi).nullish()}).passthrough(),gD=z.object({PityRules:z.array(Ri).nullish()}).passthrough(),or=z.object({SlotPresets:z.record(z.string(),fD).nullish(),PityPresets:z.record(z.string(),gD).nullish()}).passthrough();var yD=z.object({RuleID:z.string(),BoxIndex:z.number().nullish()}),dh=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,LootboxID:z.string(),OpenedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish(),Results:z.array(M).nullish(),TriggeredPity:z.array(yD).nullish()}),RD=z.object({RewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),CD=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxDrops:j.nullish()}).passthrough(),SD=z.object({LootboxID:z.string(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:le.nullish(),RewardSlots:z.array(yi).nullish(),PityRules:z.array(Ri).nullish(),Presets:RD.nullish(),RewardMultiplier:Qi.nullish(),SupplyLimits:z.array(CD).nullish(),MaxOpenCount:z.number().nullish()}).passthrough(),xD=z.object({MaxOpenCount:z.number().nullish()}).passthrough(),Ba=z.object({Definitions:z.record(z.string(),SD).nullish(),RewardPools:or.nullish(),Settings:xD.nullish()}).passthrough(),hh=z.object({LootboxDefinitions:Ba.nullish()}),ar={GetDefinitions:"GetDefinitions",Open:"Open"};var lr=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(ar.GetDefinitions,e,hh)}open(e){return this.send(ar.Open,e,De(dh))}};var bD=z.object({}).passthrough().transform(r=>r),DD=z.object({}).passthrough().transform(r=>r),PD=z.object({}).passthrough().transform(r=>r),ID=z.object({}).passthrough().transform(r=>r),vD=z.object({}).passthrough().transform(r=>r),mh=z.object({ServerTimeUtc:p,CalendarID:z.string(),DayNumber:z.number().nullish(),DailyState:bD,Resources:M.nullish(),Inventory:K.nullish()}),fh=z.object({ServerTimeUtc:p,AccrualID:z.string(),AccruedSeconds:j.nullish(),AppliedRatePerSecond:z.number().nullish(),IdleState:DD,Resources:M.nullish(),Inventory:K.nullish()}),gh=z.object({ServerTimeUtc:p,ComebackID:z.string(),ClaimedTierIndex:z.number().nullish(),ComebackState:PD,Resources:M.nullish(),Inventory:K.nullish()}),yh=z.object({ServerTimeUtc:p,ClaimID:z.string(),ClaimState:ID,Resources:M.nullish(),Inventory:K.nullish()}),Rh=z.object({Enabled:z.boolean(),Multiplier:z.number().nullish(),Progress:j.nullish(),Source:z.string().nullish(),SourceKey:z.string().nullish()}),TD=z.object({RewardMode:z.string().nullish(),RewardStackLowerTiers:z.boolean().nullish()}).passthrough(),AD=z.object({DayNumber:z.number().nullish(),Rewards:H.nullish(),IsMilestone:z.boolean().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Bi=z.object({Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),La=z.object({Availability:Q.nullish()}).passthrough(),kD=z.object({Availability:z.record(z.string(),Bi).nullish()}).passthrough(),zD=z.object({CalendarID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Days:z.array(AD).nullish(),IsLooping:z.boolean().nullish(),MissBehavior:z.string().nullish(),ResetByDays:z.number().nullish(),MissThresholdMultiplier:z.number().nullish(),ClaimMode:z.string().nullish(),ClaimCooldownSeconds:z.number().nullish(),Availability:Bi.nullish(),Presets:La.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),wD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Multiplier:z.number().nullish()}).passthrough(),MD=z.object({BaseRatePerSecond:z.number().nullish(),PowerCoefficient:z.number().nullish(),BoardRankCoefficient:z.number().nullish(),EquipmentBonusEnabled:z.boolean().nullish(),EquipmentCharacterID:z.string().nullish(),PremiumMultipliers:z.array(wD).nullish()}).passthrough(),OD=z.object({MinCharacterLevel:z.number().nullish(),RequirementsCharacterID:z.string().nullish(),Availability:Bi.nullish(),RequiredItemIDs:z.array(z.string()).nullish(),RequiredEquippedItemIDs:z.array(z.string()).nullish()}).passthrough(),ED=z.object({AccrualID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rate:MD.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:z.number().nullish(),MinClaimSeconds:z.number().nullish(),Requirements:OD.nullish(),FirstClaimMode:z.string().nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),UD=z.object({MinAbsenceSeconds:z.number().nullish(),Rewards:H.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),qD=z.object({ComebackID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(UD).nullish(),ClaimCooldownSeconds:z.number().nullish(),ClaimWindowSeconds:z.number().nullish(),TrackPresenceOnRead:z.boolean().nullish(),Availability:Bi.nullish(),Presets:La.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),BD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),CooldownSeconds:z.number().nullish(),MaxClaimsPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish(),TotalClaimLimit:z.number().nullish()}).passthrough(),LD=z.object({ClaimID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Mode:z.string().nullish(),Rewards:H.nullish(),PremiumLimitOverrides:z.array(BD).nullish(),Availability:Bi.nullish(),Presets:La.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),Ga=z.object({TierRewards:TD.nullish(),MilestoneRewardMultiplier:Qi.nullish(),DailyCalendars:z.record(z.string(),zD).nullish(),IdleAccruals:z.record(z.string(),ED).nullish(),Comebacks:z.record(z.string(),qD).nullish(),Claims:z.record(z.string(),LD).nullish(),Presets:kD.nullish()}).passthrough(),Ch=z.object({RewardDefinitions:Ga.nullish()}),Sh=z.object({Rewards:vD.nullish()}),Mt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var ur=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Mt.GetRewardDefinitions,e,Ch)}getUserRewardsState(e){return this.send(Mt.GetUserRewardsState,e,Sh)}getMilestoneRewardMultiplier(e){return this.send(Mt.GetMilestoneRewardMultiplier,e,Rh)}claimDailyReward(e){return this.send(Mt.ClaimDailyReward,e,mh)}collectIdleAccrual(e){return this.send(Mt.CollectIdleAccrual,e,fh)}claimComebackReward(e){return this.send(Mt.ClaimComebackReward,e,gh)}claimReward(e){return this.send(Mt.ClaimReward,e,yh)}};var cr=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(at.GetTutorialDefinitions,e,Bl)}getUserTutorialState(e){return this.send(at.GetUserTutorialState,e,$i)}startFlow(e){return this.send(at.StartFlow,e,Et)}reportStepShown(e){return this.send(at.ReportStepShown,e,Et)}completeStep(e){return this.send(at.CompleteStep,e,Et)}completeStepsBatch(e){return this.send(at.CompleteStepsBatch,e,Fl)}skipStep(e){return this.send(at.SkipStep,e,Et)}skipFlow(e){return this.send(at.SkipFlow,e,Et)}claimFlowReward(e){return this.send(at.ClaimFlowReward,e,Gl)}resetFlow(e){return this.send(at.ResetFlow,e,Et)}};var GD={Open:"Open",Application:"Application"},FD=z.enum(["Open","Application"]).catch("Open"),VD={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},xh=z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),ND={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Fa=z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),_D={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var Xt={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},jD=z.object({CampaignID:z.string().nullish(),DisplayNameKey:z.string().nullish(),DescriptionKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),IsRunning:z.boolean().nullish()}).passthrough(),bh=z.object({IsEnabled:z.boolean().nullish(),CreatorPortalUrl:z.string().nullish(),ParticipationMode:FD.nullish(),IsCreator:z.boolean().nullish(),CreatorStatus:xh.nullish(),VerificationCode:z.string().nullish(),TeamID:z.string().nullish(),Campaigns:z.array(jD).nullish()}).passthrough(),WD=z.object({Earned:z.number().nullish(),Mature:z.number().nullish(),CountedMetrics:z.record(z.string(),z.number()).nullish(),ReachedMilestones:z.array(z.string()).nullish(),CappedBySubmissionLimit:z.boolean().nullish(),CappedByCreatorLimit:z.boolean().nullish(),NotPaidAsCopy:z.boolean().nullish()}).passthrough(),QD=z.object({CampaignID:z.string().nullish(),CurrencyKind:Fa.nullish(),CurrencyID:z.string().nullish(),NetworkID:z.string().nullish(),Earned:z.number().nullish(),Mature:z.number().nullish(),Granted:z.number().nullish(),Paid:z.number().nullish(),Overpaid:z.number().nullish(),Claimable:z.number().nullish(),BySubmission:z.record(z.string(),WD).nullish(),ComputedAt:z.string().nullish()}).passthrough(),KD=z.object({PayoutID:z.string().nullish(),CampaignID:z.string().nullish(),Amount:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Fa.nullish(),NetworkID:z.string().nullish(),PaidAt:z.string().nullish()}).passthrough(),Dh=z.object({ServerTimeUtc:z.string().nullish(),HoldDays:z.number().nullish(),Campaigns:z.array(QD).nullish(),Payouts:z.array(KD).nullish()}).passthrough(),Ph=z.object({CampaignID:z.string().nullish(),PayoutID:z.string().nullish(),Claimed:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Fa.nullish(),NetworkID:z.string().nullish(),RemainingFraction:z.number().nullish(),IdempotentReplay:z.boolean().nullish(),Message:z.string().nullish()}).passthrough(),HD=z.object({To:z.string().nullish(),Amount:z.string().nullish()}).passthrough(),$D=z.object({ContractAddress:z.string().nullish(),TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),Signature:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(HD).nullish()}).passthrough(),JD=z.object({Kind:z.string().nullish(),Target:z.string().nullish(),Required:z.number().nullish(),Actual:z.number().nullish(),Passed:z.boolean().nullish()}).passthrough(),Ih=z.object({Passed:z.boolean().nullish(),Approved:z.boolean().nullish(),Status:xh.nullish(),WalletMissing:z.boolean().nullish(),WalletConnectAllowed:z.boolean().nullish(),Conditions:z.array(JD).nullish()}).passthrough(),ZD=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),YD=z.object({ProgramID:z.string().nullish(),Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(ZD).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),vh=z.object({ServerTimeUtc:z.string().nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ChainID:z.number().nullish(),CurrencyID:z.string().nullish(),AmountNative:z.number().nullish(),NetAmountNative:z.number().nullish(),BurnAmountNative:z.number().nullish(),AmountUsd:z.number().nullish(),ExpiresAt:z.string().nullish(),EvmSignature:$D.nullish(),SolanaSignature:YD.nullish(),StateDelta:fi.nullish()}).passthrough();var pr=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(Xt.GetCommunityMarketingState,e,bh)}getEarnings(e){return this.send(Xt.GetEarnings,e,Dh)}claim(e){return this.send(Xt.Claim,e,Ph)}checkJoinEligibility(e){return this.send(Xt.CheckJoinEligibility,e,Ih)}withdrawCryptoReward(e){return this.send(Xt.WithdrawCryptoReward,e,vh)}};var dr=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send($e.GetChatDefinitions,e,xu)}getChannels(e){return this.send($e.GetChannels,e,zs)}poll(e){return this.send($e.Poll,e,bu)}getHistory(e){return this.send($e.GetHistory,e,Du)}getConversations(e){return this.send($e.GetConversations,e,vu)}sendMessage(e){return this.send($e.SendMessage,e,Pu)}openDirectChannel(e){return this.send($e.OpenDirectChannel,e,Iu)}markRead(e){return this.send($e.MarkRead,e,hi)}joinChannel(e){return this.send($e.JoinChannel,e,hi)}leaveChannel(e){return this.send($e.LeaveChannel,e,hi)}reportMessage(e){return this.send($e.ReportMessage,e,Tu)}ignoreUser(e){return this.send($e.IgnoreUser,e,hi)}unignoreUser(e){return this.send($e.UnignoreUser,e,hi)}};var hr=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(mi.GetPushConfig,e,zu)}subscribePush(e){return this.send(mi.SubscribePush,e,vo)}unsubscribePush(e){return this.send(mi.UnsubscribePush,e,Le)}getPushSubscriptions(e){return this.send(mi.GetPushSubscriptions,e,wu)}};var mr=class extends B{constructor(e){super(e,"Localization");}send(e,t,i,s){let n=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${n}:${t.Locale}`:n,...s})}getLocalizationManifest(e){return this.send($n.GetLocalizationManifest,e,Kd)}getLocalizationTable(e){return this.send($n.GetLocalizationTable,e,Hd)}};var fr=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(mt.GetQuestDefinitions,e,Hi)}getUserQuestState(e){return this.send(mt.GetUserQuestState,e,Il)}refreshQuestCycles(e){return this.send(mt.RefreshQuestCycles,e,Le)}claimQuestReward(e){return this.send(mt.ClaimQuestReward,e,uo)}claimQuestRewardsBatch(e){return this.send(mt.ClaimQuestRewardsBatch,e,Al)}claimMilestoneReward(e){return this.send(mt.ClaimMilestoneReward,e,co)}claimMilestoneRewardsBatch(e){return this.send(mt.ClaimMilestoneRewardsBatch,e,kl)}claimGroupCompletionReward(e){return this.send(mt.ClaimGroupCompletionReward,e,vl)}addQuestProgress(e){return this.send(mt.AddQuestProgress,e,Tl)}};var gr=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ut.GetActiveEvents,e,Bs)}getDefinitions(e){return this.send(ut.GetDefinitions,e,qs)}getUserLteState(e){return this.send(ut.GetUserLteState,e,Uu)}grantTokens(e){return this.send(ut.GrantTokens,e,M)}spendTokens(e){return this.send(ut.SpendTokens,e,ko)}claimMilestone(e){return this.send(ut.ClaimMilestone,e,zo)}claimMilestonesBatch(e){return this.send(ut.ClaimMilestonesBatch,e,wo)}claimAllMilestones(e){return this.send(ut.ClaimAllMilestones,e,wo)}spendTokensBatch(e){return this.send(ut.SpendTokensBatch,e,qu)}grantTokensBatch(e){return this.send(ut.GrantTokensBatch,e,Bu)}};var yr=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(je.GetDefinitions,e,js)}getLeaderboard(e){return this.send(je.GetLeaderboard,e,Ai)}getMyProgress(e){return this.send(je.GetMyProgress,e,Gs)}submitScore(e){return this.send(je.SubmitScore,e,Fs)}submitScoreFromSource(e){return this.send(je.SubmitScoreFromSource,e,Fs)}claimCycleReward(e){return this.send(je.ClaimCycleReward,e,Vs)}claimMilestone(e){return this.send(je.ClaimMilestone,e,Ns)}getFriendsLeaderboard(e){return this.send(je.GetFriendsLeaderboard,e,Ai)}getLeaderboardsBatch(e){return this.send(je.GetLeaderboardsBatch,e,Fu)}getProgressBatch(e){return this.send(je.GetProgressBatch,e,_s)}claimCycleRewardsBatch(e){return this.send(je.ClaimCycleRewardsBatch,e,Vu)}claimMilestonesBatch(e){return this.send(je.ClaimMilestonesBatch,e,Nu)}submitScoresBatch(e){return this.send(je.SubmitScoresBatch,e,_u)}claimAllRewardsBatch(e){return this.send(je.ClaimAllRewardsBatch,e,ju)}getOverviewBatch(e){return this.send(je.GetOverviewBatch,e,Wu)}};var Rr=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Bt.GetDefinitions,e,Ks)}getActiveSeason(e){return this.send(Bt.GetActiveSeason,e,Qs)}getUserState(e){return this.send(Bt.GetUserState,e,Mo)}grantStatusTokens(e){return this.send(Bt.GrantStatusTokens,e,$u)}claimTierReward(e){return this.send(Bt.ClaimTierReward,e,Oo)}claimTierRewardsBatch(e){return this.send(Bt.ClaimTierRewardsBatch,e,Ju)}};var Cr=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Zt.GetDefinitions,e,ih)}getUserState(e){return this.send(Zt.GetUserState,e,sh)}activateTrial(e){return this.send(Zt.ActivateTrial,e,nr)}purchaseItemOrCurrency(e){return this.send(Zt.PurchaseWithResources,e,De(nr))}purchaseRealMoney(e){return this.send(Zt.PurchaseRealMoney,e,nr)}};var Sr=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(We.GetCharacterDefinitions,e,Zs)}getUserCharacters(e){return this.send(We.GetUserCharacters,e,ic)}unlockCharacter(e){return this.send(We.UnlockCharacter,e,De(Bo))}upgradeStatLevel(e){return this.send(We.UpgradeStatLevel,e,De(Uo))}upgradeCharacterLevel(e){return this.send(We.UpgradeCharacterLevel,e,De(qo))}equipItems(e){return this.send(We.EquipItems,e,sc)}unequipItems(e){return this.send(We.UnequipItems,e,nc)}unequipAllCharacters(e){return this.send(We.UnequipAllCharacters,e,rc)}unlockCharactersBatch(e){return this.send(We.UnlockCharactersBatch,e,cc)}upgradeCharacterLevelsBatch(e){return this.send(We.UpgradeCharacterLevelsBatch,e,pc)}upgradeStatLevelsBatch(e){return this.send(We.UpgradeStatLevelsBatch,e,dc)}unlockSkin(e){return this.send(We.UnlockSkin,e,De(oc))}equipSkin(e){return this.send(We.EquipSkin,e,ac)}unequipSkin(e){return this.send(We.UnequipSkin,e,lc)}getCharacterSkins(e){return this.send(We.GetCharacterSkins,e,uc)}};var xr=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(xt.CreateMatch,e,Wp)}updateMatch(e){return this.send(xt.UpdateMatch,e,Qp)}cancelMatch(e){return this.send(xt.CancelMatch,e,Kp)}instantBattle(e){return this.send(xt.InstantBattle,e,Hp)}saveStrategy(e){return this.send(xt.SaveStrategy,e,Le)}getMyMatches(e){return this.send(xt.GetMyMatches,e,da)}getAvailableMatches(e){return this.send(xt.GetAvailableMatches,e,da)}getDefinitions(e){return this.send(xt.GetDefinitions,e,Yp)}};var XD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Th=z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),eP={None:"None",Min:"Min",Average:"Average",Max:"Max"},tP=z.enum(["None","Min","Average","Max"]).catch("None"),iP={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},sP=z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),nP={Clamp:"Clamp",Reject:"Reject"},rP=z.enum(["Clamp","Reject"]).catch("Clamp"),oP=z.object({ItemInstanceID:z.string().nullish(),ItemID:z.string().nullish(),Level:z.number().nullish(),Units:z.number().nullish()}),aP=z.object({Index:z.number().nullish(),BurnedItemIDs:z.array(z.string()).nullish(),RolledCollectionID:z.string().nullish(),UsedCollections:z.record(z.string(),z.number()).nullish(),Output:oo.nullish(),OutputLevel:z.number().nullish(),BurnedInstances:z.array(oP).nullish()}),Ah=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,Type:Th.nullish(),CraftID:z.string(),CraftedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),InputRarity:z.string().nullish(),OutputRarity:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish(),Results:z.array(aP).nullish()}),lP=z.object({CraftID:z.string().nullish(),Type:Th.nullish(),CatalogID:z.string().nullish(),CollectionID:z.string().nullish(),InputRarityID:z.string().nullish(),OutputRarityID:z.string().nullish(),RequiredItemCount:z.number().nullish(),PriceOptions:le.nullish(),OutputLevelMode:tP.nullish(),InputSelection:sP.nullish(),OutputLevelOverflow:rP.nullish()}).passthrough(),Va=z.object({Definitions:z.record(z.string(),lP).nullish()}).passthrough(),kh=z.object({ServerTimeUtc:p.nullish(),CraftDefinitions:Va.nullish()}),br={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Dr=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(br.GetDefinitions,e,kh)}craft(e){return this.send(br.Craft,e,De(Ah))}};var uP=2e5,Pr=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,De(tn),{timeoutMs:uP,autoRetry:false})}readGeneration(e,t){return this.send(e,t,tn,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Ne.GetDefinitions,e,xc)}generateText(e){return this.generate(Ne.GenerateText,e)}getText(e){return this.readGeneration(Ne.GetText,e)}generateImage(e){return this.generate(Ne.GenerateImage,e)}editImage(e){return this.generate(Ne.EditImage,e)}getImage(e){return this.readGeneration(Ne.GetImage,e)}generateVideo(e){return this.generate(Ne.GenerateVideo,e)}getVideo(e){return this.readGeneration(Ne.GetVideo,e)}generateAudio(e){return this.generate(Ne.GenerateAudio,e)}getAudio(e){return this.readGeneration(Ne.GetAudio,e)}generateMusic(e){return this.generate(Ne.GenerateMusic,e)}getMusic(e){return this.readGeneration(Ne.GetMusic,e)}generateThreeD(e){return this.generate(Ne.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Ne.GetThreeD,e)}listGenerations(e){return this.send(Ne.ListGenerations,e,Sc)}getGeneration(e){return this.readGeneration(Ne.GetGeneration,e)}};var cP={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},pP=z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),zh=z.object({}).passthrough().transform(r=>r),Ci=z.object({CollectibleID:z.string(),Rarity:z.number().nullish(),IsSpecial:z.boolean().nullish(),IsDuplicate:z.boolean().nullish(),CollectionCurrencyConverted:z.number().nullish()}),wh=z.object({GrantedCollectibles:z.array(Ci).nullish(),DuplicateCollectibles:z.array(Ci).nullish(),CollectionCurrencyEarned:j.nullish()}),Mh=z.object({CreditsConfirmation:me.nullish(),OpenedCount:z.number().nullish(),Packs:z.array(wh).nullish(),GrantedCollectibles:z.array(Ci).nullish(),DuplicateCollectibles:z.array(Ci).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),NewlyCompletedSetIDs:z.array(z.string()).nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),Oh=z.object({OpenedCount:z.number().nullish(),Chests:z.array(wh).nullish(),GrantedCollectibles:z.array(Ci).nullish(),DuplicateCollectibles:z.array(Ci).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),Eh=z.object({GrantedCollectibleID:z.string().nullish(),NewlyCompletedSetID:z.string().nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Na=z.object({SetID:z.string(),Resources:M.nullish(),Inventory:K.nullish()}),Uh=z.array(Te(Na)),qh=z.object({Resources:M.nullish(),Inventory:K.nullish()}),dP=z.object({OfferID:z.string(),TitleID:z.string().nullish(),CollectionID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderPublicData:qe.nullish(),OfferedCollectibleID:z.string().nullish(),OfferedCollectibleIsSpecial:z.boolean().nullish(),ReceiverUserID:z.string().nullish(),RequestedCollectibleID:z.string().nullish(),RequestedCollectibleIsSpecial:z.boolean().nullish(),Status:pP.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RespondedAtUtc:p.nullish(),DeclineReason:z.string().nullish(),IsSpecialTradeEvent:z.boolean().nullish(),SpecialTradeEventID:z.string().nullish()}).passthrough(),Bh=z.object({OfferID:z.string(),ExpiresAtUtc:p.nullish(),Resources:M.nullish()}),Lh=z.object({OfferID:z.string(),Resources:M.nullish()}),Gh=z.object({OfferID:z.string(),ReceivedCollectibleID:z.string().nullish(),ReceivedIsSpecial:z.boolean().nullish(),SentCollectibleID:z.string().nullish(),SentCollectibleIsSpecial:z.boolean().nullish(),Transfer:z.unknown().nullish()}),Fh=z.object({OfferID:z.string(),Resources:M.nullish()}),_a=z.object({Offers:z.array(dP).nullish()}),hP=z.object({CollectibleID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rarity:z.number().nullish(),HasSpecialVersion:z.boolean().nullish(),SortOrder:z.number().nullish()}).passthrough(),mP=z.object({SetID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SortOrder:z.number().nullish(),Collectibles:z.array(hP).nullish(),SetCompletionReward:H.nullish()}).passthrough(),fP=z.object({CollectionID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SeasonChainID:z.string().nullish(),Sets:z.array(mP).nullish(),GrandPrize:H.nullish()}).passthrough(),Vh=z.object({BonusRewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),gP=z.object({PackTypeID:z.string().nullish(),PriceOptions:le.nullish(),BonusRewardSlots:z.array(yi).nullish(),PityRules:z.array(Ri).nullish(),Presets:Vh.nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectibleCount:z.number().nullish(),MaxOpenCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),GuaranteeMaxRarity:z.boolean().nullish(),RarityWeights:z.record(z.string(),z.number()).nullish(),ColorTier:z.number().nullish()}).passthrough(),yP=z.object({Rarity:z.number().nullish(),CollectionCurrencyGranted:z.number().nullish()}).passthrough(),RP=z.object({CollectionChestID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectionCurrencyCost:z.number().nullish(),MaxOpenCount:z.number().nullish(),MinCollectibleCount:z.number().nullish(),MaxCollectibleCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),BonusRewardSlots:z.array(yi).nullish(),PityRules:z.array(Ri).nullish(),Presets:Vh.nullish(),Tier:z.number().nullish()}).passthrough(),CP=z.object({SpecialTradeEventID:z.string().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),AllowedSpecialCollectibleIDs:z.array(z.string()).nullish(),SpecialTradeEventDailyTradeLimit:z.number().nullish()}).passthrough(),SP=z.object({MaxPackOpenCount:z.number().nullish(),MaxChestOpenCount:z.number().nullish()}).passthrough(),Ir=z.object({Collections:z.record(z.string(),fP).nullish(),PackTypes:z.record(z.string(),gP).nullish(),CollectionChests:z.array(RP).nullish(),DuplicateConversions:z.array(yP).nullish(),DailyTradeLimit:z.number().nullish(),CollectibleJokerCatalogID:z.string().nullish(),CollectibleJokerItemID:z.string().nullish(),SpecialTradeEvents:z.array(CP).nullish(),RewardPools:or.nullish(),Settings:SP.nullish()}).passthrough(),Qe={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 vr=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Qe.GetDefinitions,e,Ir)}getUserState(e){return this.send(Qe.GetUserState,e,zh)}openPack(e){return this.send(Qe.OpenPack,e,De(Mh))}openCollectionChest(e){return this.send(Qe.OpenCollectionChest,e,Oh)}useCollectibleJoker(e){return this.send(Qe.UseCollectibleJoker,e,Eh)}claimSetReward(e){return this.send(Qe.ClaimSetReward,e,Na)}claimSetRewardsBatch(e){return this.send(Qe.ClaimSetRewardsBatch,e,Uh)}claimGrandPrize(e){return this.send(Qe.ClaimGrandPrize,e,qh)}sendTradeOffer(e){return this.send(Qe.SendTradeOffer,e,Bh)}cancelTradeOffer(e){return this.send(Qe.CancelTradeOffer,e,Lh)}acceptTradeOffer(e){return this.send(Qe.AcceptTradeOffer,e,Gh)}declineTradeOffer(e){return this.send(Qe.DeclineTradeOffer,e,Fh)}getMyTradeOffers(e){return this.send(Qe.GetMyTradeOffers,e,_a)}getIncomingTradeOffers(e){return this.send(Qe.GetIncomingTradeOffers,e,_a)}};var Tr=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(ft.GetDefinitions,e,on)}getActiveEvent(e){return this.send(ft.GetActiveEvent,e,Pc)}getUserState(e){return this.send(ft.GetUserState,e,rn)}getGroupState(e){return this.send(ft.GetGroupState,e,_o)}joinOrCreateGroup(e){return this.send(ft.JoinOrCreateGroup,e,_o)}spin(e){return this.send(ft.Spin,e,De(vc))}claimObjectReward(e){return this.send(ft.ClaimObjectReward,e,jo)}claimGrandPrize(e){return this.send(ft.ClaimGrandPrize,e,jo)}leaveGroup(e){return this.send(ft.LeaveGroup,e,Tc)}};var Ar=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(St.GetDefinition,e,Lc)}getUserState(e){return this.send(St.GetUserState,e,Gc)}getActiveDeals(e){return this.send(St.GetActiveDeals,e,un)}dismissDeal(e){return this.send(St.DismissDeal,e,Vc)}executeNode(e){return this.send(St.ExecuteNode,e,De(Fc))}recordShow(e){return this.send(St.RecordShow,e,Nc)}claimMilestone(e){return this.send(St.ClaimMilestone,e,_c)}claimMilestonesBatch(e){return this.send(St.ClaimMilestonesBatch,e,jc)}};var xP=z.object({}).passthrough().transform(r=>r),bP=z.object({FeatureKey:z.string().nullish(),IsEnabled:z.boolean().nullish(),Rate:z.number().nullish(),Basis:z.string().nullish(),SourceCurrencyID:z.string().nullish(),TargetCurrencyID:z.string().nullish(),MinSourceAmount:z.number().nullish(),MaxRewardPerOperation:z.number().nullish(),Limits:Ce.nullish()}).passthrough(),ja=z.object({IsEnabled:z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:z.record(z.string(),Fe).nullish(),SpendRewards:z.array(bP).nullish(),Qualification:z.object({}).passthrough().transform(r=>r).nullish()}).passthrough(),Wa=z.object({Pending:z.boolean().nullish(),Qualified:z.boolean().nullish(),Groups:z.array(z.object({GroupID:z.string().nullish(),Met:z.boolean().nullish(),Conditions:z.array(z.object({Type:z.string().nullish(),Met:z.boolean().nullish(),Current:z.number().nullish(),Required:z.number().nullish()}).passthrough()).nullish()}).passthrough()).nullish()}).passthrough(),Nh=z.object({ReferralDefinitions:ja.nullish()}).passthrough(),_h=z.object({Referral:xP.nullish(),InviteUrl:z.string().nullish(),Qualification:Wa.nullish()}).passthrough(),jh=z.object({QualificationPending:z.boolean().nullish(),Qualification:Wa.nullish()}).passthrough(),Wh=z.object({ReferralCode:z.string().nullish(),ReferrerUserID:z.string().nullish(),IsFirstActivation:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),QualificationPending:z.boolean().nullish(),Qualification:Wa.nullish()}).passthrough(),Qa=z.object({RewardID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}).passthrough(),Qh=Rt(Qa),jt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var kr=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(jt.GetDefinitions,e,Nh)}getUserState(e){return this.send(jt.GetUserState,e,_h)}activateReferralCode(e){return this.send(jt.ActivateReferralCode,e,Wh)}claimInviteReward(e){return this.send(jt.ClaimInviteReward,e,Qa)}claimInviteRewardsBatch(e){return this.send(jt.ClaimInviteRewardsBatch,e,Qh)}checkQualification(e){return this.send(jt.CheckQualification,e,jh)}};var zr=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(st.GetDefinitions,e,$c)}getMessages(e){return this.send(st.GetMessages,e,Jc)}getUnreadCount(e){return this.send(st.GetUnreadCount,e,dn)}readMessages(e){return this.send(st.ReadMessages,e,Ko)}claimReward(e){return this.send(st.ClaimReward,e,hn)}claimRewardsBatch(e){return this.send(st.ClaimRewardsBatch,e,hn)}claimAll(e){return this.send(st.ClaimAll,e,hn)}deleteMessages(e){return this.send(st.DeleteMessages,e,Ko)}sendGift(e){return this.send(st.SendGift,e,Zc)}sendTransfer(e){return this.send(st.SendTransfer,e,Yc)}getGiftStatus(e){return this.send(st.GetGiftStatus,e,Xc)}};var wr=class extends B{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(fn.RequestAdPermit,e,ep)}completeView(e){return this.send(fn.CompleteView,e,tp)}};var Mr=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Se.GetFriendsList,e,zi)}getIncomingRequests(e){return this.send(Se.GetIncomingRequests,e,zi)}getOutgoingRequests(e){return this.send(Se.GetOutgoingRequests,e,zi)}getRecommendedFriends(e){return this.send(Se.GetRecommendedFriends,e,zi)}sendFriendRequest(e){return this.send(Se.SendFriendRequest,e,wi)}acceptFriendRequest(e){return this.send(Se.AcceptFriendRequest,e,wi)}declineFriendRequest(e){return this.send(Se.DeclineFriendRequest,e,wi)}removeFriend(e){return this.send(Se.RemoveFriend,e,wi)}getInbox(e){return this.send(Se.GetInbox,e,sp)}markInboxSeen(e){return this.send(Se.MarkInboxSeen,e,Mi)}getInboxUnread(e){return this.send(Se.GetInboxUnread,e,Mi)}follow(e){return this.send(Se.Follow,e,Ft)}unfollow(e){return this.send(Se.Unfollow,e,Ft)}getFollowers(e){return this.send(Se.GetFollowers,e,Rn)}getFollowing(e){return this.send(Se.GetFollowing,e,Rn)}block(e){return this.send(Se.Block,e,Ft)}unblock(e){return this.send(Se.Unblock,e,Ft)}getBlocked(e){return this.send(Se.GetBlocked,e,Rn)}react(e){return this.send(Se.React,e,Ft)}unreact(e){return this.send(Se.Unreact,e,Ft)}getMyReactions(e){return this.send(Se.GetMyReactions,e,rp)}getEntityStates(e){return this.send(Se.GetEntityStates,e,np)}addComment(e){return this.send(Se.AddComment,e,Cn)}editComment(e){return this.send(Se.EditComment,e,Cn)}deleteComment(e){return this.send(Se.DeleteComment,e,ap)}getComments(e){return this.send(Se.GetComments,e,op)}report(e){return this.send(Se.Report,e,lp)}};var DP={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var ei=z.object({Target:z.string().nullish(),Operation:z.string().nullish(),Value:z.number().nullish()}).passthrough(),PP=z.object({BoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:le.nullish(),Effect:ei.nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),Or=z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Ka=z.object({Availability:Q.nullish(),Effects:Q.nullish()}).passthrough(),IP=z.object({ScheduledBoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Effects:z.array(ei).nullish(),Availability:Or.nullish(),Presets:Ka.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),vP=z.object({ChainedBoostID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Effects:z.array(ei).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),TP=z.object({ChainID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Phases:z.array(vP).nullish(),Availability:Or.nullish(),Presets:Ka.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),AP=z.object({TriggeredBoostID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Sources:z.array(ot).nullish(),Effects:z.array(ei).nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Availability:Or.nullish(),Presets:Ka.nullish()}).passthrough(),kP=z.object({MaxAddPercent:z.number().nullish(),MaxMultiply:z.number().nullish(),MaxAddFlat:z.number().nullish()}).passthrough(),zP=z.object({Effects:z.array(ei).nullish()}).passthrough(),wP=z.object({Availability:z.record(z.string(),Or).nullish(),Effects:z.record(z.string(),zP).nullish()}).passthrough(),MP=z.object({StackingCaps:z.record(z.string(),kP).nullish()}).passthrough(),Er=z.object({Definitions:z.record(z.string(),PP).nullish(),ScheduledBoosts:z.record(z.string(),IP).nullish(),BoostChains:z.record(z.string(),TP).nullish(),TriggeredBoosts:z.record(z.string(),AP).nullish(),Settings:MP.nullish(),Presets:wP.nullish()}).passthrough(),Kh=z.object({InstanceID:z.string(),BoostID:z.string(),ActivatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RemainingCharges:z.number().nullish(),EffectSnapshot:ei.nullish(),SourceType:z.string().nullish(),SourceRef:z.string().nullish()}).passthrough();z.object({Date:p.nullish(),DailyCount:z.number().nullish(),LastFiredUtc:p.nullish()}).passthrough();var Hh=z.object({ServerTimeUtc:p.nullish(),Active:z.record(z.string(),Kh).nullish()}),$h=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),BoostID:z.string().nullish(),StackingPolicy:z.string().nullish(),ActivatedBoost:Kh.nullish(),Resources:M.nullish()}),OP={Scheduled:"Scheduled",Chain:"Chain"},EP=z.object({Kind:z.string().nullish(),SourceID:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),PhaseOrder:z.number().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),Effects:z.array(ei).nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Jh=z.object({ServerTimeUtc:p.nullish(),Windows:z.array(EP).nullish()}),ti={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Ur=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(ti.GetDefinitions,e,Er)}getActive(e){return this.send(ti.GetActive,e,Hh)}getActiveWindows(e){return this.send(ti.GetActiveWindows,e,Jh)}activate(e){return this.send(ti.Activate,e,De($h))}cleanupExpired(e){return this.send(ti.CleanupExpired,e,Le)}};var qr=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(gt.GetUserCustomDataDefinitions,e,Dn)}getMyUserCustomData(e){return this.send(gt.GetMyUserCustomData,e,dp)}getPublicUserCustomDataOf(e){return this.send(gt.GetPublicUserCustomDataOf,e,ta)}setPrivateData(e){return this.send(gt.SetPrivateData,e,ia)}setPublicData(e){return this.send(gt.SetPublicData,e,ia)}deleteKey(e){return this.send(gt.DeleteKey,e,Le)}batchSet(e){return this.send(gt.BatchSet,e,hp)}batchDelete(e){return this.send(gt.BatchDelete,e,mp)}batchGetPublicUserCustomDataOf(e){return this.send(gt.BatchGetPublicUserCustomDataOf,e,fp)}};var UP={Static:"Static",Runtime:"Runtime"},qP={Public:"Public",Private:"Private"},BP=z.enum(["Client","Server","System"]).catch("Client"),LP=z.enum(["String","Int","Bool","Json"]).catch("String"),GP=z.object({Value:z.string().nullish(),UpdatedAt:p.nullish(),Version:z.number().nullish(),LastWriter:BP.nullish(),ExpiresAt:p.nullish()}).passthrough(),Zh=z.record(z.string(),GP),Ha=z.object({StaticVersion:z.number().nullish(),RuntimeVersion:z.number().nullish(),Static:Zh.nullish(),Runtime:Zh.nullish(),NotModified:z.boolean().nullish()}),FP=z.object({KeyID:z.string(),Scope:z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:LP.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),Br=z.object({Keys:z.record(z.string(),FP).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),Li={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Lr=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Li.GetTitleCustomDataDefinitions,e,Br)}getPublicTitleData(e){return this.send(Li.GetPublicTitleData,e,Ha)}getPublicTitleDataKeys(e){return this.send(Li.GetPublicTitleDataKeys,e,Ha)}};var VP={Fast:"Fast",Sequential:"Sequential"},NP={Instant:"Instant",Timed:"Timed"};var _P={Hit:"Hit",Blocked:"Blocked"},jP=z.object({SlotIndex:z.number(),Level:z.number().nullish(),IsDamaged:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish()}).passthrough(),WP=z.object({Symbol:z.union([z.string(),z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:z.string().nullish()}).passthrough();z.object({ElapsedSeconds:z.number().nullish(),Reward:H.nullish()}).passthrough();var QP=z.object({RequiredValue:z.number().nullish(),Reward:H.nullish()}).passthrough(),KP=z.object({Reward:H.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough();z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(QP).nullish(),Rate:KP.nullish()}).passthrough();z.object({PlayedCount:z.number().nullish(),RewardsClaimedCount:z.number().nullish(),InstantClaimsCount:z.number().nullish(),EarlyClaimsCount:z.number().nullish(),LateClaimsCount:z.number().nullish(),AdViewsTotal:z.number().nullish(),StatRewardClaimsCount:z.number().nullish(),StatReportsClampedCount:z.number().nullish(),StatReportsUnknownMetricCount:z.number().nullish()}).passthrough();var Yh=z.object({}).passthrough().transform(r=>r),Xh=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),Ke=z.object({Operation:M.nullish(),ScaleWithRollMultiplier:z.boolean().nullish()}).passthrough(),HP=z.object({Count:z.number().nullish(),Sides:z.number().nullish()}).passthrough(),$P=z.object({ShieldChance:z.number().nullish(),DamagedBuildingChance:z.number().nullish(),RankMultiplierMin:z.number().nullish(),RankMultiplierMax:z.number().nullish(),RankOffsetMin:z.number().nullish(),RankOffsetMax:z.number().nullish(),StageLevelSpread:z.number().nullish()}).passthrough(),JP=z.object({CostMatrixTemplatesByID:z.record(z.string(),z.array(z.array(z.number()))).nullish(),PerBoardGrowth:z.number().nullish(),VisualTemplateCycle:z.array(z.string()).nullish(),EconomyScaledResources:ue.nullish(),ScaleRaidStealWithEconomy:z.boolean().nullish(),ScaleAttackRewardWithEconomy:z.boolean().nullish(),AttackValueFromCostMatrix:z.boolean().nullish(),AttackBlockedRewardFactor:z.number().nullish(),ScaleVictimLossWithEconomy:z.boolean().nullish(),ScaleVictimLossWithTier:z.boolean().nullish(),SynthesizedBuildingSlots:z.number().nullish(),SynthesizedBuildingMaxLevel:z.number().nullish(),DifficultyGrowthPerBoard:z.number().nullish()}).passthrough(),ZP=z.object({CostMatrix:z.array(z.array(z.number())).nullish(),PerBoardGrowth:z.number().nullish(),EconomyScale:z.number().nullish(),ScaledResources:ue.nullish()}).passthrough(),em=z.object({SlotIndex:z.number().nullish(),Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxLevel:z.number().nullish(),MaxLevelReward:H.nullish()}).passthrough(),YP=z.object({Index:z.number().nullish(),Type:z.string().nullish(),CustomTypeID:z.string().nullish(),RandomActionAttackWeight:z.number().nullish(),RandomActionRaidWeight:z.number().nullish(),ChanceTableID:z.string().nullish(),SpecialModeID:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),XP=z.object({Tiles:z.record(z.string(),YP).nullish()}).passthrough(),eI=z.object({Weight:z.number().nullish(),Bonus:Ke.nullish(),Tag:z.string().nullish()}).passthrough(),tI=z.object({Weight:z.number().nullish(),Tag:z.string().nullish(),MinBonusCells:z.number().nullish(),MaxBonusCells:z.number().nullish(),BonusPool:z.array(eI).nullish(),GuaranteedBonus:Ke.nullish(),IsJackpot:z.boolean().nullish(),JackpotFinalMultiplier:z.number().nullish(),JackpotSymbolDistribution:z.record(z.string(),z.number()).nullish()}).passthrough(),iI=z.object({Variants:z.array(tI).nullish()}).passthrough(),sI=z.object({Weight:z.number().nullish(),OutcomeID:z.string().nullish(),Reward:Ke.nullish(),ForceAction:z.string().nullish(),SpecialModeID:z.string().nullish()}).passthrough(),nI=z.object({Outcomes:z.array(sI).nullish()}).passthrough(),tm=z.object({PerAdMultiplierRange:Xh.nullish(),MaxAdViews:z.number().nullish(),AdCreditCost:z.number().nullish(),FormulaKind:z.string().nullish(),ApplyMultiplierOnEarlyClaim:z.boolean().nullish()}).passthrough(),rI=z.object({ElapsedSeconds:z.number().nullish(),Reward:Ke.nullish()}).passthrough(),oI=z.object({Tiers:z.array(rI).nullish(),TierMode:z.string().nullish(),BelowFirstTierReward:Ke.nullish()}).passthrough(),aI=z.object({RequiredValue:z.number().nullish(),Reward:Ke.nullish()}).passthrough(),lI=z.object({Reward:Ke.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough(),uI=z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(aI).nullish(),Rate:lI.nullish()}).passthrough(),im=z.object({MetricsByID:z.record(z.string(),uI).nullish()}).passthrough(),cI=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:Ke.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:le.nullish(),Multipliers:tm.nullish(),Gradation:oI.nullish(),RunStats:im.nullish()}).passthrough(),pI=z.object({Choices:z.array(cI).nullish(),OfferExpireSeconds:z.number().nullish(),ClaimExpireSeconds:z.number().nullish()}).passthrough(),dI=z.object({Chance:z.number().nullish(),RequiredOutcome:z.string().nullish(),Reward:Ke.nullish(),Tag:z.string().nullish()}).passthrough(),hI=z.object({OnPassStart:Ke.nullish(),OnTileLanding:z.record(z.string(),Ke).nullish(),OnAttack:z.record(z.string(),Ke).nullish(),OnRaid:z.record(z.string(),Ke).nullish(),OnBuild:Ke.nullish(),OnStageComplete:Ke.nullish(),OnAttackBonusDrops:z.array(dI).nullish(),ChanceTablesByID:z.record(z.string(),nI).nullish(),SpecialModesByID:z.record(z.string(),pI).nullish()}).passthrough(),sm=z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:z.number().nullish(),MaxShields:z.number().nullish(),Buildings:z.array(em).nullish(),HeistGridBonusConfig:iI.nullish(),StageOperations:hI.nullish(),TileLandingMultiplier:Xh.nullish(),EconomyOverride:ZP.nullish()}).passthrough(),mI=z.object({Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BoardTemplateID:z.string().nullish(),Buildings:z.array(em).nullish(),StageTemplateID:z.string().nullish(),CostMatrixTemplateID:z.string().nullish(),UnitValue:z.number().nullish(),Override:sm.nullish()}).passthrough(),fI=z.object({AttackCooldownSeconds:z.number().nullish(),RaidCooldownSeconds:z.number().nullish(),MaxRecentTargets:z.number().nullish(),LiveOpponentActiveDays:z.number().nullish(),LiveOpponentPoolSize:z.number().nullish(),LiveOpponentPoolCacheSeconds:z.number().nullish(),MaxLiveCandidateReads:z.number().nullish(),VictimImmunitySeconds:z.number().nullish()}).passthrough(),gI=z.object({Enabled:z.boolean().nullish(),IntervalSeconds:z.number().nullish(),MaxPerCatchUp:z.number().nullish(),Chance:z.number().nullish(),AttackWeight:z.number().nullish(),RaidWeight:z.number().nullish(),MinBoardStageLevel:z.number().nullish(),RaidLossMultiplier:z.number().nullish()}).passthrough(),Gr=z.object({RollCurrencyID:z.string().nullish(),ShieldCurrencyID:z.string().nullish(),RaidMode:z.string().nullish(),AllowedRollMultipliers:z.array(z.number()).nullish(),BoardTemplatesByID:z.record(z.string(),XP).nullish(),StageTemplatesByID:z.record(z.string(),sm).nullish(),StagesByLevel:z.record(z.string(),mI).nullish(),SoftCurrencyID:z.string().nullish(),ProceduralEconomy:JP.nullish(),Dice:HP.nullish(),Bots:$P.nullish(),Targeting:fI.nullish(),BotRaids:gI.nullish()}).passthrough(),yI=z.object({IsActive:z.boolean().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AnchorUtc:p.nullish(),RoundDurationSec:z.number().nullish(),PauseBetweenRoundsSec:z.number().nullish(),MaxRounds:z.number().nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),ContributionMin:z.number().nullish(),ContributionMax:z.number().nullish(),ScaleContributionWithRollMultiplier:z.boolean().nullish(),MaxProgress:z.number().nullish(),Milestones:z.record(z.string(),Fe).nullish(),GrandPrize:H.nullish()}).passthrough(),Fr=z.object({Board:Gr.nullish(),CommunityChest:yI.nullish()}).passthrough(),nm=z.object({AttackerGainByOutcome:z.record(z.string(),ue).nullish()}).passthrough(),RI=z.object({TargetUserID:z.string().nullish(),IsBot:z.boolean().nullish(),PublicData:qe.nullish(),TargetBuildingStates:z.array(jP).nullish(),TargetHasShield:z.boolean().nullish(),TargetStageLevel:z.number().nullish(),RaidRewardPreview:nm.nullish()}).passthrough(),CI=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:Ke.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:le.nullish(),Multipliers:tm.nullish(),RunStats:im.nullish()}).passthrough(),SI=z.object({ModeID:z.string().nullish(),Choices:z.array(CI).nullish()}).passthrough(),xI=z.object({GroupID:z.string().nullish(),Delta:j.nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),UnlockedMilestoneIDs:z.array(z.string()).nullish(),Completed:z.boolean().nullish()}).passthrough(),rm=z.object({UsedMultiplier:z.number().nullish(),Steps:z.number().nullish(),DiceValues:z.array(z.number()).nullish(),OldPosition:z.number().nullish(),NewPosition:z.number(),CyclesCompletedDelta:j.nullish(),LandedTileType:z.string().nullish(),Operation:M.nullish(),Inventory:K.nullish(),ActionRequired:z.string().nullish(),ActionData:RI.nullish(),SpecialModeOffer:SI.nullish(),CommunityChestContribution:xI.nullish()}).passthrough(),om=z.object({Outcome:z.string().nullish(),IsBotTarget:z.boolean().nullish(),BuildingIndexHit:z.number().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:It.nullish()}).passthrough(),$a=z.object({Status:z.string().nullish(),Outcome:z.string().nullish(),FoundSymbol:z.union([z.string(),z.number()]).nullish(),FoundBonus:H.nullish(),OpenedIndex:z.number().nullish(),AttemptsLeft:z.number().nullish(),RaidLayout:z.array(WP).nullish(),HeistVariantTag:z.string().nullish(),IsJackpot:z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:It.nullish(),RaidRewardPreview:nm.nullish()}).passthrough(),am=z.object({BuiltIndex:z.number(),NewLevel:z.number().nullish(),StageComplete:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish()}).passthrough(),lm=z.object({CreditsConfirmation:me.nullish(),Mode:z.union([z.string(),z.number()]).nullish(),Operation:M.nullish(),Inventory:K.nullish(),DurationSeconds:z.number().nullish(),StartedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish()}).passthrough(),um=z.object({AdViewsUsed:z.number().nullish(),RolledMultiplier:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),RemainingAdViews:z.number().nullish()}).passthrough(),bI=z.object({MetricID:z.string().nullish(),ReachedTierIndex:z.number().nullish(),RequiredValue:z.number().nullish(),RewardUnits:z.number().nullish()}).passthrough(),cm=z.object({FinalMultiplier:z.number().nullish(),AdViewsUsed:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),IsEarlyClaim:z.boolean().nullish(),ReachedTierIndex:z.number().nullish(),Operation:M.nullish(),Inventory:K.nullish(),AcceptedRunStats:z.record(z.string(),z.number()).nullish(),RunStatAwards:z.array(bI).nullish(),RunStatsClamped:z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),DI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},pm=z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),PI={Active:"Active",Left:"Left",Replaced:"Replaced"},II=z.enum(["Active","Left","Replaced"]).catch("Active"),vI=z.object({CurrentProgress:j.nullish(),MaxProgress:j.nullish()}).passthrough(),TI=z.object({UserID:z.string().nullish(),PublicData:qe.nullish(),IsBot:z.boolean().nullish(),ContributionPoints:j.nullish(),MilestoneClaims:z.record(z.string(),bl).nullish(),GrandPrizeClaimed:z.boolean().nullish(),MemberStatus:II.nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),dm=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),RoundIndex:z.number().nullish(),Members:z.array(TI).nullish(),SharedProgress:vI.nullish(),Status:pm.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:z.number().nullish()}).passthrough(),AI=z.object({GroupID:z.string().nullish(),RoundIndex:z.number().nullish(),FinalStatus:pm.nullish(),GrandPrizeReceived:z.boolean().nullish(),FinishedAtUtc:p.nullish()}).passthrough(),kI=z.object({ActiveGroupID:z.string().nullish(),ActiveRoundIndex:z.number().nullish(),History:z.array(AI).nullish()}).passthrough(),hm=z.object({ServerTimeUtc:p.nullish(),UserState:kI.nullish(),ActiveGroup:dm.nullish(),SecondsRemaining:j.nullish()}),mm=z.object({ServerTimeUtc:p.nullish(),Group:dm.nullish(),SecondsRemaining:j.nullish()}),Ja=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),fm=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),Success: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 zI={Mesh:"Mesh",Host:"Host"},Za=z.enum(["Mesh","Host"]).catch("Mesh"),wI={ServerRelay:"ServerRelay",P2P:"P2P"},Ya=z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),MI={Public:"Public",Private:"Private"},OI=z.enum(["Public","Private"]).catch("Public"),EI={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},UI=z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),gm=z.object({Urls:z.string().nullish(),Username:z.string().nullish(),Credential:z.string().nullish()}).passthrough(),qI=z.object({Enabled:z.boolean().nullish()}).passthrough(),ym=z.object({SystemState:qI.nullish(),DefaultTopology:Za.nullish(),AllowCreatorTopologyOverride:z.boolean().nullish(),DefaultChatMode:Ya.nullish(),AllowCreatorChatOverride:z.boolean().nullish(),MaxPlayersPerRoom:z.number().nullish(),RoomTtlSeconds:z.number().nullish(),MaxRoomLifetimeSeconds:z.number().nullish(),HeartbeatIntervalMs:z.number().nullish(),MemberTimeoutMs:z.number().nullish(),MaxSignalPayloadBytes:z.number().nullish(),MaxChatTextLength:z.number().nullish(),RoomLogCap:z.number().nullish(),VoiceEnabled:z.boolean().nullish(),RecordVoices:z.boolean().nullish(),IceServers:z.array(gm).nullish()}).passthrough(),BI=z.object({UserID:z.string().nullish(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),Ready:z.boolean().nullish(),State:z.record(z.string(),z.string()).nullish(),JoinedAt:z.number().nullish(),IsHost:z.boolean().nullish(),LastSeenMs:z.number().nullish()}).passthrough(),LI=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),Topology:Za.nullish(),ChatMode:Ya.nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),MemberCount:z.number().nullish(),CreatedAt:z.number().nullish()}).passthrough(),GI=z.object({Seq:z.number().nullish(),Type:UI.nullish(),FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Kind:z.string().nullish(),Payload:z.string().nullish(),Ts:z.number().nullish()}).passthrough(),Gi=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),OwnerUserID:z.string().nullish(),Topology:Za.nullish(),ChatMode:Ya.nullish(),Visibility:OI.nullish(),Status:z.string().nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),Members:z.array(BI).nullish(),IceServers:z.array(gm).nullish(),Seq:z.number().nullish(),BannedUserIDs:z.array(z.string()).nullish()}).passthrough(),Rm=z.object({Removed:z.boolean().nullish(),Banned:z.boolean().nullish()}).passthrough(),Cm=z.object({WasBanned:z.boolean().nullish()}).passthrough(),Xa=z.object({Closed:z.boolean().nullish(),NewHostUserID:z.string().nullish()}).passthrough(),Sm=z.object({Rooms:z.array(LI).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}).passthrough(),xm=z.object({Envelopes:z.array(GI).nullish(),MaxSeq:z.number().nullish()}).passthrough(),Vr=z.object({Seq: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 el=z.object({TitleCustomData:Br.nullish(),Character:Zs.nullish(),Item:Xn.nullish(),Currency:zn.nullish(),Store:Rs.nullish(),Lootbox:Ba.nullish(),Quest:Hi.nullish(),TimedEvent:qs.nullish(),Leaderboard:js.nullish(),Season:Ks.nullish(),Reward:Ga.nullish(),Collection:Ir.nullish(),Craft:Va.nullish(),DealOffer:Wo.nullish(),Premium:Ea.nullish(),TimedBoost:Er.nullish(),CoopEvent:on.nullish(),GameLoop:Fr.nullish(),Match:ha.nullish(),Experiment:Ud.nullish(),Blockchain:oa.nullish(),Marketplace:Ra.nullish(),Multiplayer:ym.nullish(),UserCustomData:Dn.nullish(),Referral:ja.nullish(),Localization:Wd.nullish(),Analytics:Pd.nullish(),Social:up.nullish(),PlatformBridge:cp.nullish()}).passthrough();var ii={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Nr=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(ii.GetTitlePublicConfiguration,e,el)}getTitlePublicConfigurationExcept(e){return this.send(ii.GetTitlePublicConfigurationExcept,e,el)}getCurrencyDefinitions(e){return this.send(ii.GetCurrencyDefinitions,e,zn)}getItemDefinitions(e){return this.send(ii.GetItemDefinitions,e,Xn)}getServerTime(e){return this.send(ii.GetServerTime,e,Le)}};var _r=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Ge.GetGameLoops,e,Fr)}getBoardDefinition(e,t=false){return this.send(Ge.GetBoardDefinition,e,Gr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Ge.GetBoardDefinitionForLevel,e,Gr,{silent:t})}getUserBoardState(e){return this.send(Ge.GetUserBoardState,e,Yh)}boardLoopRoll(e){return this.send(Ge.BoardLoopRoll,e,rm)}boardLoopAttack(e){return this.send(Ge.BoardLoopAttack,e,om)}boardLoopRaid(e){return this.send(Ge.BoardLoopRaid,e,$a)}boardLoopRaidFast(e){return this.send(Ge.BoardLoopRaidFast,e,$a)}boardLoopBuild(e){return this.send(Ge.BoardLoopBuild,e,am)}boardSpecialChoose(e){return this.send(Ge.BoardSpecialChoose,e,De(lm))}boardSpecialApplyMultiplier(e){return this.send(Ge.BoardSpecialApplyMultiplier,e,um)}boardSpecialClaim(e){return this.send(Ge.BoardSpecialClaim,e,cm)}getCommunityChestState(e){return this.send(Ge.GetCommunityChestState,e,hm)}joinOrCreateCommunityChest(e){return this.send(Ge.JoinOrCreateCommunityChest,e,mm)}claimCommunityChestMilestone(e){return this.send(Ge.ClaimCommunityChestMilestone,e,Ja)}claimCommunityChestGrandPrize(e){return this.send(Ge.ClaimCommunityChestGrandPrize,e,Ja)}leaveCommunityChest(e){return this.send(Ge.LeaveCommunityChest,e,fm)}};var VI={Live:"Live",Latest:"Latest",Specific:"Specific"},NI={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},_I=z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),jI={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"},WI=z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),QI=z.object({Level:_I,Message:z.string().nullish(),Data:Lt.nullish()}),KI=z.object({Error:WI,Message:z.string().nullish(),StackTrace:z.string().nullish()}),bm=z.object({FunctionName:z.string().nullish(),Revision:z.number().nullish(),FunctionResult:Lt.nullish(),FunctionResultTooLarge:z.boolean().nullish(),Logs:z.array(QI).nullish(),LogsTooLarge:z.boolean().nullish(),ExecutionTimeSeconds:z.number().nullish(),APIRequestsIssued:z.number().nullish(),Error:KI.nullish()}),tl={Execute:"Execute"};var jr=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(tl.Execute,e,bm)}};var Wr=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Je.GetDefinitions,e,Mp)}getUserState(e){return this.send(Je.GetUserState,e,Op)}depositToken(e){return this.send(Je.DepositToken,e,Ep)}depositNFT(e){return this.send(Je.DepositNFT,e,Up)}requestTokenWithdrawal(e){return this.send(Je.RequestTokenWithdrawal,e,qp)}requestNFTWithdrawal(e){return this.send(Je.RequestNFTWithdrawal,e,Bp)}getTransactionHistory(e){return this.send(Je.GetTransactionHistory,e,Lp)}retryWithdrawal(e){return this.send(Je.RetryWithdrawal,e,Gp)}confirmWithdrawal(e){return this.send(Je.ConfirmWithdrawal,e,Fp)}donateToDeveloper(e){return this.send(Je.DonateToDeveloper,e,ca)}donateToUsersPool(e){return this.send(Je.DonateToUsersPool,e,ca)}getPlayAccess(e){return this.send(Je.GetPlayAccess,e,zp)}confirmPlayAccess(e){return this.send(Je.ConfirmPlayAccess,e,Vt)}};var Qr=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Me.GetDefinitions,e,ed)}getGroupedOffers(e){return this.send(Me.GetGroupedOffers,e,td)}getOffersByItem(e){return this.send(Me.GetOffersByItem,e,Ca)}getOffer(e){return this.send(Me.GetOffer,e,id)}getBuyOrders(e){return this.send(Me.GetBuyOrders,e,Ca)}getMyState(e){return this.send(Me.GetMyState,e,Bn)}getHistory(e){return this.send(Me.GetHistory,e,nd)}createListing(e){return this.send(Me.CreateListing,e,Ui)}cancelListing(e){return this.send(Me.CancelListing,e,ct)}buy(e){return this.send(Me.Buy,e,ct)}marketBuy(e){return this.send(Me.MarketBuy,e,ct)}marketSell(e){return this.send(Me.MarketSell,e,ct)}createAuction(e){return this.send(Me.CreateAuction,e,Ui)}placeBid(e){return this.send(Me.PlaceBid,e,sd)}claimAuction(e){return this.send(Me.ClaimAuction,e,ct)}createBuyOrder(e){return this.send(Me.CreateBuyOrder,e,Ui)}cancelBuyOrder(e){return this.send(Me.CancelBuyOrder,e,ct)}fillBuyOrder(e){return this.send(Me.FillBuyOrder,e,ct)}createDirectTrade(e){return this.send(Me.CreateDirectTrade,e,Ui)}respondDirectTrade(e){return this.send(Me.RespondDirectTrade,e,ct)}cancelDirectTrade(e){return this.send(Me.CancelDirectTrade,e,ct)}claimBack(e){return this.send(Me.ClaimBack,e,ct)}};var Kr=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(Ze.CreateRoom,e,Gi)}joinRoom(e){return this.send(Ze.JoinRoom,e,Gi)}leaveRoom(e,t=false){return this.send(Ze.LeaveRoom,e,Xa,{keepalive:t})}listRooms(e){return this.send(Ze.ListRooms,e,Sm)}getRoom(e){return this.send(Ze.GetRoom,e,Gi)}closeRoom(e){return this.send(Ze.CloseRoom,e,Xa)}poll(e){return this.send(Ze.Poll,e,xm)}sendSignal(e){return this.send(Ze.SendSignal,e,Vr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(Ze.ClaimHost,e,Gi)}kickMember(e){return this.send(Ze.KickMember,e,Rm)}unbanMember(e){return this.send(Ze.UnbanMember,e,Cm)}sendChat(e){return this.send(Ze.SendChat,e,Vr)}setMemberState(e){return this.send(Ze.SetMemberState,e,Vr)}};var HI={Free:"Free",Price:"Price",Holding:"Holding"},il=z.enum(["Free","Price","Holding"]).catch("Free"),$I={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},JI=z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),ZI={All:"All",Any:"Any"},YI=z.enum(["All","Any"]).catch("All"),XI={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},ev=z.enum(["Public","Unlisted","Friends"]).catch("Public"),tv={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},iv=z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),sv={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Pm=z.enum(["Purchase","Free","Holding"]).catch("Free"),nv={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},rv={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},ov=z.enum(["Creator","License","Free","Holding"]).catch("License"),av=z.object({Type:oi.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),Amount:z.number().nullish(),MinLevel:z.number().nullish()}).passthrough(),lv=z.object({Requirements:z.array(av).nullish(),Match:YI.nullish(),Mode:JI.nullish()}).passthrough(),uv=z.object({OptionID:z.string().nullish(),Mode:il.nullish(),Price:ue.nullish(),Holding:lv.nullish()}).passthrough(),cv=z.object({AllowedMimeTypes:z.array(z.string()).nullish(),MaxBytes:z.number().nullish(),MaxCount:z.number().nullish(),Required:z.boolean().nullish()}).passthrough(),pv=z.object({DisplayName:z.string().nullish(),Enabled:z.boolean().nullish(),Files:z.record(z.string(),cv).nullish(),ThumbnailRequired:z.boolean().nullish(),AllowedAccessModes:z.array(il).nullish(),PricePolicy:qn.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:le.nullish(),TagVocabulary:z.array(z.string()).nullish(),MaxPublishedPerPlayer:z.number().nullish(),DailyPublishCap:z.number().nullish()}).passthrough(),dv=z.object({Allowed:z.array(Ei).nullish(),MaxRequirements:z.number().nullish()}).passthrough(),hv=z.object({AutoHideReportThreshold:z.number().nullish(),RequireApproval:z.boolean().nullish(),BlockedTerms:z.array(z.string()).nullish()}).passthrough(),mv=z.object({MaxTitleLength:z.number().nullish(),MaxDescriptionLength:z.number().nullish(),MaxTags:z.number().nullish(),MaxTagLength:z.number().nullish(),MaxMetadataKeys:z.number().nullish(),MaxMetadataValueLength:z.number().nullish(),MaxAccessOptions:z.number().nullish(),ThumbnailMaxBytes:z.number().nullish()}).passthrough(),fv=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Schedule:ge.nullish(),Gate:Z.nullish(),Order:z.number().nullish()}).passthrough(),gv=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:ge.nullish(),ContentTypes:z.record(z.string(),pv).nullish(),PricePolicy:qn.nullish(),Commission:ya.nullish(),HoldingPolicy:dv.nullish(),Moderation:hv.nullish(),Limits:mv.nullish(),Featured:z.array(fv).nullish()}).passthrough(),yv=z.object({Acquisitions:z.number().nullish(),Downloads:z.number().nullish(),Likes:z.number().nullish(),Favorites:z.number().nullish(),ReportCount:z.number().nullish(),Remixes:z.number().nullish()}).passthrough(),si=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),CreatorUserID:z.string().nullish(),IsOfficial:z.boolean().nullish(),CreatorPublicData:qe.nullish(),Title:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),Metadata:z.record(z.string(),z.string()).nullish(),ThumbnailUrl:z.string().nullish(),Visibility:ev.nullish(),Access:z.array(uv).nullish(),Status:iv.nullish(),ModerationNote:z.string().nullish(),Stats:yv.nullish(),Revision:z.number().nullish(),ParentContentID:z.string().nullish(),FileCount:z.number().nullish(),TotalBytes:z.number().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),PublishedAt:p.nullish(),IsMine:z.boolean().nullish(),Owned:z.boolean().nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish()}).passthrough(),Rv=z.object({OptionID:z.string().nullish(),Mode:il.nullish(),Available:z.boolean().nullish()}).passthrough(),Im=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Order:z.number().nullish()}).passthrough(),vm=z.object({Definitions:gv.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish(),CanPublish:z.record(z.string(),z.boolean()).nullish(),Collections:z.array(Im).nullish()}).passthrough(),Hr=z.object({Items:z.array(si).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Tm=z.object({Content:si.nullish(),AccessState:z.array(Rv).nullish(),CanDownload:z.boolean().nullish()}).passthrough(),Am=z.object({Collection:Im.nullish(),Items:z.array(si).nullish()}).passthrough(),km=z.object({CreatorUserID:z.string().nullish(),PublicData:qe.nullish(),PublishedCount:z.number().nullish(),FollowerCount:z.number().nullish(),IsFollowing:z.boolean().nullish(),Items:z.array(si).nullish()}).passthrough(),Dm=z.object({Role:z.string().nullish(),Index:z.number().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish(),ServerCopy:z.boolean().nullish()}).passthrough(),zm=z.object({ContentID:z.string().nullish(),Revision:z.number().nullish(),Uploads:z.array(Dm).nullish(),ThumbnailUpload:Dm.nullish(),ExpiresAt:p.nullish()}).passthrough(),wm=z.object({CreditsConfirmation:me.nullish(),Content:si.nullish(),Resources:M.nullish()}).passthrough(),sl=z.object({Content:si.nullish()}).passthrough(),Mm=z.object({ContentID:z.string().nullish(),OptionID:z.string().nullish(),Source:Pm.nullish(),AlreadyOwned:z.boolean().nullish(),AccessActive:z.boolean().nullish(),Settlement:It.nullish(),Resources:M.nullish(),CommissionTaken:ue.nullish()}).passthrough(),Cv=z.object({Role:z.string().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish()}).passthrough(),Om=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),Revision:z.number().nullish(),AccessVia:ov.nullish(),Files:z.array(Cv).nullish(),ThumbnailUrl:z.string().nullish(),ExpiresAt:p.nullish()}).passthrough(),Sv=z.object({ContentID:z.string().nullish(),Source:Pm.nullish(),OptionID:z.string().nullish(),PricePaid:ue.nullish(),AcquiredAt:p.nullish(),Content:si.nullish()}).passthrough(),Em=z.object({Licenses:z.array(Sv).nullish(),ContinuationToken: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 $r=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(He.GetDefinitions,e,vm)}browse(e){return this.send(He.Browse,e,Hr)}getContent(e){return this.send(He.GetContent,e,Tm)}getCollection(e){return this.send(He.GetCollection,e,Am)}getCreatorProfile(e){return this.send(He.GetCreatorProfile,e,km)}beginUpload(e){return this.send(He.BeginUpload,e,zm)}publish(e){return this.send(He.Publish,e,De(wm))}updateContent(e){return this.send(He.UpdateContent,e,sl)}unpublish(e){return this.send(He.Unpublish,e,sl)}getMyContent(e){return this.send(He.GetMyContent,e,Hr)}acquire(e){return this.send(He.Acquire,e,Mm)}getDownload(e){return this.send(He.GetDownload,e,Om)}getMyLicenses(e){return this.send(He.GetMyLicenses,e,Em)}getMyFavorites(e){return this.send(He.GetMyFavorites,e,Hr)}};var Jr=class extends B{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,cd,"defs")}get(e){return this.sendKeyed("Get",e,xa,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,dd,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,ba,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,hd,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,Da,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,Da,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,md,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,gd,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,fd,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,yd,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,pd,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Rd,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,xa,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,ba,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Zr=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$1){this.settings=ll(e$1),this.emitter=new Di,this.platform=e$1.platform??new e,this.clientPlatform=e$1.clientPlatform??Sl(),this.acquisition=new Qt(this.platform),this.acquisition.capture(),this.playtime=new Pi(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$1.fetch??globalThis.fetch.bind(globalThis),this.transport=new ts({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e$1.fetch,debugLogging:this.settings.debugLogging,throttleMs:e$1.throttleMs,maxRequestsPerSecond:e$1.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new rs(this.emitter),this.cache=new as(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e$1.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 ls(this.platform.storage,this.settings.titleID),this.api={authentication:new Hn(this),user:new Jn(this),currency:new Zn(this),item:new er(this),store:new tr(this),purchase:new rr(this),lootbox:new lr(this),reward:new ur(this),quest:new fr(this),tutorial:new cr(this),communityMarketing:new pr(this),chat:new dr(this),push:new hr(this),localization:new mr(this),timedEvent:new gr(this),leaderboard:new yr(this),season:new Rr(this),premium:new Cr(this),character:new Sr(this),match:new xr(this),craft:new Dr(this),ai:new Pr(this),collection:new vr(this),coopEvent:new Tr(this),dealOffer:new Ar(this),referral:new kr(this),mailbox:new zr(this),advertising:new wr(this),social:new Mr(this),timedBoost:new Ur(this),userCustomData:new qr(this),titleCustomData:new Lr(this),title:new Nr(this),gameLoop:new _r(this),cloudCode:new jr(this),blockchain:new Wr(this),marketplace:new Qr(this),multiplayer:new Kr(this),workshop:new $r(this),dataCollections:new Jr(this),analytics:new Qn(this),experiment:new Kn(this)},this.userService=new hs(this),this.cache.attachState(this.userService),this.auth=new us(this),this.currency=new fs(this),this.item=new gs(this),this.store=new Ss(this),this.credits=new xs(this),this.purchase=new bs(this),this.checkout=new Ds(this),this.lootbox=new Ps(this),this.reward=new Is(this),this.quest=new Us(this),this.tutorial=new Ts(this),this.communityMarketing=new As(this),this.chat=new ws(this),this.push=new Ms(this),this.localization=new Es(this),this.timedEvent=new Ls(this),this.leaderboard=new Ws(this),this.season=new Hs(this),this.premium=new $s(this),this.character=new Ys(this),this.match=new Xs(this),this.craft=new en(this),this.ai=new sn(this),this.collection=new nn(this),this.coopEvent=new an(this),this.dealOffer=new cn(this),this.referral=new pn(this),this.mailbox=new mn(this),this.ads=new yn(this),this.social=new Sn(this),this.timedBoost=new xn(this),this.userCustomData=new Pn(this),this.titleCustomData=new In(this),this.title=new vn(this),this.gameLoop=new Tn(this),this.cloudCode=new An(this),this.blockchain=new Mn(this),this.marketplace=new Ln(this),this.multiplayer=new Gn(this),this.workshop=new Fn(this),this.dataCollections=new Nn(this),this.analytics=new jn(this),this.experiments=new Wn(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:d()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var Yr=class{ctx;constructor(e){this.ctx=new Zr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=_t(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(n,{...s,...i},z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get 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 bv(r){return new Yr(r)}var Um="idos_sso",qm="state",nl="idos:sso:state",Dv="https://idosgames.com/sso/",Pv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],Iv=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function vv(){if(typeof window>"u")return false;let{origin:r}=window.location;return Pv.includes(r)||Iv.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function Tv(){if(typeof window>"u")return null;let r=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!r)return null;let e=new URLSearchParams(r),t=e.get(Um);if(!t)return null;let i=e.get(qm)??"",s=Mv();return Ev(e),Ov(),s&&i!==s?null:{code:t,state:i}}function Av(r){if(typeof window>"u")return;let e=r.returnTo??kv(),t=zv();wv(t);let i=new URL(r.ssoUrl??Dv);i.searchParams.set("title",r.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function kv(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function zv(){let r=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(r);else for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*256);return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function wv(r){try{window.sessionStorage.setItem(nl,r);}catch{}}function Mv(){try{return window.sessionStorage.getItem(nl)}catch{return null}}function Ov(){try{window.sessionStorage.removeItem(nl);}catch{}}function Ev(r){r.delete(Um),r.delete(qm);let e=r.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var Uv={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 qv(r,e="Something went wrong. Please try again."){return r?Uv[r]??r:e}function Bv(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function Lv(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function Gv(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function Lm(r,e,t,i=1){if(!r)return e;let s=r.Base??e,n=Math.max(0,t-i),o;switch(r.Shape??"Flat"){case "PerStep":o=s+(r.PerStep??0)*n;break;case "PerStepRate":o=s*(1+(r.PerStepRate??0)*n);break;case "Geometric":o=s*Math.pow(1+(r.GrowthRate??0),n);break;case "Table":o=s*Bm(r,t,1);break;case "TableAbsolute":o=Bm(r,t,s);break;default:o=s;break}return Number.isNaN(o)?s:(r.MinResult!=null&&o<r.MinResult&&(o=r.MinResult),r.MaxResult!=null&&o>r.MaxResult&&(o=r.MaxResult),o)}function Fv(r,e,t=1){return Lm(r,1,e,t)}function Vv(r){if(!r)return false;switch(r.Shape??"Flat"){case "PerStep":return (r.PerStep??0)!==0;case "PerStepRate":return (r.PerStepRate??0)!==0;case "Geometric":return (r.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return Gm(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function Nv(r){if(Number.isNaN(r)||r<=0)return 0;if(!Number.isFinite(r))return Number.MAX_SAFE_INTEGER;let e=Math.round(r);return Math.abs(r-e)<=1e-9*Math.max(1,Math.abs(r))?e:Math.ceil(r)}function Gm(r){if(!r)return [];let e=[];for(let t of r)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function Bm(r,e,t){let i=Gm(r.Points);if(i.length===0)return t;let s=null,n=null,o=null;for(let c of i)(o===null||c.AtStep>o.AtStep)&&(o=c),c.AtStep<=e&&(s===null||c.AtStep>=s.AtStep)&&(s=c),c.AtStep>e&&(n===null||c.AtStep<n.AtStep)&&(n=c);if(s===null)return t;if(n===null){let c=r.TailGrowthRate??0;return c===0?o.Value:o.Value*Math.pow(1+c,e-o.AtStep)}switch(r.Interpolation??"Step"){case "Linear":{let c=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+c*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let h=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+h*(n.Value-s.Value)}let c=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,c)}default:return s.Value}}var _v={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},rl=z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),jv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Wv=z.enum(["Top","Bottom","Left","Right"]).catch("Top"),Qv=z.object({PlacementID:z.string().nullish(),Type:rl.nullish(),Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),CreditsRewarded:z.number().nullish(),AllowedProviderIDs:z.array(z.string()).nullish()}).passthrough(),Kv=z.object({DefaultCreditsPerView:z.number().nullish(),MaxCreditsBalance:z.number().nullish(),DailyCreditEarnCap:z.number().nullish(),DailyViewCap:z.number().nullish(),MinSecondsBetweenViews:z.number().nullish()}).passthrough(),Hv=z.object({CooldownSeconds:z.number().nullish(),MinSessionTimeBeforeFirstSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),$v=z.object({Enabled:z.boolean().nullish(),Position:Wv.nullish(),RefreshIntervalSeconds:z.number().nullish()}).passthrough(),Jv=z.object({Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish()}).passthrough(),Zv=z.object({MaxImpressionsPerHour:z.number().nullish(),MaxImpressionsPerDay:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),Yv=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),DisableInterstitials:z.boolean().nullish(),DisableBanners:z.boolean().nullish(),DisableAppOpen:z.boolean().nullish()}).passthrough(),Xv=z.object({RequirePersonalizedAdsConsent:z.boolean().nullish(),RequireTrackingConsent:z.boolean().nullish(),CurrentPolicyVersion:z.string().nullish(),RegulatedRegions:z.array(z.string()).nullish()}).passthrough(),eT=z.object({RequireServerSideVerification:z.boolean().nullish(),PendingRequestTtlSeconds:z.number().nullish(),MaxPendingRequestsPerUser:z.number().nullish()}).passthrough(),tT=z.object({AndroidUnitID:z.string().nullish(),IosUnitID:z.string().nullish(),WebUnitID:z.string().nullish(),Type:rl.nullish()}).passthrough(),iT={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},sT=z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),nT=z.object({ProviderID:z.string().nullish(),Kind:sT.nullish(),Enabled:z.boolean().nullish(),Priority:z.number().nullish(),AndroidAppID:z.string().nullish(),IosAppID:z.string().nullish(),WebAppID:z.string().nullish(),Units:z.record(z.string(),tT).nullish()}).passthrough();z.object({Enabled:z.boolean().nullish(),Placements:z.record(z.string(),Qv).nullish(),Providers:z.record(z.string(),nT).nullish(),RewardedVideo:Kv.nullish(),Interstitial:Hv.nullish(),Banner:$v.nullish(),AppOpen:Jv.nullish(),FrequencyCapping:Zv.nullish(),PremiumAdReductions:z.array(Yv).nullish(),Consent:Xv.nullish(),Verification:eT.nullish()}).passthrough();var rT=z.object({RewardedVideoCredit:z.number().nullish(),TotalEarned:z.number().nullish(),TotalSpent:z.number().nullish()}).passthrough(),oT=z.object({PlacementID:z.string().nullish(),LastShownAt:p.nullish(),LastCompletedAt:p.nullish(),TotalImpressions:z.number().nullish(),TotalCompletions:z.number().nullish(),ConsecutiveFailures:z.number().nullish()}).passthrough(),aT=z.object({Date:p.nullish(),ImpressionsByPlacement:z.record(z.string(),z.number()).nullish(),CompletionsByPlacement:z.record(z.string(),z.number()).nullish(),TotalImpressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish(),AppOpenImpressions:z.number().nullish(),CreditsEarnedToday:z.number().nullish()}).passthrough(),lT=z.object({SessionID:z.string().nullish(),SessionStartAt:p.nullish(),Impressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish()}).passthrough(),uT=z.object({PersonalizedAdsConsent:z.boolean().nullish(),TrackingConsent:z.boolean().nullish(),PolicyVersion:z.string().nullish(),Region:z.string().nullish(),ConsentGivenAt:p.nullish(),ConsentRevokedAt:p.nullish()}).passthrough(),cT=z.object({RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),Type:rl.nullish(),IssuedAt:p.nullish(),ExpiresAt:p.nullish(),CreditsToAward:z.number().nullish()}).passthrough(),pT=z.object({InvalidSsvCount:z.number().nullish(),OrphanCompletions:z.number().nullish(),FastCompletions:z.number().nullish(),LastFlaggedAt:p.nullish()}).passthrough();z.object({Credits:rT.nullish(),Placements:z.record(z.string(),oT).nullish(),Daily:aT.nullish(),Session:lT.nullish(),LastImpressionAt:p.nullish(),LastInterstitialAt:p.nullish(),LastRewardedAt:p.nullish(),LastAppOpenAt:p.nullish(),TotalImpressions:z.number().nullish(),TotalRewardedCompletions:z.number().nullish(),AdsDisabledUntil:p.nullish(),Consent:uT.nullish(),PendingRequests:z.record(z.string(),cT).nullish(),FraudFlags:pT.nullish(),UpdatedAt:p.nullish()}).passthrough();
2
+ export{Ne as AIAction,DR as AIErrorCode,$t as AIGenerationStatus,Gt as AIModality,Qt as AcquisitionCapture,iT as AdProviderKind,_v as AdType,fn as AdvertisingAction,Ta as AnalyticsAction,fb as AnalyticsDropReason,va as AnalyticsEventNaming,bt as AnalyticsLimits,_P as AttackOutcome,ze as AuthType,Be as AuthenticationAction,Nt as AutomaticEvent,jv as BannerPosition,Je as BlockchainAction,PS as BlockchainNetworkType,Ip as BlockchainOperationCategory,OS as BlockchainTransactionStatus,AS as BlockchainTransactionType,ax as BodyPart,OP as BoostWindowKind,We as CharacterAction,$e as ChatAction,hy as ChatAuthorType,py as ChatBlockedTermAction,oy as ChatChannelType,uy as ChatDirectAudience,ay as ChatPartitioning,fy as ChatReportReason,yt as ClientPlatform,tl as CloudCodeAction,jI as CloudCodeErrorCode,NI as CloudCodeLogLevel,VI as CloudCodeRevisionSelection,Qe as CollectionAction,Tx as CommissionSink,PI as CommunityChestMemberStatus,DI as CommunityChestStatus,VD as CommunityCreatorStatus,Xt as CommunityMarketingAction,_D as CommunityMetricKind,GD as CommunityParticipationMode,ND as CommunityPayoutCurrencyKind,hS as ConversionRateMode,ft as CoopEventAction,UR as CoopGroupStatus,qR as CoopMemberStatus,br as CraftAction,iP as CraftInputSelectionMode,eP as CraftOutputLevelMode,nP as CraftOutputLevelOverflow,XD as CraftType,Ti as CreditsConfirmationStatus,Lg as CreditsError,kn as CurrencyAction,dS as CurrencyStatus,dt as CurrencyType,vf as CurveInterpolation,Pf as CurveShape,zt as CustomDataBucket,sS as CustomDataValueType,XC as CustomDataWriter,al as DEFAULT_BASE_URL,Kx as DataAccessMode,_x as DataCollectionKind,tb as DataCollectionSchemaMode,cb as DataCollectionsAction,Zx as DataCounterKind,Wx as DataFieldType,Qx as DataFieldVisibility,Xx as DataOwnerDeletedPolicy,$x as DataRefKind,eC as DealComparisonOperator,QR as DealNodeRuntimeStatus,XR as DealNodeType,St as DealOfferAction,WR as DealOfferActivationStatus,_n as EVENT_NAME_PATTERN,EI as EnvelopeType,hf as EventTokenType,za as ExperimentAction,vb as ExperimentGoalKind,$C as FRIENDS_FROM_PLATFORM,Gb as FodderSelectionMode,Bb as FodderValuationMode,qC as FriendActionStatus,BC as FriendSource,Ge as GameLoopAction,Yr as IDosGamesClient,Yb as IapProductType,dD as IapPurchaseStatus,df as IapStoreValues,Yn as ItemAction,kS as KycStatus,wS as KycTier,je as LeaderboardAction,$n as LocalizationAction,Mb as LocalizationMissingKeyMode,ar as LootboxAction,DC as MAILBOX_COUNTER_CAP,st as MailboxAction,yC as MailboxCategory,bC as MailboxErrors,RC as MailboxLetterSource,SC as MailboxRewardModule,Un as MarketGoodsType,vx as MarketOfferStatus,Ix as MarketOfferType,Me as MarketplaceAction,xt as MatchAction,lx as MatchStatus,Ze as MultiplayerAction,wI as MultiplayerChatMode,zI as MultiplayerTopology,ny as OFFER_NOT_IN_ROTATION,Zo as PLATFORM_AD_MESSAGES,Jo as PLATFORM_AD_PROVIDER,ZC as PlatformFriendsMode,JC as PlatformProfileMode,NS as PlayAccessMode,kb as PlayerExperimentStatus,Pi as PlaytimeTracker,Zt as PremiumAction,Yt as PurchaseAction,mi as PushAction,At as PushPermissionState,ky as PushTopic,Ty as PushTransport,mt as QuestAction,Bf as QuestObjectiveSource,Gf as QuestPrerequisiteMode,Ef as QuestStatus,VP as RaidMode,jt as ReferralAction,Ni as ResourceEntryType,Mt as RewardAction,MI as RoomVisibility,bR as SKIN_ALREADY_OWNED,Go as SKIN_SLOT,mf as ScheduleMode,Bt as SeasonAction,Se as SocialAction,NC as SocialContentStatus,GC as SocialEntityType,_C as SocialInboxVerb,FC as SocialReactionKind,VC as SocialReportReason,NP as SpecialChoiceMode,Tt as StoreAction,Vg as StoreRotationMode,Jb as StoreType,ti as TimedBoostAction,DP as TimedBoostStackingPolicy,ut as TimedEventAction,ii as TitleAction,Li as TitleCustomDataAction,qP as TitleDataBucket,UP as TitleDataScope,cP as TradeOfferStatus,ES as TransactionDirection,at as TutorialAction,eg as TutorialBoardAction,Zf as TutorialFlowStatus,Rf as TutorialGateMode,$f as TutorialRestartPolicy,Xf as TutorialScriptModule,Kf as TutorialStepCompletionMode,Di as TypedEmitter,pt as UserAction,gt as UserCustomDataAction,GS as WalletGateBalanceSource,vS as WalletLinkType,HI as WorkshopAccessMode,rv as WorkshopAccessVia,He as WorkshopAction,tv as WorkshopContentStatus,ZI as WorkshopHoldingMatch,$I as WorkshopHoldingMode,sv as WorkshopLicenseSource,nv as WorkshopSort,XI as WorkshopVisibility,qv as authErrorText,Av as beginSsoRedirect,gn as canUsePlatformAds,Lv as claimedMilestoneIDs,bv as createIDosGamesClient,ui as cryptoShortfallFromError,Fv as curveMultiplier,Dg as defineView,vd as describeUserAgent,Lm as evaluateCurve,Gv as grantedPremiumTiers,ki as isAIGenerationTerminal,Vv as isCurveConfigured,Bv as isMilestoneClaimed,pR as isReservedSlot,vv as isSsoAvailable,wn as normalizeBlockchainCategory,PR as parseAIErrorCode,Tv as readSsoCodeFromUrl,Yo as requestPlatformAd,Nv as roundAmount,db as where,Bg as zPaymentProof,iu as zPriceOption,le as zPriceOptions};