@idosgames/core 0.26.9 → 0.26.11

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 {i,o,k,m,q,g,N,a,j,r,f,h,z as z$1}from'./chunk-TFBN7PEL.js';export{r as AuthType,c as BrowserFileStore,d as BrowserStorage,j as ClientPlatform,f as CurrencyType,n as EventTokenType,l as IapStoreValues,b as MemoryFileStore,s as MemoryHost,e as MemoryStorage,v as NATIVE_HOST_GLOBAL,u as NATIVE_HOST_PROTOCOL,x as NativeHost,G as PLATFORM_AD_MESSAGES,B as PLATFORM_BRIDGE_ACK,I as PLATFORM_CREDITS_CONFIRM_FINAL,H as PLATFORM_CREDITS_CONFIRM_MESSAGES,z as PLATFORM_ORIGINS,C as PLATFORM_PAGE_UNAVAILABLE,E as PLATFORM_SIGN_IN_MESSAGES,F as PLATFORM_TOPUP_MESSAGES,J as PLATFORM_TRADE_MESSAGES,h as ResourceEntryType,L as SITE_FRAME_HIDDEN_MESSAGE,p as ScheduleMode,M as WebHost,D as askPlatformPage,N as createDefaultHost,y as getTelegramWebApp,A as isPlatformParentOrigin,K as platformTradeUrl,w as readNativeHostGlobal,t as shareFallbackText}from'./chunk-TFBN7PEL.js';import {b,a as a$1,c}from'./chunk-CS7ACWDY.js';export{e as isFail,d as isOk}from'./chunk-CS7ACWDY.js';import {z}from'zod';import rn from'decimal.js';var Ln=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.off(e,t);}}once(e,t){let n=this.on(e,i=>{n(),t(i);});return n}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e));}emit(e,t){let n=this.listeners.get(e);if(n)for(let i of [...n])i(t);}removeAllListeners(){this.listeners.clear();}};function Ml(o){return {get:e=>o.getString(e),set:(e,t)=>o.setString(e,t),remove:e=>o.remove(e)}}var Ol="https://api.idosgames.com";function El(o,e){return {titleID:o.titleID,titleTemplateID:o.titleTemplateID??"default",buildKey:o.buildKey??"",baseUrl:(o.baseUrl??Ol).replace(/\/+$/,""),devBuild:o.devBuild??false,debugLogging:o.debugLogging??false,configStorage:o.configStorage??Ml(e.storage),locale:o.locale??e.getLanguage(),appVersion:o.appVersion??""}}var zo="idos_acq",ql=["gclid","fbclid","ttclid","msclkid","yclid"],og=["ref","r"],ag=["ref_","ref-","ref=","r_","r-"];var sn=class{constructor(e){this.host=e;}host;capture(){let e=this.readFromEnvironment();lg(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),n=t?{...t.signal}:{},i=pg(this.host.getDeviceModel());return i&&(n.OsVersion=i),e&&(n.AppVersion=e),Object.keys(n).length>0?n:void 0}clear(){this.host.storage.remove(zo);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let n=Bl(Ll(t));if(n)return n}return li(t)}readFromEnvironment(){let e={},t=Ll(this.host.getFullURL());nn(e,"UtmSource",t.get("utm_source")),nn(e,"UtmMedium",t.get("utm_medium")),nn(e,"UtmCampaign",t.get("utm_campaign")),nn(e,"UtmTerm",t.get("utm_term")),nn(e,"UtmContent",t.get("utm_content")),nn(e,"ClaimToken",t.get("idos_click"));for(let R of ql){let W=t.get(R);if(W){e.ClickID=W;break}}let n=this.host.getStartParameter()??"",i=cg(n);if(i){for(let R of ug)nn(e,R,i.get(Gl[R])??null);for(let R of ql){let W=i.get(R);if(W){e.ClickID=W;break}}}let s=li(i?i.get("ref")??i.get("r")??"":n),r=Bl(t),p=s||r;p&&(e.ReferralCode=p,e.ChannelHint=s?"telegram":"query");let m=this.host.getReferrer();return m&&(e.Referrer=m),e}read(){try{let e=this.host.storage.getString(zo);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.host.storage.setString(zo,JSON.stringify(e));}catch{}}};function lg(o){return !!(o.UtmSource||o.UtmMedium||o.UtmCampaign||o.ClickID||o.Referrer||o.ReferralCode||o.ClaimToken)}function nn(o,e,t){t&&(o[e]=t);}var Ul="a1_",Gl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},ug=Object.keys(Gl);function cg(o){let e=(o||"").trim();if(!e.startsWith(Ul))return null;let t=e.slice(Ul.length);if(!t)return null;try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),i=atob(n+"=".repeat((4-n.length%4)%4)),s=Uint8Array.from(i,m=>m.charCodeAt(0)),r=new TextDecoder().decode(s),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 Bl(o){for(let e of og){let t=o.get(e);if(t)return li(t)}return null}function li(o){let e=(o||"").trim();if(!e)return null;for(let t of ag)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function pg(o){let e=o||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let n=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(n)return n[1]}var Nl="idos_usage_pending",_l="idos_usage_session",Vl="idos_usage_closed_session",jl="idos_usage_new_session",Fl="idos_usage_last_activity",Bn=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;stopVisibility=null;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=!this.ctx.host.isVisible(),this.timer=setInterval(()=>this.tick(),200*1e3),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=e=>{if(!e){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,n=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,n,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=n,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=n,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(Nl),this.currentSessionSeconds=this.readNumber(_l),this.pendingClosedSessionSeconds=this.readNumber(Vl),this.isNewSessionPending=this.readNumber(jl)!==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(Nl,this.pendingSeconds),this.writeNumber(_l,this.currentSessionSeconds),this.writeNumber(Vl,this.pendingClosedSessionSeconds),this.writeNumber(jl,this.isNewSessionPending?1:0),this.writeNumber(Fl,Date.now());}readNumber(e){let t=this.ctx.host.storage.getString(e),n=t?Number(t):0;return Number.isFinite(n)&&n>0?n:0}writeNumber(e,t){try{this.ctx.host.storage.setString(e,String(Math.floor(t)));}catch{}}};var H=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)}),ne=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}),u=z.string();var vt=z.object({Type:i.nullish(),CurrencyID:z.string().nullish(),Amount:H.nullish(),AmountUsd:z.number().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ProductID:z.string().nullish()}),hg=z.object({Type:o.nullish(),EntityID:z.string()}),dg=z.object({Address:hg.nullish(),Amount:H.nullish(),Source:z.string().nullish()}),ce=z.object({Entries:z.array(vt).nullish(),EventTokens:z.array(dg).nullish()}),Wl=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Resources:ce.nullish()}),$=z.object({Standard:ce.nullish(),PremiumBonuses:z.array(z.unknown()).nullish(),PremiumTiers:z.array(Wl).nullish()}),qt=z.object({Standard:ce.nullish(),PremiumDiscounts:z.array(z.unknown()).nullish(),PremiumTiers:z.array(Wl).nullish()}),O=z.object({Grant:$.nullish(),Consume:qt.nullish()}),Ut=z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),FromResult:O.nullish(),ToResult:O.nullish()});z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Transferred:ce.nullish()});var mg=z.object({ExperimentID:z.string().nullish(),Variants:z.array(z.string()).nullish()}).passthrough(),fg={Completed:"Completed",Started:"Started",StepReached:"StepReached"},gg=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(),ee=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:mg.nullish(),Tutorial:gg.nullish(),Platforms:z.array(k).nullish()}).passthrough();var Ie=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 yg=z.object({OffsetSecondsFromParentStart:z.number().nullish(),DurationSeconds:z.number().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Rg=z.object({StartUtc:z.string().nullish(),EndUtc:z.string().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Cg=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 Sg=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 ht=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:Ie.nullish()}).passthrough(),Re=z.object({Mode:z.string().nullish(),IsActive:z.boolean().nullish(),Scheduled:Rg.nullish(),Chain:Cg.nullish(),Cyclic:Sg.nullish(),ActivationTriggers:z.array(ht).nullish(),Relative:yg.nullish()}).passthrough();var xg={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},bg=z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Dg={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Ig=z.enum(["Step","Linear","Geometric"]).catch("Step"),Pg=z.object({AtStep:z.number().nullish(),Value:z.number().nullish()}).passthrough(),$e=z.object({Base:z.number().nullish(),Shape:bg.nullish(),PerStep:z.number().nullish(),PerStepRate:z.number().nullish(),GrowthRate:z.number().nullish(),Points:z.array(Pg).nullish(),Interpolation:Ig.nullish(),TailGrowthRate:z.number().nullish(),MinResult:z.number().nullish(),MaxResult:z.number().nullish()}).passthrough();var vg=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Rewards:$.nullish()}).passthrough(),Ag=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Multiplier:z.number().nullish()}).passthrough(),wo=z.object({Bundles:z.array(vg).nullish(),Multipliers:z.array(Ag).nullish()}).passthrough();var Tg=z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),ui=z.object({Source:Tg.nullish(),SourceKey:z.string().nullish(),Curve:$e.nullish(),Anchor:z.number().nullish(),IncludeRewards:ce.nullish(),ExcludeRewards:ce.nullish()}).passthrough(),Kl=z.object({ClaimedAt:z.string().nullish(),PremiumTiers:z.array(z.string()).nullish(),Unlocked:z.boolean().nullish()}).passthrough(),Ve=z.object({MilestoneID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredProgress:z.number().nullish(),Rewards:$.nullish(),BonusRewards:$.nullish(),SeasonTierRewards:wo.nullish(),SortOrder:z.number().nullish(),IsFeatured:z.boolean().nullish()}).passthrough(),Rn=z.object({Milestones:z.record(z.string(),Ve).nullish()}).passthrough();var J=z.object({PresetID:z.string().nullish(),Remove:z.array(z.string()).nullish()}).passthrough();var zg=z.object({TargetCurrencyID:z.string().nullish(),Rate:z.number().nullish(),MaxConvertAmount:z.number().nullish()}).passthrough(),At=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:zg.nullish()}).passthrough();var wg=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),Cn=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:u,ExpiresAt:u.nullish(),EquippedSlot:wg.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Q=z.object({ChangedInstances:z.record(z.string(),Cn).nullish(),RemovedInstanceIDs:z.array(z.string()).nullish()});var ke=o=>z.object({Id:z.string(),Success:z.boolean(),Error:z.string().nullish(),Data:o.nullish()}),Tt=o=>z.object({ServerTimeUtc:u,Items:z.array(ke(o)),Resources:O.nullish(),Inventory:Q.nullish()});var kg={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Ql=z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Mg=z.object({}).passthrough().transform(o=>o),Og=z.object({CycleID:z.string(),InstanceKey:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),CycleStartUtc:u.nullish(),CycleEndUtc:u.nullish(),PointsTotalEarned:H.nullish(),PointsCurrent:H.nullish(),ClaimedPointMilestoneIDs:z.array(z.string()).nullish(),NextMilestone:Ve.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),ko=z.object({QuestID:z.string(),CycleID:z.string().nullish(),ObjectiveID:z.string().nullish(),NewValue:H.nullish(),ObjectiveCompleted:z.boolean().nullish(),Status:Ql}),Hl=z.object({State:Mg.nullish(),PointsTracks:z.record(z.string(),Og).nullish()}),Mo=z.object({ServerTimeUtc:u,QuestID:z.string(),CycleID:z.string().nullish(),NewStatus:Ql.nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),Oo=z.object({ServerTimeUtc:u,CycleID:z.string(),MilestoneID:z.string(),PointsTotalEarned:H.nullish(),Resources:O.nullish(),Inventory:Q.nullish(),NextMilestone:Ve.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),$l=z.object({ServerTimeUtc:u,CycleID:z.string(),GroupCompletionID:z.string(),GroupID:z.string().nullish(),CompletedGroupQuests:z.number().nullish(),RequiredGroupQuests:z.number().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),Jl=z.object({MetricID:z.string(),Updates:z.array(ko).nullish()}),Zl=z.array(ke(Mo)),Yl=z.array(ke(Oo)),Eg={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},qg=z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Ug={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Lg=z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),Xl=z.object({ObjectiveID:z.string().nullish(),Source:qg.nullish(),MaxProgressPerCall:z.number().nullish(),MetricID:z.string().nullish(),Triggers:z.array(ht).nullish(),TargetValue:z.number().nullish(),AggregationMethod:z.string().nullish()}).passthrough(),Eo=z.object({Milestones:J.nullish(),Linking:J.nullish(),Availability:J.nullish(),Reward:J.nullish(),Objectives:J.nullish()}).passthrough(),Bg=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(),eu=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:Lg.nullish()}).passthrough(),tu=z.object({Schedule:Re.nullish(),AccrueProgressWhenLocked:z.boolean().nullish(),Gate:ee.nullish(),Limits:Ie.nullish()}).passthrough(),nu=z.object({Grant:$.nullish(),PointsReward:z.number().nullish()}).passthrough(),Gg=z.object({QuestID:z.string().nullish(),Identity:Bg.nullish(),Linking:eu.nullish(),Availability:tu.nullish(),Objectives:z.record(z.string(),Xl).nullish(),Reward:nu.nullish(),Presets:Eo.nullish()}).passthrough(),Ng=z.object({CompletionID:z.string().nullish(),GroupID:z.string().nullish(),RequiredCompletedQuests:z.number().nullish(),Gate:ee.nullish(),Reward:$.nullish(),PointsReward:z.number().nullish()}).passthrough(),_g=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:ee.nullish(),Milestones:z.record(z.string(),Ve).nullish(),Presets:Eo.nullish(),PointsToken:At.nullish()}).passthrough(),Vg=z.object({Milestones:z.record(z.string(),Rn).nullish(),Linking:z.record(z.string(),eu).nullish(),Availability:z.record(z.string(),tu).nullish(),Reward:z.record(z.string(),nu).nullish(),Objectives:z.record(z.string(),z.record(z.string(),Xl)).nullish()}).passthrough(),jg=z.object({CycleID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:Re.nullish(),Milestones:z.record(z.string(),Ve).nullish(),Gate:ee.nullish(),PointsToken:At.nullish(),GroupCompletions:z.record(z.string(),Ng).nullish(),Phases:z.record(z.string(),_g).nullish(),Presets:Eo.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),pi=z.object({Cycles:z.record(z.string(),jg).nullish(),Quests:z.record(z.string(),Gg).nullish(),Presets:Vg.nullish()}).passthrough(),bt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var Fg={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},Wg=z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),Kg={Never:"Never",OnRequest:"OnRequest",Always:"Always"},Qg=z.enum(["Never","OnRequest","Always"]).catch("Never"),Hg={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},$g=z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),Jg={GameLoop:"GameLoop"},Zg={Raid:"Raid",Attack:"Attack"},Yg=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(),Xg=z.object({Mode:Wg.nullish(),Triggers:z.array(ht).nullish(),TargetValue:z.number().nullish(),RequireAllTriggers:z.boolean().nullish()}).passthrough(),ey=z.object({Grant:$.nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),ty=z.object({TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),RandomActionType:z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),ny=z.object({Module:z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:ty.nullish(),MaxUses:z.number().nullish()}).passthrough(),iy=z.object({Skippable:z.boolean().nullish(),TimeoutSeconds:z.number().nullish()}).passthrough(),qo=z.object({StepID:z.string().nullish(),Order:z.number().nullish(),Identity:Yg.nullish(),Completion:Xg.nullish(),Effects:ey.nullish(),Script:ny.nullish(),Policy:iy.nullish()}).passthrough(),sy=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(),iu=z.object({Schedule:Re.nullish(),Gate:ee.nullish(),RequiredFlowIDs:z.array(z.string()).nullish(),AutoStart:z.boolean().nullish(),StartTrigger:ht.nullish()}).passthrough(),su=z.object({Skippable:z.boolean().nullish(),SkippableFromOrder:z.number().nullish(),RestartPolicy:Qg.nullish(),ExpireAfterSeconds:z.number().nullish(),IsBlocking:z.boolean().nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),ru=z.object({Grant:$.nullish(),AutoClaim:z.boolean().nullish()}).passthrough(),ry=z.object({Availability:J.nullish(),Policy:J.nullish(),Reward:J.nullish(),Steps:J.nullish()}).passthrough(),oy=z.object({FlowID:z.string().nullish(),Identity:sy.nullish(),Availability:iu.nullish(),Policy:su.nullish(),Steps:z.record(z.string(),qo).nullish(),Reward:ru.nullish(),Presets:ry.nullish()}).passthrough(),ay=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(),ly=z.object({IsEnabled:z.boolean().nullish(),MaxActiveFlows:z.number().nullish(),Blocking:ay.nullish()}).passthrough(),uy=z.object({Availability:z.record(z.string(),iu).nullish(),Policy:z.record(z.string(),su).nullish(),Reward:z.record(z.string(),ru).nullish(),Steps:z.record(z.string(),z.record(z.string(),qo)).nullish()}).passthrough(),ou=z.object({Flows:z.record(z.string(),oy).nullish(),Settings:ly.nullish(),Presets:uy.nullish()}).passthrough(),cy=z.object({}).passthrough().transform(o=>o),au=z.object({FlowID:z.string(),Status:$g,CurrentStepID:z.string().nullish(),CurrentStep:qo.nullish(),TotalSteps:z.number(),CompletedSteps:z.number(),CanSkip:z.boolean(),RewardClaimed:z.boolean(),RewardPending:z.boolean(),VariantID:z.string().nullish()}).passthrough(),hi=z.object({State:cy.nullish(),Flows:z.array(au).nullish(),UnlockedFeatures:z.array(z.string()).nullish()}).passthrough(),Ft=z.object({Flow:au.nullish()}).passthrough(),lu=z.object({FlowID:z.string().nullish(),Granted:O.nullish()}).passthrough(),uu=z.array(ke(Ft)),cu=z.object({FlowID:z.string(),StepID:z.string(),Progress:z.number(),Target:z.number(),Completed:z.boolean()}).passthrough(),dt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function di(o){return Array.isArray(o)?o.filter(e=>e!==null).map(di):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).filter(([,e])=>e!==null).map(([e,t])=>[e,di(t)])):o}var mi=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),n=this.last.get(e);return n!==void 0&&t-n<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var fi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function pu(o){return o===429||o>=500&&o<=599}function gi(o,e=Math.random){let t=Math.min(500*Math.pow(2,o-1),4e3),n=t*.2*(e()*2-1);return Math.max(50,t+n)}function Wt(o){return new Promise(e=>setTimeout(e,o))}var hu=15e3;async function du(o){try{let t=JSON.parse(await o.text()),n=Number(t?.RetryAfterMs);if(Number.isFinite(n)&&n>0)return n}catch{}let e=Number(o.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function mu(o,e=Math.random){return o+10+Math.min(250,o*.2)*e()}function fu(o,e=Math.random){let t=o<=1?1500:o===2?4e3:6e3;return t+t*.1*e()}var Uo=15,gu=1e3,yi=class{constructor(e=Uo,t=()=>Date.now(),n=Wt){this.perSecond=e;this.now=t;this.wait=n;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=gu;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(gu-(e-this.starts[0])+5);}}};var py=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function xn(o){if(!o)return null;let e=py.exec(o);if(!e)return null;let[,t,n,i]=e;if(!t||n===void 0||i===void 0)return null;let s=new rn(n),r=new rn(i),p=r.minus(rn.max(s,0));return p.lte(0)?null:{currencyID:t,required:r.toNumber(),available:s.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var hy=12e3,dy=new Set(["RelatedEntityID"]);function my(o,e){if(e===null||typeof e!="object"||Array.isArray(e))return o;let t={};for(let[n,i]of Object.entries(e))dy.has(n)||(t[n]=i);try{return `${o}|${JSON.stringify(t)}`}catch{return o}}var fy=z.object({Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().optional(),QuestProgress:z.array(ko).nullish(),TutorialProgress:z.array(cu).nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish()}).passthrough(),Ri=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new fi;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new mi(e.throttleMs),this.pacer=new yi(e.maxRequestsPerSecond??Uo),this.clientPlatform=e.clientPlatform??j.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,n,i={}){let s=i.throttleKey??my(e,t);if(!this.throttler.tryAcquire(s))return b("throttled","Throttled");if(!this.inflight.add(s))return b("throttled","Duplicate request skipped");this.raiseBusy();try{let r=`${this.baseUrl}/${e}`,p=JSON.stringify(t),m=i.ticket??null,R=i.silent??!1,W=i.timeoutMs??hy,me=i.autoRetry??!0,Me=!1,De=!1,_e=0;for(;;){let Et;i.keepalive||await this.pacer.take();try{Et=await this.doFetch(r,p,m,W,i.keepalive??!1);}catch{if(me&&_e<3){_e++,await Wt(gi(_e));continue}return this.connectionFailure("Internet Connection Error",R)}let rt=Et.status;if(rt>=200&&rt<300){let ue=!De&&this.cryptoTopUpHandler!==null,we=await this.parseSuccess(Et,n,R,e,ue);if(!we.ok&&ue){let fe=xn(we.error);if(fe){if(De=!0,await this.runTopUp(fe))continue;R||this.emitter.emit("error:global",we.error);}}return we}if(rt===401){if(!Me&&this.sessionRefreshHandler){Me=!0;let ue=null;try{ue=await this.sessionRefreshHandler();}catch{ue=null;}if(ue){m=ue;continue}}return this.emitter.emit("auth:unauthorized",void 0),b("unauthorized","Unauthorized")}if(pu(rt)){let ue=rt===429?await du(Et):null;if(ue!==null&&ue>hu)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ue/1e3)} s`,R);if(me&&_e<3){_e++,await Wt(ue!==null?mu(ue):rt===429?fu(_e):gi(_e));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${rt})`,R)}let En="";try{En=await Et.text();}catch{}if(rt===409&&/operation in progress/i.test(En)&&me&&_e<3){_e++,await Wt(gi(_e));continue}return this.handleWebError(En,rt,R)}}finally{this.inflight.remove(s),this.lowerBusy();}}async doFetch(e,t,n,i,s=false){let r=new AbortController,p=setTimeout(()=>{r.abort();},i);try{let m={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return n&&(m.Authorization=`Bearer ${n}`),await this.fetchImpl(e,{method:"POST",body:t,headers:m,signal:r.signal,...s?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,n,i,s=false){let r;try{r=await e.text();}catch{return this.globalError("Failed to read response body",n)}let p;try{p=JSON.parse(r);}catch{return this.globalError("JSON Parse Error",n)}let m=fy.safeParse(p);if(!m.success)return this.globalError("Malformed response envelope",n);if(!m.data.Success){let De=m.data.Error??"Server returned Success=false",_e=s&&xn(De);return !n&&!_e&&this.emitter.emit("error:global",De),b("server",De)}let R=m.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:m.data.StateEpoch??null,versions:R});let W=m.data.QuestProgress;W&&W.length>0&&this.emitter.emit("quest:systemProgress",W);let me=m.data.TutorialProgress;me&&me.length>0&&this.emitter.emit("tutorial:systemProgress",me);let Me=t.safeParse(m.data.Data);if(!Me.success){let De=t.safeParse(di(m.data.Data));De.success&&(Me=De);}if(!Me.success){let De=`Validation error (${i}): ${Me.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",De),n||this.emitter.emit("error:global",De),b("validation",De)}return a$1(Me.data)}handleWebError(e,t,n){let i=`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");i=typeof r=="string"&&r.length>0?`HTTP ${t}: ${r}`:`HTTP ${t}: ${e}`;}catch{i=`HTTP ${t}: ${e}`;}return n||this.emitter.emit("error:global",i),b("server",i)}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 bn(o){return (typeof o=="string"?o:o.toISOString()).slice(0,10)}function Gn(o){return `${bn(o)}T00:00:00.000Z`}function yu(o){let e=new Date(o);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Ru(o,e){return new Date(o.getTime()+e*6e4).toISOString()}function Go(o,e,t,n){let i={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return i;o.InventoryV2??={};let s=o.InventoryV2,r=n.toISOString(),p=new Map,m=new Map,R=new Map,W=new Map,me=new Map,Me=new Map,De=new Map,_e=new Map,Et=e.Grant?.PremiumTiers??[],rt=Et.length;for(let ue=0;;ue++){let we,fe;if(ue===0)we=e.Grant?.Standard?.Entries,fe=false;else if(ue-1<rt)we=Et[ue-1]?.Resources?.Entries,fe=false;else if(ue===1+rt)we=e.Consume?.Standard?.Entries,fe=true;else break;if(we)for(let de of we){if(de.Type==null)continue;let ye=Math.max(0,de.Amount??0);if(!(ye<=0))switch(de.Type){case "VirtualCurrency":{if(!de.CurrencyID)continue;let Ce=fe?m:p;Ce.set(de.CurrencyID,(Ce.get(de.CurrencyID)??0)+ye);break}case "CryptoCurrency":{if(!de.CurrencyID)continue;let Ce=fe?W:R;Ce.set(de.CurrencyID,(Ce.get(de.CurrencyID)??new rn(0)).plus(ye));break}case "Item":{if(!de.ItemID)continue;let Ce=yy(t,de.CatalogID,de.ItemID),ve=(Ce?Ce.IsStackable??true:true)?fe?Me:me:fe?_e:De;ve.set(de.ItemID,(ve.get(de.ItemID)??0)+ye);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(i.vcChanged=p.size>0||m.size>0,i.vcChanged){s.VirtualCurrencies??={};for(let ue of new Set([...p.keys(),...m.keys()])){let we=p.get(ue)??0,fe=m.get(ue)??0,de=we-fe,ye=s.VirtualCurrencies[ue];ye?(ye.Amount+=de,ye.UpdatedAt=r,ye.Daily&&bn(ye.Daily.PeriodStartUtc)===bn(n)?(ye.Daily.Earned+=we,ye.Daily.Spent+=fe):ye.Daily={PeriodStartUtc:Gn(n),Earned:we,Spent:fe}):s.VirtualCurrencies[ue]={Amount:de,CreatedAt:r,UpdatedAt:r,Daily:{PeriodStartUtc:Gn(n),Earned:we,Spent:fe}};}}if(i.ccChanged=R.size>0||W.size>0,i.ccChanged){s.CryptoCurrencies??={};for(let ue of new Set([...R.keys(),...W.keys()])){let we=R.get(ue)??new rn(0),fe=W.get(ue)??new rn(0),de=we.minus(fe),ye=s.CryptoCurrencies[ue];ye?(ye.Amount=new rn(ye.Amount).plus(de).toString(),ye.UpdatedAt=r):s.CryptoCurrencies[ue]={Amount:de.toString(),Frozen:"0",CreatedAt:r,UpdatedAt:r};}}if(i.itemsChanged=me.size>0||Me.size>0||De.size>0||_e.size>0,i.itemsChanged){s.Items??={},s.UnstackableItems??={};let ue=s.UnstackableItems,we=new Set([...me.keys(),...Me.keys(),...De.keys(),..._e.keys()]);for(let fe of we){let de=(me.get(fe)??0)-(Me.get(fe)??0),ye=(De.get(fe)??0)-(_e.get(fe)??0),Ce=de+ye,pt=s.Items[fe];pt?(de!==0&&(pt.StackableAmount+=de),ye!==0&&(pt.UnstackableAmount+=ye),Ce!==0&&(pt.TotalAmount+=Ce)):s.Items[fe]={StackableAmount:Math.max(0,de),UnstackableAmount:Math.max(0,ye),TotalAmount:Math.max(0,Ce)};}for(let[fe,de]of _e){if(de<=0)continue;let ye=Object.values(ue).filter(Ce=>Ce.ItemID===fe&&Ce.EquippedSlot==null&&(Ce.ExpiresAt==null||new Date(Ce.ExpiresAt)>n)).sort(gy).slice(0,de).map(Ce=>Ce.ItemInstanceID);for(let Ce of ye)delete ue[Ce];}for(let[fe,de]of De){let ye=Ry(t,fe);for(let Ce=0;Ce<de;Ce++){let pt=a();ue[pt]={ItemInstanceID:pt,ItemID:fe,CatalogID:ye,RemainingUses:1,AcquiredAt:r};}}}o.EventToken??={};let En=o.EventToken;for(let ue=0;;ue++){let we,fe;if(ue===0)we=e.Grant?.Standard?.EventTokens,fe=false;else if(ue-1<rt)we=Et[ue-1]?.Resources?.EventTokens,fe=false;else if(ue===1+rt)we=e.Consume?.Standard?.EventTokens,fe=true;else break;if(!(!we||we.length===0))for(let de of we){let ye=de.Address;if(!ye||ye.Type==null)continue;let Ce=de.Amount??0;if(Ce<=0)continue;let pt=Cy(En,ye.Type);if(!pt)continue;let ve=pt[ye.EntityID];ve||(ve={},pt[ye.EntityID]=ve),ve.Balance??={Current:0,TotalEarned:0,TotalSpent:0},ve.Daily??={Date:Gn(n),TotalEarned:0},ve.Meta??={};let qn=de.Source&&de.Source.length>0?de.Source:"CustomAction";fe?(ve.Balance.Current-=Ce,ve.Balance.TotalSpent+=Ce):(ve.Balance.Current+=Ce,ve.Balance.TotalEarned+=Ce,bn(ve.Daily.Date)!==bn(n)&&(ve.Daily={Date:Gn(n),TotalEarned:0}),ve.Daily.TotalEarned+=Ce,ve.Daily.EarnedBySource??={},ve.Daily.EarnedBySource[qn]=(ve.Daily.EarnedBySource[qn]??0)+Ce,ve.Daily.TriggersBySource??={},ve.Daily.TriggersBySource[qn]=(ve.Daily.TriggersBySource[qn]??0)+1,ve.Daily.LastTriggerBySource??={},ve.Daily.LastTriggerBySource[qn]=r,ve.Meta.JoinedAtUtc||(ve.Meta.JoinedAtUtc=r),ve.Meta.LastEarnedAtUtc=r),i.tokensChanged=true;}}return i}function gy(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 yy(o,e,t){let n=o?.Catalogs;if(n){if(e){let i=n[e]?.Items?.[t];if(i)return i}for(let i of Object.values(n)){let s=i.Items?.[t];if(s)return s}}}function Ry(o,e){let t=o?.Catalogs;if(t){for(let[n,i]of Object.entries(t))if(i.Items&&e in i.Items)return n}}function Cy(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??={};case "Challenge":return o.Challenge??={};case "ChallengePoints":return o.ChallengePoints??={};default:return null}}function Cu(o,e,t){let n={drop:[],restore:{}};if(!t)return n;let i=t.ChangedInstances??{},s=new Set(t.RemovedInstanceIDs??[]),r=new Set;for(let m of Object.values(i))m?.ItemID&&r.add(m.ItemID);for(let m of s){let R=o[m]?.ItemID;R&&r.add(R);}if(r.size===0)return n;let p=m=>s.has(m)||m in i;if(e){for(let[m,R]of Object.entries(e))m in o||p(m)||R&&r.has(R.ItemID)&&n.drop.push(m);for(let[m,R]of Object.entries(o))m in e||p(m)||R&&r.has(R.ItemID)&&(n.restore[m]=R);}return n}function No(o,e){return o===e||o.startsWith(`${e}:`)}var Si=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 n of Object.values(t))n&&(typeof n.Amount=="number"&&(n.Amount=String(n.Amount)),typeof n.Frozen=="number"&&(n.Frozen=String(n.Frozen)));}applyUserState(e){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 n of t)this.currentState[n]=e[n];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,n=new Date){if(!this.currentState)return;let i=Go(this.currentState,e,t,n);this.emitResourceChanges(i,false);}applyResourcesWithDelta(e,t,n,i=new Date){if(!this.currentState)return;let s=this.currentState,r={...s.InventoryV2?.UnstackableItems??{}},p=Go(s,e,n,i),m=Cu(r,s.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),W=t?.RemovedInstanceIDs??[],me=m.drop.length>0||Object.keys(m.restore).length>0||R.length>0||W.length>0;if(me){s.InventoryV2??={},s.InventoryV2.UnstackableItems??={};let Me=s.InventoryV2.UnstackableItems;for(let De of m.drop)delete Me[De];for(let[De,_e]of Object.entries(m.restore))Me[De]=_e;for(let[De,_e]of R)Me[De]=_e;for(let De of W)delete Me[De];}this.emitResourceChanges(p,me);}emitResourceChanges(e,t){let n=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),n&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(n||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,n,i){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let s=this.currentState.InventoryV2.CryptoCurrencies,r=t instanceof rn?t:new rn(t),p=i===void 0?new rn(0):i instanceof rn?i:new rn(i),m=n??new Date().toISOString(),R=s[e];R?(R.Amount=new rn(R.Amount).plus(r).toString(),p.isZero()||(R.Frozen=new rn(R.Frozen??0).plus(p).toString()),R.UpdatedAt=m):s[e]={Amount:r.toString(),Frozen:p.toString(),CreatedAt:m,UpdatedAt:m},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,n){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let i=this.currentState.Store.Purchases,s=i[e];s||(s={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},i[e]=s),s.TotalPurchases+=t,s.LastPurchasedAt=n,n>=s.DailyResetUtc?(s.DailyPurchases=t,s.DailyResetUtc=yu(n)):s.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,n){if(!e||n<=0)return;this.currentState??={};let i=this.currentState.Lootbox??={};if(i.Pity??={},t){let s=new Date().toISOString();for(let r of t)r.RuleID&&(i.Pity[`${e}:${r.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:s});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchRewardWindowState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Windows??={},this.currentState.Reward.Windows[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,n){if(!e)return;this.currentState??={},this.currentState.Quest??={};let i=this.currentState.Quest;if(t){i.Cycles??={};let s=i.Cycles[t];if(!s)return;s.Quests??={};let r=s.Quests[e]??={QuestID:e,Status:n};r.Status=n,n==="Claimed"&&(r.ClaimedAtUtc??=new Date().toISOString());}else {i.PermanentQuests??={};let s=i.PermanentQuests[e]??={QuestID:e,Status:n};s.Status=n,n==="Claimed"&&(s.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let n=this.getQuestPointsProgress(e);n&&(n.Milestone??={},this.markMilestoneClaimed(n.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let n of Object.values(e)){if(!n.CycleID)continue;let i=n.InstanceKey?`${n.CycleID}:${n.InstanceKey}`:n.CycleID,s=t[i]??={};s.Balance??={Current:0,TotalEarned:0,TotalSpent:0},s.Balance.Current=n.PointsCurrent??0,s.Balance.TotalEarned=n.PointsTotalEarned??0,s.Milestone??={};for(let r of n.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(s.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 n=this.currentState.Quest.Cycles[e];n&&(n.ClaimedGroupCompletionIDs??=[],n.ClaimedGroupCompletionIDs.includes(t)||n.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let n=t.Flows[e.FlowID]??={FlowID:e.FlowID};n.Status=e.Status,n.CurrentStepID=e.CurrentStepID??null,n.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(n.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let n of e){if(!n.FlowID||!n.StepID)continue;let i=t.Flows[n.FlowID]??={FlowID:n.FlowID,Status:"InProgress"};i.Steps??={};let s=i.Steps[n.StepID]??={StepID:n.StepID};s.Progress=n.Progress,n.Completed&&(s.CompletedAtUtc??=new Date().toISOString(),i.CurrentStepID===n.StepID&&(i.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let n of e){if(!n.QuestID)continue;let i;if(!n.CycleID)t.PermanentQuests??={},i=t.PermanentQuests[n.QuestID]??={QuestID:n.QuestID,Status:n.Status};else {t.Cycles??={};let s=t.Cycles[n.CycleID];if(!s)continue;s.Quests??={},i=s.Quests[n.QuestID]??={QuestID:n.QuestID,Status:n.Status};}if(i.Status=n.Status,n.ObjectiveID){i.Objectives??={};let s=i.Objectives[n.ObjectiveID]??={ObjectiveID:n.ObjectiveID,CurrentValue:0,Completed:false};s.CurrentValue=n.NewValue??0,n.ObjectiveCompleted&&(s.Completed=true,s.CompletedAtUtc??=new Date().toISOString());}n.Status==="Completed"&&(i.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[n,i]of Object.entries(t))if(No(n,e)&&i)return i;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,n,i){if(!(!t||!n)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[s,r]of Object.entries(this.currentState.EventToken.TimedEvent))r&&((i?s!==i:!No(s,t))||this.markMilestoneClaimed(r.Milestone??(r.Milestone={}),n));this.patchActiveEventMilestoneClaimed(e,t,n,i),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,n,i){let s=this.activeEventsCache?.ActiveEvents;if(s)for(let r of s)r.Type!==e||r.TimedEventID!==t||i&&r.TokenEntityID&&r.TokenEntityID!==i||(r.Progress??={},this.markMilestoneClaimed(r.Progress.Milestone??(r.Progress.Milestone={}),n));}markMilestoneClaimed(e,t){e.Claims??={};let n=e.Claims[t]??={};n.ClaimedAt??=new Date().toISOString(),n.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let n=this.ensureLeaderboardProgress(e);n.CurrentScore=t.CurrentScore??0,n.LastKnownRank=t.LastKnownRank??0,n.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,n.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,n.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,n,i){if(!e)return;let s=this.ensureLeaderboardProgress(e);(s.ScoreCycleVersion??0)<i&&(s.ScoreEarnedThisCycle=0,s.ClaimedMilestoneIDs=[],s.BracketID=null),s.CurrentScore=t,s.ScoreEarnedThisCycle=(s.ScoreEarnedThisCycle??0)+n,s.ScoreCycleVersion=i,s.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let n=this.ensureLeaderboardProgress(e);n.ClaimedMilestoneIDs??=[],n.ClaimedMilestoneIDs.includes(t)||n.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,n=t[e];return n||(n={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=n),n}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let n=this.ensureSeasonState(e);n.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let n=this.ensureSeasonState(e);n.ClaimedTierRewards??=[],n.ClaimedTierRewards.includes(t)||n.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,n=t[e];return n||(n={SeasonChainID:e},t[e]=n),n}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let n=this.currentState?.Character?.Characters;if(!n)return;let i=false;for(let s of Object.values(n))for(let r of Object.values(s.Equipment??{}))r?.ItemInstanceID===e&&(r.Level=t,i=true);i&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySelectedCharacter(e){this.currentState??={},this.currentState.Character??={};let t=e??null;(this.currentState.Character.SelectedCharacterID??null)!==t&&(this.currentState.Character.SelectedCharacterID=t,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let n=this.currentState.Character.Characters,i=n[e];i||(i={CharacterID:e},n[e]=i),t(i),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,n){if(!e||!t)return;let i=this.currentState?.Character?.Characters?.[e];i&&(i.Equipment??={},n===null?delete i.Equipment[t]:i.Equipment[t]=n,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,n=false;for(let[i,s]of Object.entries(e.ChangedInstances??{}))t[i]=s,n=true;for(let i of e.RemovedInstanceIDs??[])i in t&&(delete t[i],n=true);n&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,n){this.currentState??={};let i=this.currentState.CoopEvent??={MyObjectIndex:-1};i.ActiveGroupID=e,i.ActiveCoopEventID=t,i.MyObjectIndex=n,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(n=>n!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(n=>n!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(n=>n!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),n=false;typeof e.FriendsCount=="number"&&(n||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(n||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(n||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),n&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let n=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let i of Object.keys(n)){let s=n[i];s&&s.BoostID===e.BoostID&&i!==e.InstanceID&&delete n[i];}n[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,n,i,s){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let r=this.currentState.CustomData,p={Value:n,UpdatedAt:new Date().toISOString(),Version:i,LastWriter:"Client",ExpiresAt:s??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 n=this.currentState.CustomData;if(e==="Private")n.Private&&delete n.Private[t];else if(e==="Public")n.Public&&delete n.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let n=this.ensureBoard();n.BuildingStates??=[];let i=n.BuildingStates.find(s=>s.SlotIndex===e);i||(i={SlotIndex:e},n.BuildingStates.push(i)),t(i),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let i=this.ensureBoard().Pending;i&&(e&&(i.RaidLayout=e),t>=0&&(i.OpenedIndices??=[],i.OpenedIndices.includes(t)||i.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let n=this.ensureBoard().Pending;!n||n.Type.toUpperCase()!=="SPECIAL"||(n.Special??={},e(n.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let i of Object.values(e.CryptoBalances??{}))i?.CurrencyID&&this.patchCryptoCurrencyDelta(i.CurrencyID,i.AmountDelta,i.UpdatedAt,i.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),n=e.PendingAdded;if(t.size>0||n){let i=this.currentState.Blockchain??={},s=i.PendingWithdrawals??[];t.size>0&&(s=s.filter(r=>!r.TitleTransactionID||!t.has(r.TitleTransactionID))),n&&!s.some(r=>r.TitleTransactionID===n.TitleTransactionID)&&(s=[...s,n]),i.PendingWithdrawals=s;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var xi=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,n]of Object.entries(e))this.sections.has(t)||this.sections.set(t,n);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let n=this.config?.[e];return n??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var bi=class{user;config;constructor(e){this.user=new Si(e),this.config=new xi;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Sy(o){return o}var xy=0,by=1500,Dy=3,Ii=class{constructor(e,t,n=null,i="",s="auto"){this.emitter=e;this.config=t;this.storage=n;this.titleId=i;this.loginMode=s;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return a$1(void 0);let n=Date.now(),i=[],s=[];for(let m of new Set(e)){let R=this.rules.get(m);if(R&&(t?.force||R.needsServer(n))){i.push(this.runRule(m,R));continue}(t?.force||!this.state.isStateFresh(m,t?.maxAgeMs))&&s.push(m);}let p=(await Promise.all([...i,s.length>0?this.queueSlice(s):Promise.resolve(a$1(void 0))])).find(m=>!m.ok);return p&&!p.ok?p:a$1(void 0)}runRule(e,t){let n=this.ruleInflight.get(e);if(n)return n;let i=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,i),i}queueSlice(e){for(let n of e)this.pending.add(n);let t=new Promise(n=>this.waiters.push(n));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},xy),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let n;this.batchRunning=new Promise(i=>n=i);try{let i=this.state?await this.state.readStateSlice(e):a$1(void 0),s=i.ok?a$1(void 0):i;for(let r of t)r(s);}finally{this.batchRunning=null,n();}}async read(e,t,n){this.register(e);let i=Di(e,n?.args);if(this.noteUsed(e,n?.args,n?.loginParams),!n?.forceRefresh){let R=this.fresh(i,n?.maxAgeMs);if(R)return a$1(R.data);let W=this.loginFailures.get(i);if(W)return this.loginFailures.delete(i),W;let me=this.inflight.get(i);if(me)return me}let s=this.generation.get(i)??0,r=Date.now(),m=t().then(R=>{if(!R.ok)return R;let W=Date.now();if((this.generation.get(i)??0)===s)return this.entries.set(i,{data:R.data,storedAt:W,expiresAt:_o(e,R.data,W)}),R;let me=this.entries.get(i);if(me&&me.storedAt>=r)return R;let Me=_o(e,R.data,W);return this.entries.set(i,{data:R.data,storedAt:W,expiresAt:Math.min(Me??1/0,W+by)}),R}).finally(()=>{this.inflight.get(i)===m&&this.inflight.delete(i);});return this.inflight.set(i,m),m}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...n})=>n))}acceptLoginViews(e){for(let t of e??[]){let n=this.loginBindings.get(t.Name);if(!n)continue;let i=t.Key?t.Key:void 0,s=Di(n.view,i);if(!t.Success){this.loginFailures.set(s,b("server",t.Error??"View failed."));continue}let r=n.schema.safeParse(t.Data);r.success&&(this.loginFailures.delete(s),n.apply(r.data,i),this.put(n.view,r.data,i));}}noteUsed(e,t,n){if(!e.login||this.loginMode!=="auto")return;let i=e.login;this.loadUsed().then(()=>{let s=Su({Name:i,Key:t});this.used.get(s)?.n!==this.session&&(this.used.set(s,{Name:i,Key:t??"",...n,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>Dy||this.used.set(Su(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),n=t?JSON.parse(t):null;return !n||typeof n.s!="number"||!Array.isArray(n.v)?e:{session:n.s,views:n.v.filter(i=>i&&typeof i.Name=="string"&&typeof i.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(Di(e,t))?.data}put(e,t,n){this.register(e);let i=Di(e,n);this.bump(i);let s=Date.now();this.entries.set(i,{data:t,storedAt:s,expiresAt:_o(e,t,s)});}invalidate(e,t){let n=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${n}|${t}`);return}for(let i of [...this.entries.keys(),...this.inflight.keys()])(i===n||i.startsWith(`${n}|`))&&this.drop(i);this.drop(n);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,n])=>({key:t,ageMs:e-n.storedAt,expiresInMs:n.expiresAt===null?null:n.expiresAt-e}))}fresh(e,t){let n=this.entries.get(e);if(!n)return;let i=Date.now();if(!(n.expiresAt!==null&&i>=n.expiresAt)&&!(t!==void 0&&i-n.storedAt>t))return n}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let n of this.views.values())n.dependsOn?.some(i=>t.has(i))&&this.invalidate(n);}};function Di(o,e){return e===void 0?o.key:`${o.key}|${e}`}function Su(o){return o.Key?`${o.Name}|${o.Key}`:o.Name}function _o(o,e,t){let n=o.expiresAt?.(e)??null,i=o.ttlMs!==void 0?t+o.ttlMs:null;return n!==null&&i!==null?Math.min(n,i):n??i}var Pi=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 Iy(e)?e:r.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 Iy(o){return o!==null&&Object.values(r).includes(o)}var Py=8,vy=100,Ay=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,vi=["GameLoop"];function Ty(o){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(o)}var Ai=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=r.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,n){let i=this.authContext;if(!i)return c;let s=this.baseRequest();s.UserID=i.userID,s.ClientSessionTicket=i.clientSessionTicket,s.WalletAddress=e,s.NetworkID=t,n&&(s.WalletSignature=n);let r=await this.ctx.api.authentication.linkWallet(s);return r.ok&&r.data.PlayAccess&&this.setPlayAccess(r.data.PlayAccess),r}async unlinkWallet(e){let t=this.authContext;if(!t)return c;let n=this.baseRequest();n.UserID=t.userID,n.ClientSessionTicket=t.clientSessionTicket,n.NetworkID=e;let i=await this.ctx.api.authentication.unlinkWallet(n);return i.ok&&i.data.PlayAccess&&this.setPlayAccess(i.data.PlayAccess),i}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.host.getDeviceID(),e.Device=this.ctx.host.getDeviceModel(),e.Platform=this.ctx.host.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(r.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.host.getTelegramInitDataRaw();if(!e)return b("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let n=await this.ctx.api.authentication.loginWithTelegram(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(r.Telegram)):n}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.Password=t;let i=await this.ctx.api.authentication.loginWithEmail(n);if(!i.ok)return i;this.applyAuthContext(i.data);let s=await this.fetchAndApplyClientState(r.Email);return s.ok&&this.keepEmailCredentials(e,t),s}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.Password=t,n.DeviceID=this.ctx.host.getDeviceID(),n.Device=this.ctx.host.getDeviceModel(),n.Platform=this.ctx.host.getPlatform();let i=await this.ctx.api.authentication.registerWithEmail(n);return i.ok?(this.pendingRegistration={email:e,password:t},a$1({codeTtlMinutes:i.data.CodeTtlMinutes??0,resendCooldownSeconds:i.data.ResendCooldownSeconds??0})):i}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.VerificationCode=t;let i=await this.ctx.api.authentication.confirmEmailRegistration(n);if(!i.ok)return i;this.applyAuthContext(i.data);let s=await this.fetchAndApplyClientState(r.Email);return s.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,s}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let n=await this.ctx.api.authentication.resendVerificationCode(t);return n.ok?a$1(void 0):n}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let n=await this.ctx.api.authentication.loginWithGoogle(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(r.Google)):n}async loginWithApple(e,t){if(!e?.trim())return b("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.AppleIDToken=e,t?.nonce&&(n.AuthNonce=t.nonce),t?.name?.trim()&&(n.Username=t.name.trim());let i=await this.ctx.api.authentication.loginWithApple(n);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(r.Apple)):i}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.WalletAddress=e,n.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(n)}async loginWithWallet(e,t,n){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.WalletAddress=e,i.NetworkID=t,i.WalletSignature=n,i.Platform=this.ctx.host.getPlatform(),i.Device=this.ctx.host.getDeviceModel(),i.DeviceID=this.ctx.host.getDeviceID();let s=await this.ctx.api.authentication.loginWithWallet(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(r.Wallet)):s}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.host.getDeviceID(),t.Device=this.ctx.host.getDeviceModel(),t.Platform=this.ctx.host.getPlatform();let n=await this.ctx.api.authentication.loginWithSsoCode(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(r.iDosGames)):n}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 n=await this.ctx.userService.prepareLoginClientState(vi,vi);t.ClientState=n.request;let i=await this.ctx.api.authentication.resolvePlatformGameSession(t);if(!i.ok)return i;this.applyAuthContext(i.data),this.platformGameSession=true;let s=i.data.ClientState;return this.fetchAndApplyClientState(r.iDosGames,s?()=>n.finish(s):void 0)}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,n){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.Email=e,i.ResetToken=t,i.Password=n,this.ctx.api.authentication.resetPassword(i)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==r.None?e:r.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let n=this.baseRequest();n.RefreshToken=t,e?.appOpened&&(n.AppOpened=true);let i=await this.ctx.api.authentication.refreshSession(n);return i.ok?(this.applyRefresh(i.data),"ok"):(Ty(i.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,n){switch(e){case r.Email:return this.loginWithEmail(t,n);case r.Device:case r.None:return this.loginWithDeviceID();case r.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 this.ctx.host.signIn(this.ctx.settings.titleID);if(!t.ticket)return null;let n=this.baseRequest();n.PlatformGameTicket=t.ticket;let i=await this.ctx.api.authentication.resolvePlatformGameSession(n);return i.ok?(this.applyAuthContext(i.data),this.platformGameSession=!0,i.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==r.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===r.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&&Ay.test(e)}static isValidPasswordLength(e){return e.length>=Py&&e.length<=vy}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=r.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e,t){let n=t?await t():await this.ctx.userService.getClientStateExcept(vi,vi);return n.ok&&(this.sessionAuthType=e,this.rememberSession?(this.ctx.authStore.saveAuthType(e),this.ctx.authStore.saveRefreshToken(this.sessionRefreshToken)):this.ctx.authStore.clear(),this.ctx.emitter.emit("auth:loggedIn",void 0)),n}};var zy="idos:cfg",Dn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${xu(t)}`:e&&e.length>0?`f:${xu(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.v!="string"||!n.c?null:n}catch{return null}}async write(e,t,n){try{let i={v:t,c:n};await this.storage.set(this.keyOf(e),JSON.stringify(i));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${zy}:${this.titleId}:${e}`}};function xu(o){return [...o].map(e=>e.toLowerCase()).sort().join(",")}var bu="idos:loc",In=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.v!="number"||!n.t||typeof n.t!="object"?null:n}catch{return null}}async write(e,t,n){try{let i={v:t,t:n};await this.storage.set(this.keyOf(e),JSON.stringify(i)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let n={};for(let[i,s]of Object.entries(t))typeof s=="number"&&s>0&&(n[i]=s);return n}catch{return {}}}async noteVersion(e,t){let n=await this.readVersions();n[e]!==t&&(n[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(n)));}keyOf(e){return `${bu}:${this.titleId}:${e}`}versionsKey(){return `${bu}:${this.titleId}:versions`}};var wy="idos:sec",Ti=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let n=JSON.parse(t);return !n||typeof n!="object"||n.v!==e||!n.s||typeof n.s!="object"?{}:n.s}catch{return {}}}async write(e,t){try{let n={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(n));}catch{}}keyOf(){return `${wy}:${this.titleId}`}};var ky="idos:state",zi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.e!="string"||!n.v||!n.s?null:n}catch{return null}}async write(e,t,n,i){if(!(!e||!t))try{let s={e:t,v:n,s:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}keyOf(e){return `${ky}:${this.titleId}:${e}`}};function My(o,e){if(!o)return;let t=new Set((e??[]).map(i=>i.trim().toLowerCase()));if(t.size===0)return o;let n={};for(let[i,s]of Object.entries(o))t.has(i.toLowerCase())||(n[i]=s);return n}function Vo(o,e,t,n){let i={...o??{}};if(!e||!t||!n)return i;for(let[s,r]of Object.entries(t))n[s]===r&&s in e&&(i[s]=e[s]);return i}function Oy(o){return {...o??{}}}function jo(o){return typeof o.StateEpoch=="string"&&o.StateEpoch.length>0?o.StateEpoch:null}var wi=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,n=Date.now()){if(this.versions[e]===void 0)return false;let i=this.confirmedAt[e];return i===void 0?false:t===void 0||n-i<=t}forget(e){let t=[];for(let n of e)this.versions[n]!==void 0&&(delete this.versions[n],delete this.confirmedAt[n],t.push(n));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=My(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let r=Object.keys(this.versions);this.reset(e),this.notify(r);}return []}let n=Date.now(),i=[],s=[];for(let[r,p]of Object.entries(t)){let m=this.versions[r];m!==p&&(m!==void 0&&p===m+1?(this.versions[r]=p,this.confirmedAt[r]=n):(delete this.versions[r],delete this.confirmedAt[r],m!==void 0&&p>m+1&&s.push(r)),i.push(r),this.dirty=true);}return this.notify(i),s}afterFullRead(e,t){let n=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=Oy(t);let i=Date.now();this.confirmedAt={};for(let r of Object.keys(this.versions))this.confirmedAt[r]=i;this.dirty=true;let s=new Set;for(let r of new Set([...Object.keys(n),...Object.keys(this.versions)]))n[r]!==this.versions[r]&&s.add(r);this.notify([...s]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let n=Date.now(),i=[];for(let[s,r]of Object.entries(t??{}))this.versions[s]!==r&&i.push(s),this.versions[s]=r,this.confirmedAt[s]=n;this.dirty=true,this.notify(i);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Du=b("server","Title configuration is unavailable (CDN and API both failed)."),ki=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:a()}:null}get configCache(){return this.cache??=new Dn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new In(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new Ti(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new wi(new zi(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){if(!this.ctx.auth.context?.userID||!this.stateStore.currentEpoch)return;let i=this.stateStore.noteMutation(e,t);i.length>0&&(this.ctx.cache.ensureState(i),this.ctx.emitter.emit("user:changedElsewhere",{containers:i}));}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return c;let t=Dn.scopeOf(e.TitleFields,null),n=await this.configCache.read(t);n&&(e.KnownTitleConfigVersion=n.v),await this.prepareLocalization(e);let i=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let s=await this.ctx.api.user.getClientState(e);if(!s.ok)return s;let r=await this.resolveTitleConfig(s.data,t,n,{Fields:e.TitleFields});return r==null?Du:(this.finishStateHandshake(s.data,i),await this.restoreSections(s.data.TitleConfigVersion,r),await this.applyClientState(s.data,r,void 0,void 0),this.ctx.cache.acceptLoginViews(s.data.Views),await this.applyLocalization(s.data.Localization),await this.flushState(i),s)}async prepareStateHandshake(e,t){let n=this.ctx.auth.context?.userID;if(!n)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(n),await this.stateStore.flush(n,this.ctx.data.user.state);let i=this.stateStore.versionsFor(t);if(i){e.KnownStateVersions=i;let s=this.stateStore.currentEpoch;s&&(e.KnownStateEpoch=s);}return {userId:n,cached:this.stateStore.cachedState,sent:i}}finishStateHandshake(e,t){let n=Vo(e.User,t.cached,t.sent,e.StateVersions);e.User=n;let i=jo(e);!i||!t.userId||this.stateStore.afterFullRead(i,e.StateVersions);}async resolveTitleConfig(e,t,n,i){let s=e.TitleConfigVersion;if(n&&s&&n.v===s)return n.c;if(e.TitleConfigUrl){let p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return s&&await this.configCache.write(t,s,p),p}let r=await this.fetchConfigFromApi(i);return r!=null?(s&&await this.configCache.write(t,s,r),r):n?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let n=await t.json();return n&&typeof n=="object"?n:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let n={...t,...e},i=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(n):await this.ctx.api.title.getTitlePublicConfiguration(n);return i.ok?i.data:null}async getClientStateExcept(e,t){let n=this.baseRequest();if(!n)return c;let i=await this.prepareClientStateExcept(n,e,t,true),s=await this.ctx.api.user.getClientStateExcept(n);return s.ok?this.finishClientStateExcept(i,s.data):s}async prepareLoginClientState(e,t){let n={BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:a()},i=await this.prepareClientStateExcept(n,e,t,false);return {request:n,finish:async s=>{let r=this.ctx.auth.context?.userID??null;return r&&await this.stateStore.load(r),i.handshake={userId:r,cached:null,sent:void 0},this.finishClientStateExcept(i,s)}}}async prepareClientStateExcept(e,t,n,i){e.ExcludeFields=t,e.ExcludeTitleFields=n;let s=Dn.scopeOf(null,n??[]),r=await this.configCache.read(s);r&&(e.KnownTitleConfigVersion=r.v),await this.prepareLocalization(e);let p=i?await this.prepareStateHandshake(e,t??null):{userId:null,cached:null,sent:void 0};return await this.prepareLoginViews(e),{scope:s,cached:r,handshake:p,excludeFields:t,excludeTitleFields:n}}async finishClientStateExcept(e,t){let n=await this.resolveTitleConfig(t,e.scope,e.cached,{ExcludeFields:e.excludeTitleFields??[]});return n==null?Du:(this.finishStateHandshake(t,e.handshake),await this.restoreSections(t.TitleConfigVersion,n),await this.applyClientState(t,n,e.excludeFields,e.excludeTitleFields),this.ctx.cache.acceptLoginViews(t.Views),await this.applyLocalization(t.Localization),await this.flushState(e.handshake),a$1(t))}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let n=t,i={};for(let[s,r]of Object.entries(await this.sectionCache.read(e)))n[s]==null&&(i[s]=r);this.ctx.data.config.restoreSections(i),this.ctx.data.config.setSectionSink((s,r)=>{n[s]!=null||r==null||(i[s]=r,this.sectionCache.write(e,i));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let n=await this.localizationCache.readVersions();Object.keys(n).length>0&&(e.KnownLocalizationVersions=n);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),n=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:n});}async resolveLocalizationTable(e){let t=e.Locale??null,n=e.Version??0;if(!t)return null;let i=await this.localizationCache.read(t);if(n<=0)return i?.t??null;if(i&&i.v===n)return i.t;if(e.Url){let r=await this.fetchLocalizationFromCdn(e.Url);if(r!=null)return await this.localizationCache.write(t,n,r),r}let s=await this.fetchLocalizationFromApi(t,i?.v??0);return s??i?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let n=await t.json();return n&&typeof n=="object"?n:null}catch{return null}}async fetchLocalizationFromApi(e,t){let n=this.baseRequest();if(!n)return null;let i=await this.ctx.api.localization.getLocalizationTable({...n,Locale:e,KnownVersion:t});if(!i.ok)return null;let s=i.data;if(s.NotModified)return null;let r=s.Entries??{},p=s.Version??0,m=s.Locale??e;return p>0&&await this.localizationCache.write(m,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}async getUserState(e){let t=this.baseRequest();if(!t)return c;e&&e.length>0&&(t.Fields=e);let n=await this.prepareStateHandshake(t,null),i=await this.ctx.api.user.getUserState(t);if(!i.ok)return i;let s=Vo(i.data.User,n.cached,n.sent,i.data.StateVersions);i.data.User=s;let r=n.sent??{},p=Object.entries(i.data.StateVersions??{}).filter(([R,W])=>r[R]!==W||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(s,p);let m=jo(i.data);return m&&(this.stateStore.afterSliceRead(m,i.data.StateVersions),await this.flushState(n)),i}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return 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,n){let i=this.baseRequest();if(!i)return c;i.UsageTime=e,i.IsNewSession=t,i.SessionDurationSeconds=n;let s=await this.ctx.api.user.addUsageTime(i);return s.ok&&this.ctx.emitter.emit("user:usageTimeAdded",s.data),s}async deleteUserAccount(){let e=this.baseRequest();if(!e)return 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 n=await this.ctx.api.user.changeUsername(t);return n.ok&&this.ctx.emitter.emit("user:usernameChanged",n.data),n}async applyClientState(e,t,n,i){let s=n?.includes("GameLoop")===true,r=i?.includes("GameLoop")===true,p=s?this.ctx.data.user.state?.GameLoop:void 0,m=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;s&&R&&R.GameLoop==null&&(R.GameLoop=p);let W=this.ctx.data.config.titlePublicConfiguration;r&&W&&W.GameLoop==null&&(W.GameLoop=m),this.ctx.emitter.emit("user:clientStateReceived",e);}};var Oi=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return b("client","SpendID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${a()}`},i=await this.ctx.api.currency.spend(n);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",i.data)),i}async convert(e,t,n,i,s,r){if(!t)return b("client","SourceID is required.");if(!i)return b("client","TargetID is required.");if(s<=0)return b("client","Amount must be positive.");if(e===n&&t===i)return b("client","Source and target must differ.");if(e===f.Crypto||n===f.Crypto)return b("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return c;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:n,TargetID:i,SourceAmount:String(Math.trunc(s)),TransactionID:r&&r.length>0?r:`convert_${e}_${t}_to_${n}_${i}_${a()}`},m=await this.ctx.api.currency.convert(p);if(m.ok){let R=m.data,W={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(W,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return m}async cryptoConvert(e,t,n,i,s,r){let p=s instanceof rn?s:new rn(s);if(!t)return b("client","SourceID is required.");if(!i)return b("client","TargetID is required.");if(p.lte(0))return b("client","SourceAmount must be a positive decimal.");if(e===n&&t===i)return b("client","Source and target must differ.");if(e===f.Virtual&&n===f.Virtual)return b("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===f.Virtual&&!p.isInteger())return b("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return c;let m={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:n,TargetID:i,SourceAmount:p.toString(),TransactionID:r&&r.length>0?r:`crypto_convert_${e}_${t}_to_${n}_${i}_${a()}`},R=await this.ctx.api.currency.cryptoConvert(m);if(R.ok){let W=R.data,me=[],Me=[];if(W.SourceType===f.Virtual&&me.push({Type:"VirtualCurrency",CurrencyID:W.SourceID,Amount:Math.trunc(Number(W.SourceSpent))}),W.TargetType===f.Virtual&&Me.push({Type:"VirtualCurrency",CurrencyID:W.TargetID,Amount:Math.trunc(Number(W.TargetCredited))}),me.length>0||Me.length>0){let De={Consume:me.length>0?{Standard:{Entries:me}}:null,Grant:Me.length>0?{Standard:{Entries:Me}}:null};this.ctx.data.user.applyResourceOperation(De,this.ctx.data.config.itemDefinitions);}W.SourceType===f.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(W.SourceID,new rn(W.SourceSpent).negated(),W.ServerTimeUtc),W.TargetType===f.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(W.TargetID,new rn(W.TargetCredited),W.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",W);}return R}};var Ei=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,n,i){let s=e.trim();if(!s)return b("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:n,CreditsConfirmationID:i,RelatedEntityID:`upgrade_item_${s}_${a()}`};t&&t.length>0&&(r.FodderInstanceIDs=[...t]);let p=await this.ctx.api.item.upgradeLevel(r);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(p.data.ItemInstanceID??s,p.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",p.data)),p}async upgradeLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},n=await this.ctx.api.item.upgradeLevelsBatch(t);if(n.ok){for(let i of n.data)i.Success&&i.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(i.Data.ItemInstanceID,i.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",n.data);}return n}};var qi=z.object({OptionID:z.string().nullish(),Name:z.string().nullish(),Cost:qt.nullish(),AllowedPlatforms:z.array(k).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),he=z.record(z.string(),qi),Ey=z.object({Store:m,Receipt:z.string(),Signature:z.string().nullish()}).passthrough();var Nn={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},ge=z.object({ConfirmationID:z.string(),Url:z.string(),Status:z.string(),PriceCredits:z.number(),ExpiresAt:u}).passthrough(),Iu=z.object({Linked:z.boolean(),Credits:z.number(),TopUpUrl:z.string().nullish()}).passthrough(),qy={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"},Fo=z.object({ServerTimeUtc:u,OfferID:z.string(),Count:z.number(),Resources:O.nullish(),Inventory:Q.nullish(),CreditsConfirmation:ge.nullish()}),Pu=z.array(ke(Fo)),Uy=z.object({OfferID:z.string(),TotalPurchases:z.number(),DailyPurchases:z.number(),DailyResetUtc:u,LastPurchasedAt:u}),Ly=z.object({SlotKey:z.string(),InstanceKey:z.string(),OfferID:z.string().nullish(),Purchases:z.number(),LastPurchasedAt:u}),vu=z.object({Purchases:z.record(z.string(),Uy).nullish(),Rotations:z.record(z.string(),Ly).nullish()}).passthrough().transform(o=>o),Lt=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(),Ui=z.object({Schedule:Re.nullish(),Gate:ee.nullish()}).passthrough(),By={Fixed:"Fixed",Title:"Title",Player:"Player"},Gy=z.object({OfferID:z.string().nullish(),Weight:z.number().nullish(),Gate:ee.nullish()}).passthrough(),Au=z.object({Mode:z.string().nullish(),OfferID:z.string().nullish(),Pool:z.array(Gy).nullish(),Salt:z.string().nullish(),PerInstanceCap:z.number().nullish()}).passthrough(),Ny=z.object({Identity:J.nullish(),Availability:J.nullish(),Rotation:J.nullish()}).passthrough(),_y=z.object({SlotID:z.string().nullish(),Identity:Lt.nullish(),Availability:Ui.nullish(),Rotation:Au.nullish(),Presets:Ny.nullish()}).passthrough(),Vy=z.object({Identity:J.nullish(),Availability:J.nullish()}).passthrough(),jy=z.object({SectionID:z.string().nullish(),Identity:Lt.nullish(),Availability:Ui.nullish(),Slots:z.record(z.string(),_y).nullish(),UniqueOffersInSection:z.boolean().nullish(),Presets:Vy.nullish()}).passthrough(),Tu=z.object({Sections:z.record(z.string(),jy).nullish()}).passthrough(),Fy=z.object({Identity:J.nullish(),Availability:J.nullish(),Layout:J.nullish()}).passthrough(),Wy=z.object({StoreID:z.string().nullish(),Identity:Lt.nullish(),Availability:Ui.nullish(),Layout:Tu.nullish(),Presets:Fy.nullish()}).passthrough(),zu=z.object({Options:he.nullish(),CompareAt:z.record(z.string(),qt).nullish()}).passthrough(),wu=z.object({Grant:$.nullish()}).passthrough(),ku=z.object({Schedule:Re.nullish(),Gate:ee.nullish(),Limits:Ie.nullish()}).passthrough(),Ky=z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish(),Availability:J.nullish()}).passthrough(),Qy=z.object({OfferID:z.string().nullish(),Identity:Lt.nullish(),Pricing:zu.nullish(),Reward:wu.nullish(),Availability:ku.nullish(),Presets:Ky.nullish()}).passthrough(),Hy=z.object({Identity:z.record(z.string(),Lt).nullish(),Availability:z.record(z.string(),Ui).nullish(),Layout:z.record(z.string(),Tu).nullish(),Rotation:z.record(z.string(),Au).nullish(),Pricing:z.record(z.string(),zu).nullish(),Reward:z.record(z.string(),wu).nullish(),OfferAvailability:z.record(z.string(),ku).nullish()}).passthrough(),Li=z.object({Stores:z.record(z.string(),Wy).nullish(),StoreOffers:z.record(z.string(),Qy).nullish(),Presets:Hy.nullish()}).passthrough(),$y=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:u.nullish()}).passthrough(),Jy=z.object({OptionID:z.string(),Name:z.string().nullish(),Cost:qt.nullish(),CompareAtCost:qt.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(),Zy=z.object({OfferID:z.string(),Identity:Lt.nullish(),PriceOptions:z.array(Jy).nullish(),Rewards:$.nullish(),State:$y.nullish()}).passthrough(),Yy=z.object({SlotID:z.string(),Identity:Lt.nullish(),SortOrder:z.number(),RotationMode:z.string().nullish(),RotationInstanceKey:z.string().nullish(),RefreshesAtUtc:u.nullish(),RemainingThisRotation:z.number().nullish(),Offer:Zy.nullish()}).passthrough(),Xy=z.object({SectionID:z.string(),Identity:Lt.nullish(),SortOrder:z.number(),Slots:z.array(Yy).nullish()}).passthrough(),eR=z.object({StoreID:z.string(),Identity:Lt.nullish(),SortOrder:z.number(),ScheduleInstanceKey:z.string().nullish(),ExpiresAtUtc:u.nullish(),Sections:z.array(Xy).nullish()}).passthrough(),Bi=z.object({ServerTimeUtc:u,Stores:z.array(eR).nullish(),AdCreditBalance:z.number()}).passthrough(),Bt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},tR="OFFER_NOT_IN_ROTATION";var Mu="Store",Ou={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 n of t.Sections??[])for(let i of n.Slots??[]){let s=Date.parse(i.RefreshesAtUtc??"");!Number.isNaN(s)&&(e===null||s<e)&&(e=s);}return e}},Gi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ou,{schema:Bi,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,n){if(!e)return b("client","OfferID is required.");if(t<1)return b("client","Count must be at least 1.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,StoreID:n?.slot?.storeID,SectionID:n?.slot?.sectionID,SlotID:n?.slot?.slotID,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${i.userID}_${a()}`},r=await this.ctx.api.store.purchase(s);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,n={}){return await this.ctx.credits.pay(i=>this.purchase(e,t,{selectedOptionID:n.selectedOptionID,slot:n.slot,creditsConfirmationID:i}),{onConfirmation:n.onConfirmation,signal:n.signal,pollMs:n.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):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},n=await this.ctx.api.store.purchaseBatch(t);if(n.ok){let i=false;for(let s of n.data)!s.Success||!s.Data||!s.Data.OfferID||(this.ctx.data.user.patchStorePurchase(s.Data.OfferID,s.Data.Count,s.Data.ServerTimeUtc),!i&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true));this.ctx.emitter.emit("store:offersPurchasedBatch",n.data);}return n}async getDefinitions(e){let t=this.ctx.cache.configSection(Mu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.store.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Mu,i.data),this.ctx.emitter.emit("store:definitionsLoaded",i.data)),i}getStorefront(e){return this.ctx.cache.read(Ou,()=>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 n of t.Sections??[])for(let i of n.Slots??[]){let s=i.RefreshesAtUtc;s&&(e===null||Date.parse(s)<Date.parse(e))&&(e=s);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return 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 Ni=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let n=await e(void 0);if(!n.ok||!n.data.CreditsConfirmation)return n;let i=n.data.CreditsConfirmation,s=()=>e(i.ConfirmationID);if(this.ctx.host.supports.creditsConfirm){let m=await this.ctx.host.confirmCredits({titleID:this.ctx.settings.titleID,confirmationID:i.ConfirmationID});if(m.ok)return await s();if(m.error==="DECLINED")return b("server","CREDITS_CONFIRMATION_DECLINED");if(m.error==="NOT_ENOUGH_CREDITS")return b("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(i);let r=Math.max(1e3,t.pollMs??2500),p=Date.parse(i.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return b("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>p)return b("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(W=>setTimeout(W,r));let m=await this.ctx.store.getCreditsConfirmation(i.ConfirmationID);if(!m.ok)continue;let R=m.data.Status;if(R!==Nn.Pending)return R===Nn.Declined?b("server","CREDITS_CONFIRMATION_DECLINED"):R===Nn.Expired?b("server","CREDITS_CONFIRMATION_EXPIRED"):await s()}}};var _i=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$1(t.data.Purchase??{}):t}async validatePurchase(e,t,n){if(!t)return b("client","Receipt is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:n?.signature,ProductID:n?.productID,TransactionID:n?.transactionID},s=await this.ctx.api.purchase.validatePurchase(i);return s.ok&&this.applyValidation(s.data),s}async buyWithTelegramStars(e,t){if(!e)return b("client","productID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),ProductID:e},i=await this.ctx.api.purchase.createTelegramInvoice(n);return i.ok&&t?.open!==false&&this.ctx.host.openInvoice(i.data.InvoiceLink),i}async buy(e){if(!e)return b("client","productID is required.");if(!this.ctx.host.supports.storePurchases)return b("client","UNAVAILABLE");if(!this.ctx.auth.context)return c;let t=await this.getDefinitions();if(!t.ok)return t;let n=t.data.Purchase?.Products?.[e],i=this.hostStore(),s=n?.StoreProductIDs?.[i];if(!n||n.Enabled===false||!s)return b("client","NOT_SOLD");let r=this.ctx.buildAuthedBaseRequest(),p=await this.ctx.host.buyProduct({storeProductID:s,type:n.Type??"Consumable",accountID:r.UserID??void 0});return !p.ok||!p.receipt?b("client",p.error??"FAILED"):this.deliver(p.receipt,n)}async restorePending(){if(!this.ctx.host.supports.storePurchases||!this.ctx.auth.context)return 0;let e=await this.ctx.host.pendingPurchases();if(e.length===0)return 0;let t=await this.getDefinitions(),n=t.ok?Object.values(t.data.Purchase?.Products??{}):[],i=0;for(let s of e){let r=n.find(p=>s.storeProductID&&p.StoreProductIDs?.[s.store]===s.storeProductID);(await this.deliver(s,r)).ok&&i++;}return i}async deliver(e,t){let n=await this.validatePurchase(e.store,e.receipt,{signature:e.signature});return n.ok&&await this.ctx.host.finishPurchase(e,(t?.Type??"Consumable")==="Consumable"),n}hostStore(){return this.ctx.host.getClientPlatform()===j.Ios?"AppleAppStore":"GooglePlay"}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},n=await this.ctx.api.purchase.validatePurchasesBatch(t);if(n.ok)for(let i of n.data.Items)i.Success&&i.Data&&this.applyValidation(i.Data);return n}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Eu=3,nR=700,Vi=class{constructor(e){this.ctx=e;e.host.supports.cryptoTopUp&&this.setTopUpHandler(this.hostTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return xn(e)}hostTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let n=await this.ctx.host.topUp({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return n.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:n.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=Eu;t++){let n=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(n.ok)return;if(n.reason!=="throttled"||t===Eu)break;await Wt(nR);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,n])=>({...n,OptionID:n.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,n)=>(t.OptionID??"").localeCompare(n.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let n of t)if(n?.Type===h.Purchase&&n.ProductID)return n.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let n of t){if(n?.Type!==h.CryptoCurrency||!n.CurrencyID)continue;let i=Number(n.Amount??0);if(!(i>0))continue;let s=this.cryptoBalance(n.CurrencyID);return s>=i?null:{currencyID:n.CurrencyID,required:i,available:s,missing:i-s}}return null}cryptoBalance(e){let n=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(n?.Amount??0)}};var qu="Lootbox",ji=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(qu,e);if(t){let s={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),a$1(s)}let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.lootbox.getDefinitions(n);if(i.ok){let s=i.data.LootboxDefinitions;s&&(this.ctx.data.config.patchSection(qu,s),this.ctx.emitter.emit("lootbox:definitionsLoaded",s));}return i}async open(e,t,n,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;let r={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:n,Payment:i,CreditsConfirmationID:s,RelatedEntityID:`lootbox_${e}_${n??"default"}_${a()}`},p=await this.ctx.api.lootbox.open(r);if(p.ok&&!p.data.CreditsConfirmation){let m=p.data;m.TriggeredPity&&m.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,m.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(m.Resources,m.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",m);}return p}};var Wo="Reward";function Fi(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Wi=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(Wo)?.Comebacks??{}).some(n=>n?.TrackPresenceOnRead===true),refresh:async()=>{let n=await this.getUserRewardsState();return n.ok&&(t=true),n}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(Wo,e);if(t){let s={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),a$1(s)}let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.reward.getRewardDefinitions(n);if(i.ok){let s=i.data.RewardDefinitions;s&&(this.ctx.data.config.patchSection(Wo,s),this.ctx.emitter.emit("reward:definitionsLoaded",s));}return i}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 n=t.data;this.multiplierEnabled=n.Enabled,this.multiplier=n.Enabled?n.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",n);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return c;let n={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${a()}`},i=await this.ctx.api.reward.claimDailyReward(n);if(i.ok){let s=i.data;this.ctx.data.user.patchDailyCalendarState(s.CalendarID,s.DailyState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",s);}return i}async collectIdleAccrual(e){if(!Fi(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}_${a()}`},n=await this.ctx.api.reward.collectIdleAccrual(t);if(n.ok){let i=n.data;this.ctx.data.user.patchIdleAccrualState(i.AccrualID,i.IdleState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",i);}return n}async claimComebackReward(e){if(!Fi(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}_${a()}`},n=await this.ctx.api.reward.claimComebackReward(t);if(n.ok){let i=n.data;this.ctx.data.user.patchComebackState(i.ComebackID,i.ComebackState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",i);}return n}async claimReward(e){if(!Fi(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}_${a()}`},n=await this.ctx.api.reward.claimReward(t);if(n.ok){let i=n.data;this.ctx.data.user.patchClaimRewardState(i.ClaimID,i.ClaimState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",i);}return n}async claimRewardWindow(e,t,n={}){if(!Fi(e))return b("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return b("client","Amount must be a positive number.");let i=n.boost??"None";if(i==="Ad"&&!n.adRequestID)return b("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:i,...n.adRequestID?{AdRequestID:n.adRequestID}:{},RelatedEntityID:n.roundID??`reward_window_${e}_${a()}`},r=await this.ctx.api.reward.claimRewardWindow(s);if(r.ok){let p=r.data;this.ctx.data.user.patchRewardWindowState(p.WindowID,p.WindowState),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:windowClaimed",p);}return r}};var Ki="Tutorial",Uu={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"]},Qi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Uu,{schema:hi,apply:n=>this.applyUserTutorialState(n)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(Ki)?.Flows??{}).length>0,refresh:async()=>{let n=await this.getUserTutorialState();return n.ok&&(t=true),n}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(Ki,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.tutorial.getTutorialDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Ki,i.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",i.data)),i}getUserTutorialState(e=true,t){return this.ctx.cache.read(Uu,()=>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 n=await this.ctx.api.tutorial.getUserTutorialState(t);return n.ok&&this.applyUserTutorialState(n.data),n}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.reportStepShown(n))}async completeStep(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.completeStep(n),{relatedEntityID:`tutorial_step_${e}_${t}_${a()}`})}async completeStepsBatch(e,t){let n=e?.trim();if(!n)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 i={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepIDs:t,RelatedEntityID:`tutorial_batch_${n}_${a()}`},s=await this.ctx.api.tutorial.completeStepsBatch(i);return s.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",s.data)),s}async skipStep(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.skipStep(n))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${a()}`},i=await this.ctx.api.tutorial.claimFlowReward(n);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",i.data)),i}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,n){let i=e?.trim();if(!i)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i},r=await t(s);return r.ok&&(this.applyFlowView(r.data),this.ctx.emitter.emit(n.event,r.data)),r}async stepCall(e,t,n,i){let s=e?.trim(),r=t?.trim();if(!s)return b("client","FlowID is required.");if(!r)return b("client","StepID is required.");if(!this.ctx.auth.context)return c;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:s,StepID:r};i?.relatedEntityID&&(p.RelatedEntityID=i.relatedEntityID);let m=this.ctx.data.user.state?.Tutorial?.Flows?.[s]?.RewardClaimed===true,R=await n(p);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(s,r,m,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,n,i){return !n&&i.Flow?.RewardClaimed===true?true:i.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Ki)?.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 Hi=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 n=await this.ctx.api.communityMarketing.getEarnings(t);return n.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",n.data),n}async claim(e){if(!e)return b("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.CampaignID=e;let n=await this.ctx.api.communityMarketing.claim(t);return n.ok&&this.ctx.emitter.emit("communityMarketing:claimed",n.data),n}async withdrawCryptoReward(e,t,n){if(!e)return b("client","campaignID is required.");if(!t)return b("client","walletAddress is required.");let i=this.ctx.authedRequest();if(!i)return c;i.CampaignID=e,i.WalletAddress=t,n&&(i.Amount=n);let s=await this.ctx.api.communityMarketing.withdrawCryptoReward(i);return s.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",s.data),s}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Be=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 iR={Global:"Global",Announcement:"Announcement",Group:"Group"},Bu=z.enum(["Global","Announcement","Group"]).catch("Global"),sR={None:"None",Language:"Language",Region:"Region"},rR=z.enum(["None","Language","Region"]).catch("None"),oR={Anyone:"Anyone",Friends:"Friends"},aR=z.enum(["Anyone","Friends"]).catch("Anyone"),lR={Reject:"Reject",Mask:"Mask"},uR=z.enum(["Reject","Mask"]).catch("Reject"),cR={Player:"Player",Publisher:"Publisher",System:"System"},pR=z.enum(["Player","Publisher","System"]).catch("Player"),hR={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var dR=z.object({DisplayNameKey:z.string().nullish(),SortOrder:z.number().nullish(),IconPath:z.string().nullish(),JoinedByDefault:z.boolean().nullish()}).passthrough(),Gu=z.object({Gate:ee.nullish(),Schedule:Re.nullish()}).passthrough(),Nu=z.object({Gate:ee.nullish(),Limits:Ie.nullish(),MaxLength:z.number().nullish()}).passthrough(),_u=z.object({HotTailSize:z.number().nullish(),HistoryHours:z.number().nullish()}).passthrough(),mR=z.object({Availability:J.nullish(),Write:J.nullish(),Retention:J.nullish()}).passthrough(),fR=z.object({ChannelID:z.string().nullish(),Identity:dR.nullish(),Type:Bu.nullish(),GroupSource:z.string().nullish(),Partitioning:rR.nullish(),Capacity:z.number().nullish(),Availability:Gu.nullish(),Write:Nu.nullish(),Retention:_u.nullish(),Presets:mR.nullish()}).passthrough(),gR=z.object({IsEnabled:z.boolean().nullish(),Gate:ee.nullish(),WhoCanMessage:aR.nullish(),Limits:Ie.nullish(),MaxLength:z.number().nullish(),HistoryHours:z.number().nullish(),MaxConversations:z.number().nullish()}).passthrough(),yR=z.object({BlockedTerms:z.array(z.string()).nullish(),BlockedTermAction:uR.nullish(),MaxIgnoreListSize:z.number().nullish(),ReportsEnabled:z.boolean().nullish(),ReportLimits:Ie.nullish()}).passthrough(),RR=z.object({MinIntervalSeconds:z.number().nullish(),MaxMessagesPerPoll:z.number().nullish(),MaxHistoryPageSize:z.number().nullish()}).passthrough(),CR=z.object({Availability:z.record(z.string(),Gu).nullish(),Write:z.record(z.string(),Nu).nullish(),Retention:z.record(z.string(),_u).nullish()}).passthrough(),Vu=z.object({IsEnabled:z.boolean().nullish(),Channels:z.record(z.string(),fR).nullish(),Direct:gR.nullish(),Moderation:yR.nullish(),Polling:RR.nullish(),Presets:CR.nullish()}).passthrough(),SR=z.object({LastReadAt:z.string().nullish(),LastReadMessageID:z.string().nullish(),Left:z.boolean().nullish()}).passthrough(),Lu=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(),SR).nullish(),Limits:z.record(z.string(),Lu).nullish(),ReportLimits:Lu.nullish()}).passthrough();var Ko=z.object({RoomID:z.string().nullish(),SentAt:z.string().nullish(),MessageID:z.string().nullish()}).passthrough(),$i=z.object({RoomID:z.string().nullish(),ChannelID:z.string().nullish(),MessageID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderProfile:Be.nullish(),AuthorType:pR.nullish(),Text:z.string().nullish(),SentAt:z.string().nullish(),SystemKey:z.string().nullish(),SystemParams:z.record(z.string(),z.string()).nullish()}).passthrough(),xR=z.object({ChannelID:z.string().nullish(),RoomID:z.string().nullish(),DisplayNameKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),Type:Bu.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(),Ji=z.object({Channels:z.array(xR).nullish(),PollIntervalSeconds:z.number().nullish(),MutedUntil:z.string().nullish(),MuteReason:z.string().nullish()}).passthrough(),bR=z.object({RoomID:z.string().nullish(),Messages:z.array($i).nullish(),NextCursor:Ko.nullish(),UnreadCount:z.number().nullish(),ServedFromDatabase:z.boolean().nullish()}).passthrough(),ju=z.object({Rooms:z.array(bR).nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),Fu=z.object({RoomID:z.string().nullish(),Messages:z.array($i).nullish(),NextBefore:Ko.nullish()}).passthrough(),Wu=z.object({Message:$i.nullish(),Moderated:z.boolean().nullish()}).passthrough(),Ku=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Be.nullish(),MaxLength:z.number().nullish()}).passthrough(),DR=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Be.nullish(),LastMessage:$i.nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),Qu=z.object({Conversations:z.array(DR).nullish()}).passthrough(),Pn=z.object({Ignored:z.array(z.string()).nullish(),Cursor:Ko.nullish(),Joined:z.boolean().nullish()}).passthrough(),Hu=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish()}).passthrough(),et={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 $u="Chat",Ju={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Zi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ju,{schema:Ji,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection($u,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.chat.getChatDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection($u,i.data),this.ctx.emitter.emit("chat:definitionsLoaded",i.data)),i}getChannels(e,t){return this.ctx.cache.read(Ju,()=>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 n=await this.ctx.api.chat.getChannels(t);return n.ok&&this.ctx.emitter.emit("chat:channelsLoaded",n.data),n}async poll(e){let t=this.ctx.authedRequest();if(!t)return c;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let n=await this.ctx.api.chat.poll(t);if(!n.ok)return n;for(let i of n.data.Rooms??[])i.NextCursor&&i.RoomID&&this.cursors.set(i.RoomID,i.NextCursor),i.Messages&&i.Messages.length>0&&this.ctx.emitter.emit("chat:messages",i);return n}async getHistory(e,t,n){let i=this.ctx.authedRequest();return i?(i.RoomID=e,t&&(i.Before=t),n&&(i.Limit=n),this.ctx.api.chat.getHistory(i)):c}async sendMessage(e,t,n){let i=this.ctx.authedRequest();if(!i)return c;i.ChannelID=e,i.Text=t,n&&(i.Locale=n);let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async sendDirect(e,t){let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.Text=t;let i=await this.ctx.api.chat.sendMessage(n);return i.ok&&this.ctx.emitter.emit("chat:sent",i.data),i}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):c}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):c}async markRead(e,t){let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let i=await this.ctx.api.chat.markRead(n);return i.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),i}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):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,n,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,s.MessageID=t,s.Reason=n,i&&(s.Comment=i),this.ctx.api.chat.reportMessage(s)):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 IR={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},PR=z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),vR={Player:"player",Title:"title",Creator:"creator"},vn={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Zu=z.object({Configured:z.boolean().nullish(),PublicKey:z.string().nullish()}).passthrough(),AR=z.object({TitleID:z.string().nullish(),Topic:z.string().nullish()}).passthrough(),Qo=z.object({EndpointHash:z.string().nullish(),Transport:PR.nullish(),Locale:z.string().nullish(),Topics:z.array(AR).nullish()}).passthrough(),Yu=z.object({Configured:z.boolean().nullish(),Subscriptions:z.array(Qo).nullish()}).passthrough(),tt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var TR="IDOS_PLATFORM_PUSH_REQUEST",zR="IDOS_PLATFORM_PUSH_RESPONSE",wR=12e4;function Xu(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(n=>{let i=false,s=m=>{i||(i=true,window.removeEventListener("message",r),clearTimeout(p),n(m));},r=m=>{let R=m?.data;!R||R.type!==zR||R.requestId!==t||z$1.includes(m.origin)&&s(R.ok===true);},p=setTimeout(()=>s(false),wR);window.addEventListener("message",r);for(let m of z$1)try{e.postMessage({type:TR,requestId:t,titleID:o},m);}catch{}})}var kR="idos:push:deviceToken:",Yi=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let n=await this.ctx.api.push.getPushConfig(t),i=n.ok?n.data:{Configured:false,PublicKey:null};return this.cachedConfig=i,n.ok&&this.ctx.emitter.emit("push:configLoaded",i),i}async getState(){let e=await this.getConfig();if(this.ctx.host.supports.pushNotifications){if(!e.Configured)return tt.Unsupported;let s=await this.ctx.host.requestPushToken({prompt:false});return s.error==="BLOCKED"?tt.Blocked:s.token?this.ctx.host.storage.getString(this.deviceTokenKey())===s.token?tt.Subscribed:tt.Idle:s.error==="NOT_GRANTED"?tt.Idle:tt.Unsupported}if(!e.Configured||!e.PublicKey)return tt.Unsupported;if(this.isEmbedded())return tt.Embedded;if(!this.isSupported())return tt.Unsupported;let t=Notification.permission;return t==="denied"?tt.Blocked:t!=="granted"?tt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?tt.Subscribed:tt.Idle}async subscribe(e={}){let t=await this.getConfig();if(this.ctx.host.supports.pushNotifications)return this.subscribeDevice(t,e);if(!t.Configured||!t.PublicKey)return b("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Xu(this.ctx.settings.titleID)?a$1({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 n=await Notification.requestPermission();if(n!=="granted")return b("client",n==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let i=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let r=await i.pushManager.getSubscription()??await i.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:MR(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return c;let m=r.toJSON();p.PushEndpoint=m.endpoint,p.PushP256dh=m.keys?.p256dh,p.PushAuth=m.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(p);return R.ok?(this.ctx.emitter.emit("push:subscribed",R.data),a$1({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return c;if(this.ctx.host.supports.pushNotifications){let n=this.ctx.host.storage.getString(this.deviceTokenKey());if(!n)return b("client","This device has no push subscription to remove.");e.PushDeviceToken=n;let i=await this.ctx.api.push.unsubscribePush(e);return i.ok&&(this.ctx.host.storage.remove(this.deviceTokenKey()),this.ctx.emitter.emit("push:unsubscribed",void 0)),i}if(this.isSupported()){let i=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();i&&(e.PushEndpoint=i.endpoint,await i.unsubscribe());}if(!e.PushEndpoint)return 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 n=await this.ctx.api.push.unsubscribePush(t);return n.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),n}async subscribeDevice(e,t){if(!e.Configured)return b("client","Push notifications are not available for this title.");let n=await this.ctx.host.requestPushToken({prompt:true});if(!n.token)return b("client",n.error==="BLOCKED"?"The player blocked notifications for this app.":"The device gave no push token.");let i=this.ctx.authedRequest();if(!i)return c;i.PushTransport=n.transport??"Fcm",i.PushDeviceToken=n.token,i.PushLocale=t.locale??(this.ctx.host.getLanguage()||void 0),i.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let s=await this.ctx.api.push.subscribePush(i);return s.ok?(this.ctx.host.storage.setString(this.deviceTokenKey(),n.token),this.ctx.emitter.emit("push:subscribed",s.data),a$1({Where:"game",Subscription:s.data})):s}deviceTokenKey(){return kR+this.ctx.settings.titleID}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function MR(o){let e=o.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(o.length/4)*4,"="),t=atob(e),n=new ArrayBuffer(t.length),i=new Uint8Array(n);for(let s=0;s<t.length;s++)i[s]=t.charCodeAt(s);return n}var Xi=Object.freeze({}),es=class{constructor(e){this.ctx=e;}ctx;table={...Xi};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new In(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,n])=>({Locale:n?.Locale??t,DisplayName:n?.DisplayName??null,Order:n?.Order??0})).sort((t,n)=>(t.Order??0)-(n.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let n=this.resolveKey(e,t),i=this.lookup(n)??this.lookup(e);return i===void 0?this.onMissing(e):t?OR(i,t):i}applyState(e,t){if(!e){this.reset();return}let n=e.Locale??null;this.table=t.table??{...Xi},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return c;let n=await this.loadTableFromApi(e);if(!n.ok)return n;let{locale:i,table:s,fallbackLocale:r}=n.data,p=null;if(r){let m=await this.loadTableFromApi(r);m.ok&&(p=m.data.table);}return this.table=s,this.fallbackTable=p,this.currentFallbackLocale=r,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:r,entryCount:Object.keys(s).length}),{ok:true,data:i}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):c}reset(){this.table={...Xi},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:a()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return c;t.Locale=e;let n=await this.cache.read(ec(e));n&&(t.KnownVersion=n.v);let i=await this.ctx.api.localization.getLocalizationTable(t);if(!i.ok)return i;let s=i.data,r=s.Locale??ec(e),p=s.Version??0;if(s.NotModified){let R=n??await this.cache.read(r);return {ok:true,data:{locale:r,table:R?.t??{...Xi},fallbackLocale:s.FallbackLocale??null}}}let m=s.Entries??{};return p>0&&await this.cache.write(r,p,m),{ok:true,data:{locale:r,table:m,fallbackLocale:s.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let n=t?.count;if(typeof n!="number")return e;let i=this.pluralCategory(n),s=`${e}.${i}`;if(this.lookup(s)!==void 0)return s;let 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 OR(o,e){return o.replace(/\{(\w+)\}/g,(t,n)=>{let i=e[n];return i===void 0?t:String(i)})}function ec(o){return o.trim().replace(/_/g,"-").toLowerCase()}var Ho="Quest",ER={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:o=>{let e=Date.now(),t=null,n=[...Object.values(o.PointsTracks??{}).map(i=>i?.CycleEndUtc),...Object.values(o.State?.Cycles??{}).map(i=>i?.CycleEndUtc)];for(let i of n){let s=Date.parse(i??"");!Number.isNaN(s)&&s>e&&(t===null||s<t)&&(t=s);}return t}},ts=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:n=>{let i=e.cache.configSection(Ho)?.Cycles;if(!i)return false;let s=e.data.user.state?.Quest?.Cycles??{};for(let r of Object.keys(i)){let p=Date.parse(s[r]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=n&&t<p)return true}return false},refresh:async()=>{let n=await this.getUserQuestState(true,{forceRefresh:true});return n.ok&&(t=Date.now()),n}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(Ho,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.quest.getQuestDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Ho,i.data),this.ctx.emitter.emit("quest:definitionsLoaded",i.data)),i}getUserQuestState(e=true,t){return this.ctx.cache.read(ER,()=>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 n=await this.ctx.api.quest.getUserQuestState(t);if(n.ok){let i=n.data.State??{};this.ctx.data.user.applyQuest(i),this.ctx.data.user.patchQuestPointsTracks(n.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",i);}return n}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return 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 n=e.trim();if(!n)return b("client","QuestID is required.");if(!this.ctx.auth.context)return c;let i=t&&t.trim().length>0?t.trim():void 0,s={...this.ctx.buildAuthedBaseRequest(),QuestID:n,CycleID:i,RelatedEntityID:`quest_claim_${i??""}_${n}_${a()}`},r=await this.ctx.api.quest.claimQuestReward(s);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;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},n=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(n.ok){let i=false;for(let s of n.data)!s.Success||!s.Data||(this.ctx.data.user.patchQuestStatus(s.Data.QuestID,s.Data.CycleID,"Claimed"),!i&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",n.data);}return n}async claimMilestoneReward(e,t){let n=e.trim(),i=t.trim();if(!n||!i)return b("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CycleID:n,MilestoneID:i,RelatedEntityID:`milestone_claim_${n}_${i}_${a()}`},r=await this.ctx.api.quest.claimMilestoneReward(s);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;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(n.ok){let i=false;for(let s of n.data)!s.Success||!s.Data||(this.ctx.data.user.patchMilestoneClaimed(s.Data.CycleID,s.Data.MilestoneID),!i&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",n.data);}return n}async claimGroupCompletionReward(e,t){let n=e.trim(),i=t.trim();if(!n||!i)return b("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CycleID:n,GroupCompletionID:i,RelatedEntityID:`group_completion_${n}_${i}_${a()}`},r=await this.ctx.api.quest.claimGroupCompletionReward(s);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 n=e.trim();if(!n)return b("client","MetricID is required.");if(t<0)return b("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),MetricID:n,ProgressValue:t},s=await this.ctx.api.quest.addQuestProgress(i);return s.ok&&(this.ctx.data.user.patchQuestProgressUpdates(s.data.Updates),this.ctx.emitter.emit("quest:progressAdded",s.data)),s}};var tc=z.object({}).passthrough().transform(o=>o);var qR=z.object({Order:z.number().nullish(),Type:z.string().nullish(),DurationSec:z.number().nullish(),BonusMultiplier:z.number().nullish()}).passthrough(),UR=z.object({Schedule:z.array(qR).nullish(),RepeatCycle:z.boolean().nullish(),MaxCycles:z.number().nullish()}).passthrough(),LR=z.object({IsActive:z.boolean().nullish(),CurrentPhaseEndUtc:u.nullish(),NextBonusStartUtc:u.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentPhaseIndex:z.number().nullish(),ActiveBonusMultiplier:z.number().nullish()}).passthrough(),BR=z.object({Milestones:J.nullish()}).passthrough(),$o=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Category:z.string().nullish(),Token:At.nullish(),TokenSources:z.array(ht).nullish(),ClaimMode:z.string().nullish(),Milestones:z.record(z.string(),Ve).nullish(),Presets:BR.nullish(),BonusWindow:UR.nullish()}).passthrough(),GR=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Content:$o.nullish(),ClaimGraceHours:z.number().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),NR=z.object({TimedEventID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:Re.nullish(),Content:$o.nullish(),Events:z.array(GR).nullish(),Gate:ee.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),_R=z.object({MaxConcurrentEvents:z.number().nullish()}).passthrough(),VR=z.object({Milestones:z.record(z.string(),Rn).nullish()}).passthrough(),ns=z.object({Definitions:z.record(z.string(),NR).nullish(),Settings:_R.nullish(),Presets:VR.nullish()}).passthrough(),jR=z.object({Type:q,TimedEventID:z.string(),CurrentChainedEventID:z.string().nullish(),Content:$o.nullish(),Progress:tc.nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),NextMilestone:Ve.nullish(),BonusWindow:LR.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentEventOrder:z.number().nullish(),TotalEventsInChain:z.number().nullish(),TokenEntityID:z.string().nullish()}).passthrough(),is=z.object({ActiveEvents:z.array(jR).nullish()}).passthrough(),nc=z.object({Tokens:z.record(z.string(),tc).nullish()}),Jo=z.object({Type:q.nullish(),LteID:z.string().nullish(),Resources:O.nullish()}),Zo=z.object({Type:q.nullish(),LteID:z.string().nullish(),MilestoneID:z.string().nullish(),TokenEntityID:z.string().nullish(),Rewards:O.nullish(),Inventory:Q.nullish()}),FR=z.object({Type:q.nullish(),LteID:z.string().nullish(),Resources:O.nullish()}),Yo=z.array(ke(Zo)),ic=z.array(ke(Jo)),sc=z.array(ke(FR)),ft={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var rc="TimedEvent",oc={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 n=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},ss=class{constructor(e){this.ctx=e;e.cache.bindLoginView(oc,{schema:is,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(oc,()=>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(rc,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.timedEvent.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(rc,i.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",i.data)),i}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,n,i,s,r,p=1){if(!t)return b("client","LteID is required.");if(!n)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c;let m={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:n,Outcome:i,AmountOverride:s,SourceParams:r,RollMultiplier:p},R=await this.ctx.api.timedEvent.grantTokens(m);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,n){if(!t)return b("client","LteID is required.");if(n<=0)return b("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:n},s=await this.ctx.api.timedEvent.spendTokens(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",s.data)),s}async claimMilestone(e,t,n){if(!t||!n)return b("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:n},s=await this.ctx.api.timedEvent.claimMilestone(i);if(s.ok){let r=s.data;this.ctx.data.user.applyResourcesWithDelta(r.Rewards,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,n,r.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",r);}return s}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},n=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return n.ok&&(this.applyMilestoneClaimBatch(n.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",n.data)),n}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return c;e&&e.length>0&&(t.Events=e);let n=await this.ctx.api.timedEvent.claimAllMilestones(t);return n.ok&&(this.applyMilestoneClaimBatch(n.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",n.data)),n}async spendTokensBatch(e){if(!e||e.length===0)return b("client","spends is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},n=await this.ctx.api.timedEvent.spendTokensBatch(t);if(n.ok){let i=false;for(let s of n.data)!i&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(s.Data.Resources,this.ctx.data.config.itemDefinitions),i=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",n.data);}return n}async grantTokensBatch(e){if(!e||e.length===0)return b("client","grants is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},n=await this.ctx.api.timedEvent.grantTokensBatch(t);if(n.ok){let i=false;for(let s of n.data)!i&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(s.Data.Resources,this.ctx.data.config.itemDefinitions),i=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",n.data);}return n}applyMilestoneClaimBatch(e){let t=false;for(let n of e){if(!n.Success||!n.Data)continue;let i=n.Data;i.Type&&i.LteID&&i.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(i.Type,i.LteID,i.MilestoneID,i.TokenEntityID),!t&&i.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(i.Rewards,i.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var WR=z.object({UserID:z.string(),Score:H.nullish(),Rank:z.number().nullish(),LastScoreUpdateUtc:u.nullish(),IpHash:z.string().nullish(),PublicProfile:Be.nullish(),SeasonTierAtCycleEnd:z.number().nullish()}).passthrough(),_n=z.object({LeaderboardID:z.string(),CycleVersion:z.number().nullish(),TotalParticipants:H.nullish(),CycleEndUtc:u.nullish(),TopUsers:z.array(WR).nullish(),BracketID:z.string().nullish()}),KR=z.object({CycleKey:z.string().nullish(),CycleEndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),MilestoneTokensEarned:H.nullish(),ClaimableMilestoneIDs:z.array(z.string()).nullish(),CycleIndex:z.number().nullish(),ChainedEventID:z.string().nullish()}).passthrough(),rs=z.object({LeaderboardID:z.string(),CurrentScore:H.nullish(),LastKnownRank:z.number().nullish(),HasUnclaimedReward:z.boolean().nullish(),UnclaimedRewardRank:z.number().nullish(),ScoreEarnedThisCycle:H.nullish(),MilestoneTokensEarned:H.nullish(),TokenEntityID:z.string().nullish(),NextMilestone:Ve.nullish(),HasUnclaimedMilestone:z.boolean().nullish(),GrantedPremiumTiers:z.record(z.string(),z.array(z.string())).nullish(),ClaimableGraceCycles:z.array(KR).nullish()}),os=z.object({LeaderboardID:z.string(),NewScore:H,CycleVersion:z.number()}),as=z.object({ServerTimeUtc:u,LeaderboardID:z.string(),Rank:z.number().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),ls=z.object({ServerTimeUtc:u,LeaderboardID:z.string(),MilestoneID:z.string(),Resources:O.nullish(),Inventory:Q.nullish()}),ac=z.array(ke(_n)),us=z.array(ke(rs)),lc=z.array(ke(as)),uc=z.array(ke(ls)),cc=z.array(ke(os)),QR=z.object({LeaderboardID:z.string(),CycleReward:ke(as).nullish(),Milestones:z.array(ke(ls)).nullish()}),pc=z.array(QR),HR=z.object({LeaderboardID:z.string(),Leaderboard:ke(_n).nullish(),Progress:ke(rs).nullish()}),hc=z.array(HR),$R=z.string(),dc=z.object({Rank:z.string().nullish(),Rewards:$.nullish(),SeasonTierRewards:wo.nullish()}).passthrough(),JR=z.object({RankRewards:z.array(dc).nullish()}).passthrough(),ZR=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),YR=z.object({Milestones:J.nullish(),RankRewards:J.nullish()}).passthrough(),XR=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:$R.nullish(),Schedule:Re.nullish(),ChainEvents:z.array(ZR).nullish(),Gate:ee.nullish(),TopUsersLimit:z.number().nullish(),MinScoreToEnterTop:z.number().nullish(),BracketSize:z.number().nullish(),LinkedSeasonChainID:z.string().nullish(),RankRewards:z.array(dc).nullish(),Milestones:z.record(z.string(),Ve).nullish(),Presets:YR.nullish(),MilestoneClaimMode:z.string().nullish(),MilestoneClaimGraceHours:z.number().nullish(),ScoreSources:z.array(ht).nullish()}).passthrough(),eC=z.object({Milestones:z.record(z.string(),Rn).nullish(),RankRewards:z.record(z.string(),JR).nullish()}).passthrough(),cs=z.object({Definitions:z.record(z.string(),XR).nullish(),Presets:eC.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 mc="Leaderboard",fc={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"]},ps=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fc,{schema:us,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(mc,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.leaderboard.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(mc,i.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",i.data)),i}async getLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getLeaderboard(t);return n.ok&&this.ctx.emitter.emit("leaderboard:loaded",n.data),n}async getMyProgress(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getMyProgress(t);return n.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),n.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",n.data)),n}async submitScore(e,t){if(!e)return b("client","LeaderboardID is required.");if(t<=0)return b("client","Score must be positive.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},i=await this.ctx.api.leaderboard.submitScore(n);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),s.NewScore,t,s.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",s);}return i}async submitScoreFromSource(e,t,n,i,s=1){if(!e)return b("client","LeaderboardID is required.");if(!t)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:n,Params:i,RollMultiplier:s},p=await this.ctx.api.leaderboard.submitScoreFromSource(r);if(p.ok){let m=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),m.NewScore,m.NewScore,m.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",m);}return p}async claimCycleReward(e){if(!e)return b("client","LeaderboardID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},n=await this.ctx.api.leaderboard.claimCycleReward(t);if(n.ok){let i=n.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",i);}return n}async claimMilestone(e,t,n){if(!e||!t)return b("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...n?{CycleKey:n}:{}},s=await this.ctx.api.leaderboard.claimMilestone(i);if(s.ok){let r=s.data;n||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 s}async getFriendsLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return n.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",n.data),n}async getLeaderboardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return n.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",n.data),n}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(b("client","leaderboardIDs is required.")):this.ctx.cache.read(fc,()=>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 n=await this.ctx.api.leaderboard.getProgressBatch(t);return n.ok&&this.applyProgressBatch(n.data),n}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},n=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(n.ok){for(let i of n.data)!i.Success||!i.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(i.Data.LeaderboardID)),i.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",n.data);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(n.ok){for(let i of n.data)!i.Success||!i.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(i.Data.LeaderboardID),i.Data.MilestoneID),i.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",n.data);}return n}async submitScoresBatch(e){if(!e||e.length===0)return b("client","scores is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},n=await this.ctx.api.leaderboard.submitScoresBatch(t);if(n.ok){for(let i of n.data)!i.Success||!i.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(i.Data.LeaderboardID),i.Data.NewScore,i.Data.NewScore,i.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",n.data);}return n}async claimAllRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},n=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(n.ok){for(let i of n.data){let s=this.cycleDocID(i.LeaderboardID);i.CycleReward?.Success&&i.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(s),i.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.CycleReward.Data.Resources,i.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let r of i.Milestones??[])!r.Success||!r.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(s,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",n.data);}return n}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 n=await this.ctx.api.leaderboard.getOverviewBatch(t);if(n.ok){for(let i of n.data)i.Progress?.Success&&i.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(i.LeaderboardID),i.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",n.data);}return n}};var Xo=z.object({}).passthrough().transform(o=>o),hs=z.object({SeasonChainID:z.string(),CycleIndex:z.number().nullish(),Season:z.lazy(()=>Cc).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:H.nullish(),UserState:Xo.nullish(),NextTier:z.lazy(()=>Rc).nullish()}).passthrough(),gc=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),AmountGranted:H.nullish(),NewStatusTokens:H.nullish(),OldTier:z.number().nullish(),NewTier:z.number(),TierUp:z.boolean().nullish()}),ea=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),TierNumber:z.number(),Resources:O.nullish(),Inventory:Q.nullish()}),yc=Tt(ea);var Rc=z.object({Tier:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredTokens:H.nullish(),TierReachedReward:$.nullish()}).passthrough(),Cc=z.object({SeasonID:z.string().nullish(),Order:z.number().nullish(),DurationSec:H.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(Rc).nullish(),LinkedCollectionID:z.string().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough();var tC=z.object({SeasonChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:Re.nullish(),Seasons:z.array(Cc).nullish(),GrantTokensAccessMode:z.string().nullish(),Gate:ee.nullish()}).passthrough(),ds=z.object({Chains:z.record(z.string(),tC).nullish()}).passthrough(),Qt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Sc="Season",xc={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}},ms=class{constructor(e){this.ctx=e;e.cache.bindLoginView(xc,{schema:hs,apply:(t,n)=>this.applyActiveSeason(n??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Sc,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.season.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Sc,i.data),this.ctx.emitter.emit("season:definitionsLoaded",i.data)),i}getActiveSeason(e,t){return e?this.ctx.cache.read(xc,()=>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 n=await this.ctx.api.season.getActiveSeason(t);return n.ok&&this.applyActiveSeason(e,n.data),n}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return b("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.SeasonChainID=e;let n=await this.ctx.api.season.getUserState(t);return n.ok&&(this.ctx.data.user.patchSeasonState(e,n.data),this.ctx.emitter.emit("season:userStateLoaded",n.data)),n}async grantStatusTokens(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","Amount must be positive.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${a()}`},i=await this.ctx.api.season.grantStatusTokens(n);return i.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,i.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",i.data)),i}async claimTierReward(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","TierNumber must be positive.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${a()}`},i=await this.ctx.api.season.claimTierReward(n);if(i.ok){let s=i.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",s);}return i}async claimTierRewardsBatch(e,t){if(!e)return b("client","SeasonChainID is required.");let n=(t??[]).filter(r=>r>0);if(n.length===0)return b("client","TierNumbers is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:n,RelatedEntityID:`season_tier_batch_${e}_${a()}`},s=await this.ctx.api.season.claimTierRewardsBatch(i);if(s.ok){let r=s.data;for(let p of r.Items??[]){let m=p.Data?.TierNumber;p.Success&&typeof m=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,m);}this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",r);}return s}};var bc="Premium",fs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(bc,e);if(t){let s={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",s),a$1(s)}let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.premium.getDefinitions(n);return i.ok&&i.data.Premium&&(this.ctx.data.config.patchSection(bc,i.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",i.data)),i}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 n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},i=await this.ctx.api.premium.activateTrial(n);return i.ok&&(i.data.Premium&&this.ctx.data.user.applyPremium(i.data.Premium),this.ctx.emitter.emit("premium:trialActivated",i.data)),i}async purchaseItemOrCurrency(e,t,n="Default",i=1,s){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:n,Count:i,CreditsConfirmationID:s,RelatedEntityID:`premium_purchase_${e}_${t}`},p=await this.ctx.api.premium.purchaseItemOrCurrency(r);if(p.ok&&!p.data.CreditsConfirmation){let m=p.data;m.Premium&&this.ctx.data.user.applyPremium(m.Premium),this.ctx.data.user.applyResourceOperation(m.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",m);}return p}async purchaseRealMoney(e,t,n,i,s,r,p,m){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!i||!s)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:n,ProductID:i,ReceiptData:s,PurchaseToken:r,PackageName:p,AppStoreEnvironment:m,RelatedEntityID:`premium_iap_${e}_${t}`},W=await this.ctx.api.premium.purchaseRealMoney(R);if(W.ok){let me=W.data;me.Premium&&this.ctx.data.user.applyPremium(me.Premium),this.ctx.data.user.applyResourceOperation(me.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",me);}return W}};var gs=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ItemInstanceID:z.string().nullish(),Level:z.number().nullish(),EquippedAt:u.nullish()}),Vn=z.object({CharacterID:z.string(),Level:z.number().nullish(),Experience:H.nullish(),Power:z.number().nullish(),StatLevels:z.record(z.string(),z.number()).nullish(),Equipment:z.record(z.string(),gs).nullish(),UpdatedAt:u.nullish()}).passthrough(),Dc=z.object({Characters:z.record(z.string(),Vn).nullish(),SelectedCharacterID:z.string().nullish()}),ta=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u,CharacterID:z.string(),StatID:z.string(),StatLevel:z.number(),Power:z.number().nullish(),Resources:O.nullish()}),na=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u,CharacterID:z.string(),NewLevel:z.number(),Power:z.number().nullish(),Resources:O.nullish()}),Ic=z.object({ServerTimeUtc:u,CharacterID:z.string(),Equipment:z.record(z.string(),gs).nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),Pc=z.object({ServerTimeUtc:u,CharacterID:z.string(),ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),nC=z.object({ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish()}),vc=z.object({ServerTimeUtc:u,Characters:z.record(z.string(),nC).nullish(),Inventory:Q.nullish()}),ia=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u,CharacterID:z.string(),Power:z.number().nullish(),Resources:O.nullish()}),Ac=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u,CharacterID:z.string(),SkinID:z.string(),Resources:O.nullish(),Inventory:Q.nullish(),Equipped:z.boolean().nullish(),EquipError:z.string().nullish(),Equipment:gs.nullish(),Power:z.number().nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish()}),Tc=z.object({ServerTimeUtc:u,CharacterID:z.string(),SkinID:z.string(),Equipped:gs.nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),zc=z.object({ServerTimeUtc:u,CharacterID:z.string(),Cleared:z.boolean().nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),iC=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:u.nullish(),GateOpen:z.boolean().nullish(),Purchasable:z.boolean().nullish(),PriceOptions:he.nullish()}),sC=z.object({CharacterID:z.string(),CharacterOpen:z.boolean().nullish(),DefaultSkinID:z.string().nullish(),WornSkinID:z.string().nullish(),Skins:z.array(iC).nullish()}),wc=z.object({ServerTimeUtc:u,Characters:z.record(z.string(),sC).nullish()}),kc=z.object({ServerTimeUtc:u,SelectedCharacterID:z.string().nullish()}),Mc=Tt(ia),Oc=Tt(na),Ec=Tt(ta),sa=z.object({RequiredStatID:z.string(),RequiredLevel:z.number()}).passthrough(),qc=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:he.nullish(),CostCurve:$e.nullish(),BaseStatValue:z.number().nullish(),ValueCurve:$e.nullish(),RankCurve:$e.nullish(),Requirements:z.array(sa).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),rC=z.object({SlotID:z.string(),MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(sa).nullish(),AllowedRarityIDs:z.array(z.string()).nullish(),AllowedItemTags:z.array(z.string()).nullish(),MinItemLevel:z.number().nullish(),MaxItemLevel:z.number().nullish()}).passthrough(),Uc=z.object({Slots:z.record(z.string(),rC).nullish()}).passthrough(),Lc=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(),oC=z.object({ClassID:z.string().nullish(),RarityID:z.string().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),aC=z.object({UnlockedByDefault:z.boolean().nullish(),PriceOptions:he.nullish()}).passthrough(),lC=z.object({Stats:J.nullish(),Levels:J.nullish(),Equipment:J.nullish()}).passthrough(),Bc=z.object({MaxRank:z.number().nullish(),FirstPaidRank:z.number().nullish(),PriceOptions:he.nullish(),CostCurve:$e.nullish()}).passthrough(),ra="@skin";function uC(o){return !!o&&o.startsWith("@")}var cC=z.object({CatalogID:z.string().nullish(),ItemID:z.string()}).passthrough(),pC=z.object({PriceOptions:he.nullish(),Schedule:Re.nullish(),Gate:ee.nullish()}).passthrough(),hC=z.object({MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(sa).nullish()}).passthrough(),dC=z.object({SkinID:z.string().nullish(),Identity:Lc.nullish(),Item:cC.nullish(),Sale:pC.nullish(),Requirements:hC.nullish()}).passthrough(),mC=z.object({DefaultSkinID:z.string().nullish(),Definitions:z.record(z.string(),dC).nullish()}).passthrough(),fC=z.object({CharacterID:z.string(),Identity:Lc.nullish(),Classification:oC.nullish(),Unlock:aC.nullish(),Presets:lC.nullish(),Equipment:Uc.nullish(),Stats:z.record(z.string(),qc).nullish(),RankLadder:Bc.nullish(),RankStatCurve:$e.nullish(),StatMaxLevelCurve:$e.nullish(),Skins:mC.nullish()}).passthrough(),gC=z.object({Stats:z.record(z.string(),qc).nullish()}).passthrough(),yC=z.object({RankLadder:Bc.nullish()}).passthrough(),RC=z.object({Equipment:Uc.nullish()}).passthrough(),CC=z.object({Stats:z.record(z.string(),gC).nullish(),Levels:z.record(z.string(),yC).nullish(),Equipment:z.record(z.string(),RC).nullish()}).passthrough(),ys=z.object({Definitions:z.record(z.string(),fC).nullish(),Presets:CC.nullish()}).passthrough(),He={GetCharacterDefinitions:"GetCharacterDefinitions",GetUserCharacters:"GetUserCharacters",UnlockCharacter:"UnlockCharacter",UpgradeStatLevel:"UpgradeStatLevel",UpgradeCharacterLevel:"UpgradeCharacterLevel",EquipItems:"EquipItems",UnequipItems:"UnequipItems",UnequipAllCharacters:"UnequipAllCharacters",UnlockCharactersBatch:"UnlockCharactersBatch",UpgradeCharacterLevelsBatch:"UpgradeCharacterLevelsBatch",UpgradeStatLevelsBatch:"UpgradeStatLevelsBatch",UnlockSkin:"UnlockSkin",EquipSkin:"EquipSkin",UnequipSkin:"UnequipSkin",GetCharacterSkins:"GetCharacterSkins",SelectCharacter:"SelectCharacter"},SC="SKIN_ALREADY_OWNED";var oa="Character",Rs=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(oa)?.Definitions,n=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([i,s])=>s?.Unlock?.UnlockedByDefault===true&&!n[s.CharacterID??i])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(oa,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.character.getCharacterDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(oa,i.data),this.ctx.emitter.emit("character:definitionsLoaded",i.data)),i}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let n=t.data.Characters??{};this.ctx.data.user.applyCharacter(n),this.ctx.data.user.applySelectedCharacter(t.data.SelectedCharacterID),this.ctx.emitter.emit("character:userCharactersLoaded",n);}return t}async unlockCharacter(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${a()}`},i=await this.ctx.api.character.unlockCharacter(n);if(i.ok&&!i.data.CreditsConfirmation){let s=i.data;this.ctx.data.user.patchCharacter(s.CharacterID,r=>{r.Level??=1,r.StatLevels??={},r.Equipment??={},s.Power!=null&&(r.Power=s.Power),r.UpdatedAt=s.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(s.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",s);}return i}async upgradeStatLevel(e,t,n){if(!e||!t)return b("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${a()}`,SelectedOptionID:n?.selectedOptionID,CreditsConfirmationID:n?.creditsConfirmationID,...n?.levels!=null?{Levels:n.levels}:{},...n?.targetLevel!=null?{TargetLevel:n.targetLevel}:{}},s=await this.ctx.api.character.upgradeStatLevel(i);if(s.ok&&!s.data.CreditsConfirmation){let r=s.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 s}async upgradeCharacterLevel(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${a()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},i=await this.ctx.api.character.upgradeCharacterLevel(n);if(i.ok&&!i.data.CreditsConfirmation){let s=i.data;this.ctx.data.user.patchCharacter(s.CharacterID,r=>{r.Level=s.NewLevel,s.Power!=null&&(r.Power=s.Power),r.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(r.StatLevels??={},r.Equipment??={});}),this.ctx.data.user.applyResourceOperation(s.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",s);}return i}async equipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},i=await this.ctx.api.character.equipItems(n);return i.ok&&(this.applyEquipChangesLocally(e,i.data),this.ctx.emitter.emit("character:itemsEquipped",i.data)),i}async unequipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},i=await this.ctx.api.character.unequipItems(n);if(i.ok){let s=i.data;this.applyUnequipChangesLocally(e,s),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:s.ClearedSlotIDs??[],power:s.Power??null});}return i}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return 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,n){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,AutoEquip:n?.autoEquip??false,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${a()}`},s=await this.ctx.api.character.unlockSkin(i);if(s.ok&&!s.data.CreditsConfirmation){let r=s.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 s}async equipSkin(e,t,n){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:n},s=await this.ctx.api.character.equipSkin(i);if(s.ok){let r=s.data;this.applyInventoryDelta(r.Inventory),this.applySkinLocally(r.CharacterID,r.Equipped??null,r.Power,r.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",r);}return s}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},n=await this.ctx.api.character.unequipSkin(t);if(n.ok){let i=n.data;i.Cleared&&(this.applyInventoryDelta(i.Inventory),this.applySkinLocally(i.CharacterID,null,i.Power,i.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",i);}return n}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):c}async selectCharacter(e){let t=this.ctx.authedRequest();if(!t)return c;let n=e?.trim();if(!n)return b("client","CharacterID is required.");t.CharacterID=n;let i=await this.ctx.api.character.selectCharacter(t);return i.ok&&(this.ctx.data.user.applySelectedCharacter(i.data.SelectedCharacterID),this.ctx.emitter.emit("character:selected",i.data)),i}applySkinLocally(e,t,n,i){let s=this.ctx.data.user;s.patchCharacterEquipment(e,ra,t??null),s.patchCharacter(e,r=>{n!=null&&(r.Power=n),r.UpdatedAt=i;});}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},n=await this.ctx.api.character.unlockCharactersBatch(t);return n.ok&&(this.applyBatchResults(n.data,i=>{this.ctx.data.user.patchCharacter(i.CharacterID,s=>{s.Level??=1,s.StatLevels??={},s.Equipment??={},i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=i.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",n.data)),n}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},n=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return n.ok&&(this.applyBatchResults(n.data,i=>{this.ctx.data.user.patchCharacter(i.CharacterID,s=>{s.Level=i.NewLevel,i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=i.ServerTimeUtc,i.NewLevel===1&&(s.StatLevels??={},s.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",n.data)),n}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},n=await this.ctx.api.character.upgradeStatLevelsBatch(t);return n.ok&&(this.applyBatchResults(n.data,i=>{this.ctx.data.user.patchCharacter(i.CharacterID,s=>{s.StatLevels??={},s.StatLevels[i.StatID]=i.StatLevel,i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=i.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",n.data)),n}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let n of e.Items??[])!n.Success||!n.Data||t(n.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[i,s]of Object.entries(t.Equipment??{}))n.patchCharacterEquipment(e,i,s);n.patchCharacter(e,i=>{t.Power!=null&&(i.Power=t.Power),i.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let n=t.ClearedSlotIDs??[];if(n.length===0&&t.Power==null)return;let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let s of n)i.patchCharacterEquipment(e,s,null);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[n,i]of Object.entries(e.Characters??{})){for(let s of i.ClearedSlotIDs??[])t.patchCharacterEquipment(n,s,null);t.patchCharacter(n,s=>{i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=e.ServerTimeUtc;});}}};var Gc="Match",Cs=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,n,i,s,r){let p=this.ctx.auth.context;if(!p)return c;let m={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:n,BattleStrategy:i,TargetUserID:s,SelectedOptionID:r,RelatedEntityID:`pvp_create_${p.userID}_${a()}`},R=await this.ctx.api.match.createMatch(m);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 n={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},i=await this.ctx.api.match.updateMatch(n);return i.ok&&this.ctx.emitter.emit("match:updated",i.data),i}async cancelMatch(e){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},n=await this.ctx.api.match.cancelMatch(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",n.data)),n}async instantBattle(e,t,n,i){let s=this.ctx.auth.context;if(!s)return c;let r={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:n,BattleStrategy:i,RelatedEntityID:`pvp_battle_${e}_${a()}`},p=await this.ctx.api.match.instantBattle(r);if(p.ok){let m=p.data,R=this.ctx.data.config.itemDefinitions;if(m.Resources)this.ctx.data.user.applyResourceOperation(m.Resources,R);else if(m.ResourcesDual){let W=m.ResourcesDual;W.FromUserID===s.userID&&W.FromResult?this.ctx.data.user.applyResourceOperation(W.FromResult,R):W.ToUserID===s.userID&&W.ToResult&&this.ctx.data.user.applyResourceOperation(W.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",m);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},n=await this.ctx.api.match.saveStrategy(t);return n.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),n}async getMyMatches(e=0,t=20,n){let i=this.ctx.authedRequest();if(!i)return c;i.Page=e,i.PageSize=t,i.Statuses=n;let s=await this.ctx.api.match.getMyMatches(i);return s.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",s.data),s}async getAvailableMatches(e=0,t=20,n=false){let i=this.ctx.authedRequest();if(!i)return c;i.Page=e,i.PageSize=t,i.OnlyPublic=n;let s=await this.ctx.api.match.getAvailableMatches(i);return s.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",s.data),s}async getDefinitions(e){let t=this.ctx.cache.configSection(Gc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.match.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Gc,i.data),this.ctx.emitter.emit("match:definitionsLoaded",i.data)),i}};var xC="Challenge",Ss=class{constructor(e){this.ctx=e;}ctx;lastState=null;get definitions(){return this.ctx.cache.configSection(xC)??null}get state(){return this.lastState}chainDefinition(e){return this.definitions?.Chains?.[e]??null}phaseDefinition(e,t){return t?this.chainDefinition(e)?.Challenges?.find(n=>n?.ChallengeID===t)??null:null}chainView(e){return this.lastState?.Chains?.find(t=>t.ChainID===e)??null}newAttemptID(){return a().replace(/-/g,"")}async getState(e){let t=this.ctx.authedRequest();if(!t)return c;e&&(t.ChainID=e);let n=await this.ctx.api.challenge.getState(t);return n.ok&&this.applyState(n.data,e),n}async refreshOpponents(e){if(!e)return b("client","ChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.ChainID=e;let n=await this.ctx.api.challenge.refreshOpponents(t);return n.ok&&this.applyState(n.data,e),n}async attempt(e,t,n,i,s){if(!e)return b("client","ChainID is required.");if(!n)return b("client","AttemptID is required.");let r=this.ctx.authedRequest();if(!r)return c;r.ChainID=e,r.AttemptID=n,"tierID"in t?r.TierID=t.tierID:r.RevengeID=t.revengeID,i&&(r.CharacterID=i),s&&(r.BattleStrategy=s);let p=await this.ctx.api.challenge.attempt(r);if(p.ok){let m=p.data;m.IsReplay||this.ctx.data.user.applyResourcesWithDelta(m.Rewards,m.Inventory,this.ctx.data.config.itemDefinitions),this.patchAfterAttempt(e,m,"revengeID"in t?t.revengeID:void 0),this.ctx.emitter.emit("challenge:attemptCompleted",m);}return p}async claimMilestone(e,t,n){if(!e||!t)return b("client","ChainID and MilestoneID are required.");let i=this.ctx.authedRequest();if(!i)return c;i.ChainID=e,i.MilestoneID=t,n&&(i.InstanceKey=n);let s=await this.ctx.api.challenge.claimMilestone(i);if(s.ok){let r=s.data;this.ctx.data.user.applyResourcesWithDelta(r.Rewards,r.Inventory,this.ctx.data.config.itemDefinitions),this.markClaimed(e,r.InstanceKey??n,t),this.ctx.emitter.emit("challenge:milestoneClaimed",r);}return s}async claimReachedMilestones(e){if(!this.ctx.auth.context)return c;let t=[],n=(this.lastState?.Chains??[]).filter(i=>!e||i.ChainID===e);for(let i of n){if(!i.ChainID)continue;let s=[i.Active,...i.Ended??[]].filter(r=>!!r&&!!r.CanClaim);for(let r of s)for(let p of this.reachedUnclaimed(i.ChainID,r)){let m=await this.claimMilestone(i.ChainID,p,r.InstanceKey??void 0);m.ok&&t.push(m.data);}}return a$1(t)}reachedUnclaimed(e,t){let n=this.phaseDefinition(e,t.ChallengeID),i=t.PointsEarned??0,s=new Set(t.ClaimedMilestoneIDs??[]);return Object.entries(n?.Milestones??{}).filter(([r,p])=>!s.has(r)&&(p?.RequiredProgress??1/0)<=i).sort((r,p)=>(r[1]?.RequiredProgress??0)-(p[1]?.RequiredProgress??0)).map(([r])=>r)}applyState(e,t){if((e.Rewards||e.Inventory)&&this.ctx.data.user.applyResourcesWithDelta(e.Rewards,e.Inventory,this.ctx.data.config.itemDefinitions),t&&this.lastState){let n=(this.lastState.Chains??[]).filter(i=>i.ChainID!==t);this.lastState={...e,Chains:[...n,...e.Chains??[]]};}else this.lastState=e;this.ctx.emitter.emit("challenge:stateLoaded",e);}patchAfterAttempt(e,t,n){let i=this.chainView(e);if(!i)return;t.Tickets!=null&&(i.Tickets=t.Tickets);let s=i.Active;if(!s||s.InstanceKey!==t.InstanceKey)return;t.PointsEarned!=null&&(s.PointsEarned=t.PointsEarned),t.IsReplay||(s.AttemptsToday=(s.AttemptsToday??0)+1);let r=t.Attempt;if(!(!r?.Win||!s.Arena))if(r.IsRevenge)s.Arena.Revenges=(s.Arena.Revenges??[]).filter(p=>p.RevengeID!==n);else for(let p of s.Arena.Opponents??[])p.TierID===r.TierID&&p.OpponentID===r.OpponentID&&(p.Defeated=true);}markClaimed(e,t,n){let i=this.chainView(e);if(i)for(let s of [i.Active,...i.Ended??[]])s&&(t&&s.InstanceKey!==t||!t&&s!==i.Active||(s.ClaimedMilestoneIDs=[...new Set([...s.ClaimedMilestoneIDs??[],n])]));}};var Nc="Craft",xs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Nc,e);if(t){let s={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),a$1(s)}let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.craft.getDefinitions(n);return i.ok&&i.data.CraftDefinitions&&(this.ctx.data.config.patchSection(Nc,i.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",i.data.CraftDefinitions)),i}async craft(e,t,n=1,i,s,r){if(!e)return b("client","CraftID is required.");let p=this.ctx.auth.context;if(!p)return c;let m={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:n,SelectedOptionID:i,InputInstanceIDs:s,CreditsConfirmationID:r,RelatedEntityID:`craft_${e}_${p.userID}_${a()}`},R=await this.ctx.api.craft.craft(m);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 Ht=z.lazy(()=>z.union([z.string(),z.number(),z.boolean(),z.null(),z.array(Ht),z.record(z.string(),Ht)]));var $t={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},_c=z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),on={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function jn(o){return o!==on.Pending&&o!==on.Running}var bC={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 DC(o){return o?/\b(AI_[A-Z_]+)\s*:/.exec(o)?.[1]??null:null}var IC=z.object({Url:z.string().nullish(),ContentType:z.string().nullish(),Variant:z.string().nullish()}),PC=z.object({Code:z.string().nullish(),Message:z.string().nullish()}),bs=z.object({CreditsConfirmation:ge.nullish(),GenerationID:z.string(),FeatureKey:z.string().nullish(),Modality:_c.nullish(),Status:z.string(),Progress:z.number().nullish(),OutputText:z.string().nullish(),OutputJson:z.record(z.string(),Ht).nullish(),Assets:z.array(IC).nullish(),Error:PC.nullish(),Charge:O.nullish(),PlayerRefunded:z.boolean().nullish(),Reused:z.boolean().nullish(),Reward:O.nullish(),Context:z.record(z.string(),Ht).nullish(),PaymentSettled:z.boolean().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish()}),Vc=z.object({Data:z.array(bs).nullish(),Skip:z.number().nullish(),Limit:z.number().nullish()}),vC=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(),Dt=z.record(z.string(),z.string()),AC=z.object({Key:z.string().nullish(),Role:z.string().nullish(),Required:z.boolean().nullish(),Label:Dt.nullish()}).passthrough(),TC=z.object({Name:z.string().nullish(),Type:z.string().nullish(),Required:z.boolean().nullish(),MaxLength:z.number().nullish(),Default:z.string().nullish(),Multiline:z.boolean().nullish(),Label:Dt.nullish(),Placeholder:Dt.nullish(),Choices:z.array(z.object({Value:z.string().nullish(),Label:Dt.nullish()}).passthrough()).nullish()}).passthrough(),jc=z.object({Key:z.string(),Kind:z.string().nullish(),Name:Dt.nullish(),Hint:Dt.nullish(),Unit:Dt.nullish(),Choices:z.array(z.object({Value:z.string(),Name:Dt.nullish(),Group:z.string().nullish()}).passthrough()).nullish(),Groups:z.array(z.object({Key:z.string(),Name:Dt.nullish()}).passthrough()).nullish(),Default:z.string().nullish(),Min:z.number().nullish(),Max:z.number().nullish(),Step:z.number().nullish()}).passthrough(),Fc=z.object({PriceOptions:he.nullish()}).passthrough(),zC=z.object({Id:z.string().nullish(),Kind:z.string().nullish(),Action:z.string().nullish(),IsTrend:z.boolean().nullish(),Category:z.string().nullish(),Order:z.number().nullish(),Name:Dt.nullish(),Description:Dt.nullish(),Preview:z.object({Url:z.string().nullish(),PosterUrl:z.string().nullish(),Type:z.string().nullish()}).passthrough().nullish(),Inputs:z.array(AC).nullish(),Variables:z.array(TC).nullish(),Settings:z.array(jc).nullish()}).passthrough(),wC=z.object({Modality:_c.nullish(),Async:z.boolean().nullish(),Limits:Ie.nullish(),PriceOptions:he.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:$.nullish(),PromptVariables:z.array(vC).nullish(),AllowFreePrompt:z.boolean().nullish(),PlatformTemplateId:z.string().nullish(),PlatformTemplate:zC.nullish(),Settings:z.array(jc).nullish(),FreePerDay:z.number().nullish(),FreeLeftToday:z.number().nullish()}).passthrough(),Wc=z.object({Enabled:z.boolean().nullish(),Features:z.record(z.string(),wC).nullish()}).passthrough(),je={GetDefinitions:"GetDefinitions",GenerateText:"GenerateText",GetText:"GetText",GenerateImage:"GenerateImage",EditImage:"EditImage",GenerateVideo:"GenerateVideo",GetVideo:"GetVideo",GenerateAudio:"GenerateAudio",GenerateMusic:"GenerateMusic",GenerateThreeD:"GenerateThreeD",GetThreeD:"GetThreeD",ListGenerations:"ListGenerations",GetGeneration:"GetGeneration",GetImage:"GetImage",GetAudio:"GetAudio",GetMusic:"GetMusic",GenerateFromTemplate:"GenerateFromTemplate",EstimateTemplatePrice:"EstimateTemplatePrice"};var Kc="AI",kC=/^[A-Za-z0-9_-]{1,128}$/,MC=2e3,OC=5e3,EC=30*6e4;function qC(o,e){return new Promise(t=>{if(e?.aborted){t();return}let n=()=>{clearTimeout(i),e?.removeEventListener("abort",n),t();},i=setTimeout(n,o);e?.addEventListener("abort",n,{once:true});})}var Ds=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(Kc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.ai.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Kc,i.data),this.ctx.emitter.emit("ai:definitionsLoaded",i.data)),i}generateText(e,t,n){return this.generate(e,{Text:t},n,i=>this.ctx.api.ai.generateText(i))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,n){return this.generate(e,{Image:t},n,i=>this.ctx.api.ai.generateImage(i))}editImage(e,t,n){return this.generate(e,{ImageEdit:t},n,i=>this.ctx.api.ai.editImage(i))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,n){return this.generate(e,{Video:t},n,i=>this.ctx.api.ai.generateVideo(i))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,n){return this.generate(e,{Audio:t},n,i=>this.ctx.api.ai.generateAudio(i))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,n){return this.generate(e,{Music:t},n,i=>this.ctx.api.ai.generateMusic(i))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,n){return this.generate(e,{TemplateInputs:t},n,i=>this.ctx.api.ai.generateFromTemplate(i))}async estimateTemplatePrice(e,t,n){return e?this.ctx.auth.context?this.ctx.api.ai.estimateTemplatePrice({...this.ctx.buildAuthedBaseRequest(),FeatureKey:e,Params:t,Variables:n}):c:b("client","FeatureKey is required.")}generateThreeD(e,t,n){return this.generate(e,{ThreeD:t},n,i=>this.ctx.api.ai.generateThreeD(i))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):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 jn(e)}async waitForGeneration(e,t={}){let n;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;n=p.data;}else {if(!e?.GenerationID)return b("client","GenerationID is required.");n=e;}let i=Date.now()+(t.timeoutMs??EC),s=Math.max(1,t.intervalMs??MC),r=Math.max(s,t.maxIntervalMs??OC);for(;!jn(n.Status);){if(t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");if(Date.now()+s>i)return b("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await qC(s,t.signal),t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(n);if(s=Math.min(r,Math.round(s*1.5)),!p.ok){if(p.reason==="connection")continue;return p}n=p.data,jn(n.Status)||t.onUpdate?.(n);}return a$1(n)}pollFor(e){switch(e.Modality){case $t.Text:return this.getText(e.GenerationID);case $t.Image:return this.getImage(e.GenerationID);case $t.Audio:return this.getAudio(e.GenerationID);case $t.Music:return this.getMusic(e.GenerationID);case $t.Video:return this.getVideo(e.GenerationID);case $t.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,n,i){if(!e)return b("client","FeatureKey is required.");let s=n?.relatedEntityID;if(s!==void 0&&!kC.test(s))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 r={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,Variables:n?.variables,Params:n?.params,Context:n?.context,RelatedEntityID:s??a()},p=await i(r);return p.ok&&!p.data.CreditsConfirmation&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return b("client","GenerationID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.GenerationID=e;let i=await t(n);return i.ok&&(await this.reconcileCharge(i.data,false),this.emitView(i.data)),i}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===on.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===on.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===on.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var aa="Collection",Is=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let n=e.cache.configSection(aa),i=Object.keys(n?.Collections??{});if(i.length===0||t)return false;let s=e.cache.configSection("Season");return Object.values(s?.Chains??{}).some(p=>(p?.Seasons??[]).some(m=>!!m?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==i[0]},refresh:async()=>{let n=await this.getUserState();return n.ok&&(t=true),n}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(aa,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.collection.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(aa,i.data),this.ctx.emitter.emit("collection:definitionsLoaded",i.data)),i}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,n=1,i){let s=this.ctx.auth.context;if(!s)return c;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:n,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${s.userID}_${a()}`},p=await this.ctx.api.collection.openPack(r);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,n=1){let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:n,RelatedEntityID:`open_chest_${e}_${t}_${i.userID}_${a()}`},r=await this.ctx.api.collection.openCollectionChest(s);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",r.data)),r}async useCollectibleJoker(e,t){let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${n.userID}_${a()}`},s=await this.ctx.api.collection.useCollectibleJoker(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",s.data)),s}async claimSetReward(e,t){let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${n.userID}_${a()}`},s=await this.ctx.api.collection.claimSetReward(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",s.data)),s}async claimSetRewardsBatch(e){if(!e||e.length===0)return b("client","sets is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},n=await this.ctx.api.collection.claimSetRewardsBatch(t);if(n.ok){let i=false;for(let s of n.data)!i&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",n.data);}return n}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return c;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${a()}`},i=await this.ctx.api.collection.claimGrandPrize(n);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",i.data)),i}async sendTradeOffer(e,t,n,i,s,r=false){let p=this.ctx.auth.context;if(!p)return c;let m={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:n,ReceiverUserID:i,RequestedCollectibleID:s,RequestedCollectibleIsSpecial:r,RelatedEntityID:`trade_send_${p.userID}_${i}_${a()}`},R=await this.ctx.api.collection.sendTradeOffer(m);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}_${a()}`},n=await this.ctx.api.collection.cancelTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",n.data)),n}async acceptTradeOffer(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${a()}`},n=await this.ctx.api.collection.acceptTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",n.data)),n}async declineTradeOffer(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${a()}`},n=await this.ctx.api.collection.declineTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",n.data)),n}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return c;t.CollectionID=e;let n=await this.ctx.api.collection.getMyTradeOffers(t);return n.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",n.data),n}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return c;t.CollectionID=e;let n=await this.ctx.api.collection.getIncomingTradeOffers(t);return n.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",n.data),n}};var UC=z.object({}).passthrough().transform(o=>o),LC={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},BC={Active:"Active",Left:"Left",Replaced:"Replaced"},GC=z.object({ObjectIndex:z.number().nullish(),ObjectCompletionRewardClaimed:z.boolean().nullish()}).passthrough(),NC=z.object({UserID:z.string().nullish(),PublicData:Be.nullish(),BuildObjectsProgress:GC.nullish(),IsBot:z.boolean().nullish(),SpinsCount:z.number().nullish(),TokensSpent:z.number().nullish(),MemberStatus:z.string().nullish(),GrandPrizeClaimed:z.boolean().nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),_C=z.object({Index:z.number().nullish(),OwnerUserID:z.string().nullish(),CurrentProgress:z.number().nullish(),MaxProgress:z.number().nullish(),IsCompleted:z.boolean().nullish()}).passthrough(),VC=z.object({Objects:z.array(_C).nullish()}).passthrough(),Qc=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(NC).nullish(),BuildObjectsState:VC.nullish(),Status:z.string().nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:z.number().nullish()}).passthrough(),Hc=z.object({CoopChainID:z.string(),CycleIndex:z.number().nullish(),EventOrder:z.number().nullish(),EventDef:z.lazy(()=>$c).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:z.number().nullish()}).passthrough(),jC=z.string(),la=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(),FC=z.object({Index:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxProgress:z.number().nullish(),CompletionReward:$.nullish()}).passthrough(),WC=z.object({Objects:z.array(FC).nullish(),PriceOptions:he.nullish(),SpinnerTable:z.array(la).nullish(),MaxSpinsPerCall:z.number().nullish()}).passthrough(),$c=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:jC.nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),BuildObjects:WC.nullish(),GrandPrize:$.nullish()}).passthrough(),KC=z.object({CoopChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:Re.nullish(),Events:z.array($c).nullish(),Gate:ee.nullish()}).passthrough(),Ps=z.object({ServerTimeUtc:u.nullish(),UserState:UC.nullish(),ActiveGroup:Qc.nullish()}),ua=z.object({ServerTimeUtc:u.nullish(),Group:Qc.nullish(),SecondsRemaining:H.nullish()}),Jc=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u.nullish(),GroupID:z.string().nullish(),Resources:O.nullish(),ObjectIndex:z.number().nullish(),Sector:la.nullish(),RequestedSpins:z.number().nullish(),SpinsUsed:z.number().nullish(),Sectors:z.array(la).nullish(),ProgressDelta:z.number().nullish(),NewProgress:H.nullish(),MaxProgress:H.nullish(),ObjectCompleted:z.boolean().nullish(),AllObjectsCompleted:z.boolean().nullish()}),ca=z.object({ServerTimeUtc:u.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),Zc=z.object({ServerTimeUtc:u.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),vs=z.object({Chains:z.record(z.string(),KC).nullish()}).passthrough(),It={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Yc="CoopEvent",Xc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},As=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Xc,{schema:Ps,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Yc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.coopEvent.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Yc,i.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",i.data)),i}async getActiveEvent(e){if(!e)return b("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.CoopChainID=e;let n=await this.ctx.api.coopEvent.getActiveEvent(t);return n.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",n.data),n}getUserState(e){return this.ctx.cache.read(Xc,()=>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 n=await this.ctx.api.coopEvent.getGroupState(t);return n.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",n.data),n}async joinOrCreateGroup(e){if(!e)return b("client","CoopChainID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},n=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(n.ok){let i=n.data.Group;i&&this.ctx.data.user.patchCoopEventActiveGroup(i.GroupID??null,i.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",n.data);}return n}async spin(e,t,n=1,i,s){if(!e||!t)return b("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:n,SelectedOptionID:i,CreditsConfirmationID:s,RelatedEntityID:a()},p=await this.ctx.api.coopEvent.spin(r);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(p.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",p.data)),p}async claimObjectReward(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.claimObjectReward(t);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",n.data)),n}async claimGrandPrize(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.claimGrandPrize(t);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",n.data)),n}async leaveGroup(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.leaveGroup(t);return n.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",n.data)),n}};var QC={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},HC={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},$C=z.object({NodeID:z.string().nullish(),Status:z.string().nullish(),ExecutionCount:z.number().nullish(),UnlockedAtUtc:u.nullish(),CompletedAtUtc:u.nullish(),LastExecutedAtUtc:u.nullish(),NextAvailableAtUtc:u.nullish(),LastExecutionRefID:z.string().nullish()}).passthrough(),JC=z.object({TrackID:z.string().nullish(),CurrentValue:z.number().nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),ep=z.object({OfferID:z.string().nullish(),InstanceKey:z.string().nullish(),SourceOfferVersion:z.number().nullish(),Status:z.string().nullish(),ActivatedAtUtc:u.nullish(),ExhaustedAtUtc:u.nullish(),ExpiredAtUtc:u.nullish(),DismissedAtUtc:u.nullish(),ShowCount:z.number().nullish(),LastShownAtUtc:u.nullish(),Nodes:z.record(z.string(),$C).nullish(),Tracks:z.record(z.string(),JC).nullish(),SelectedChoiceNodeID:z.string().nullish()}).passthrough(),ZC=z.object({SlotID:z.string().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),ActiveOfferID:z.string().nullish(),ActiveOfferStartedAtUtc:u.nullish(),ActiveOfferExpiresAtUtc:u.nullish(),ActiveOffer:ep.nullish(),NextCycleStartsAtUtc:u.nullish(),LastUpdatedUtc:u.nullish(),DismissSkipAvailableAtUtc:u.nullish(),LastDismissedAtUtc:u.nullish(),ActiveScheduleInstanceKey:z.string().nullish()}).passthrough(),YC=z.object({TotalExecutions:z.number().nullish(),DailyExecutions:z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),XC=z.object({TotalActivations:z.number().nullish(),TotalExhausted:z.number().nullish(),TotalExpired:z.number().nullish(),TotalDismissed:z.number().nullish(),TotalShows:z.number().nullish(),LastShownAtUtc:u.nullish(),LastActivatedAtUtc:u.nullish(),LastExhaustedAtUtc:u.nullish(),NodeCounts:z.record(z.string(),YC).nullish()}).passthrough(),eS=z.object({Slots:z.record(z.string(),ZC).nullish(),OfferHistory:z.record(z.string(),XC).nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),tS={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},nS={Eq:"Eq",Gte:"Gte",Lte:"Lte"},iS=z.object({Order:z.number().nullish(),OfferID:z.string().nullish(),DurationSec:z.number().nullish(),DelayBeforeActivationSec:z.number().nullish()}).passthrough(),Ts=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(),tp=z.object({Schedule:Re.nullish(),Gate:ee.nullish()}).passthrough(),np=z.object({AllowDismissSkip:z.boolean().nullish(),DismissSkipDelaySec:z.number().nullish()}).passthrough(),sS=z.object({Identity:J.nullish(),Availability:J.nullish(),Behaviour:J.nullish()}).passthrough(),rS=z.object({SlotID:z.string().nullish(),Enabled:z.boolean().nullish(),Identity:Ts.nullish(),Availability:tp.nullish(),Behaviour:np.nullish(),Queue:z.array(iS).nullish(),Presets:sS.nullish()}).passthrough(),oS=z.object({ViewsRequiredToComplete:z.number().nullish(),MaxViewsPerActivation:z.number().nullish(),GrantRewardsPerView:z.boolean().nullish()}).passthrough(),aS=z.object({RewardedVideo:oS.nullish()}).passthrough(),lS=z.object({TrackID:z.string().nullish(),Operator:z.string().nullish(),Value:z.number().nullish()}).passthrough(),uS=z.object({Identity:J.nullish(),Graph:J.nullish(),Milestones:J.nullish()}).passthrough(),cS=z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish()}).passthrough(),pS=z.object({TrackID:z.string().nullish(),Amount:z.number().nullish(),RespectBounds:z.boolean().nullish()}).passthrough(),hS=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(),dS=z.object({RequiredCompletedNodeIDs:z.array(z.string()).nullish(),RequiredAnyCompletedNodeIDs:z.array(z.string()).nullish(),RequiredTracks:z.array(lS).nullish(),VisibleWhileLocked:z.boolean().nullish()}).passthrough(),ip=z.object({Options:he.nullish()}).passthrough(),sp=z.object({Grants:$.nullish(),TrackChanges:z.array(pS).nullish(),MilestonePoints:z.number().nullish()}).passthrough(),mS=z.object({NodeID:z.string().nullish(),Type:z.string().nullish(),Identity:Ts.nullish(),Pricing:ip.nullish(),Reward:sp.nullish(),Action:aS.nullish(),UnlockRules:dS.nullish(),NextNodeIDs:z.array(z.string()).nullish(),ChoiceGroupID:z.string().nullish(),Limits:Ie.nullish(),HideWhenCompleted:z.boolean().nullish(),ExhaustOfferOnComplete:z.boolean().nullish(),Presets:cS.nullish()}).passthrough(),rp=z.object({RootNodeIDs:z.array(z.string()).nullish(),Nodes:z.array(mS).nullish(),Tracks:z.array(hS).nullish(),ExhaustedWhenAllTerminalNodesCompleted:z.boolean().nullish()}).passthrough(),op=z.object({Milestones:z.record(z.string(),Ve).nullish(),ClaimMode:z.string().nullish(),Token:At.nullish()}).passthrough(),ap=z.object({OfferID:z.string().nullish(),Version:z.number().nullish(),Enabled:z.boolean().nullish(),Identity:Ts.nullish(),Graph:rp.nullish(),Milestones:op.nullish(),Presets:uS.nullish()}).passthrough(),fS=z.object({Identity:z.record(z.string(),Ts).nullish(),Availability:z.record(z.string(),tp).nullish(),Behaviour:z.record(z.string(),np).nullish(),Graph:z.record(z.string(),rp).nullish(),Milestones:z.record(z.string(),op).nullish(),Pricing:z.record(z.string(),ip).nullish(),Reward:z.record(z.string(),sp).nullish()}).passthrough(),pa=z.object({Slots:z.record(z.string(),rS).nullish(),Offers:z.record(z.string(),ap).nullish(),Presets:fS.nullish()}).passthrough(),lp=z.object({DealOfferDefinitions:pa.nullish()}),up=z.object({DealOffers:eS.nullish()}),gS=z.object({EntityID:z.string().nullish(),TotalEarned:z.number().nullish(),ClaimedIDs:z.array(z.string()).nullish(),ReachedUnclaimedIDs:z.array(z.string()).nullish()}).passthrough(),yS=z.object({SlotID:z.string().nullish(),SortOrder:z.number().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),OfferDef:ap.nullish(),ActivationState:ep.nullish(),IsNewActivation:z.boolean().nullish(),ComputedExpiresAtUtc:u.nullish(),Cost:qt.nullish(),Milestone:gS.nullish(),ScheduleInstanceKey:z.string().nullish()}).passthrough(),zs=z.object({Slots:z.array(yS).nullish()}),cp=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u.nullish(),SlotID:z.string().nullish(),NodeID:z.string().nullish(),NodeCompleted:z.boolean().nullish(),OfferExhausted:z.boolean().nullish(),Idempotent:z.boolean().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),pp=z.object({ServerTimeUtc:u.nullish(),SlotID:z.string().nullish(),Resources:O.nullish()}),hp=z.object({ServerTimeUtc:u.nullish(),SlotID:z.string().nullish(),Resources:O.nullish()}),dp=z.object({ServerTimeUtc:u.nullish(),SlotID:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),mp=z.object({ServerTimeUtc:u.nullish(),SlotID:z.string().nullish(),ClaimedIDs:z.array(z.string()).nullish(),Rejected:z.record(z.string(),z.string()).nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),wt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var RS="DealOffer",fp={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fp,{schema:zs,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(RS,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(fp,()=>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}_${a()}`},n=await this.ctx.api.dealOffer.dismissDeal(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",n.data)),n}async executeNode(e,t,n,i){if(!e||!t)return b("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return c;let s=n&&n.trim().length>0?n.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:s??`deal_exec_${e}_${t}_${a()}`},p=await this.ctx.api.dealOffer.executeNode(r);return p.ok&&!p.data.CreditsConfirmation&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${a()}`},n=await this.ctx.api.dealOffer.recordShow(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",n.data)),n}async claimMilestone(e,t){if(!e||!t)return b("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${a()}`},i=await this.ctx.api.dealOffer.claimMilestone(n);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",i.data)),i}async claimMilestonesBatch(e,t){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let n=[...new Set(t.map(r=>r.trim()).filter(r=>r.length>0))],i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:n,RelatedEntityID:`deal_milestone_batch_${e}_${a()}`},s=await this.ctx.api.dealOffer.claimMilestonesBatch(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",s.data)),s}};var gp="Referral",ks=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(gp,e);if(t){let s={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",s),a$1(s)}let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.referral.getDefinitions(n);return i.ok&&i.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(gp,i.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",i.data)),i}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=sn.parseReferralCode(e)?.toUpperCase();if(!t)return b("client","ReferralCode is required.");let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${n.userID}`},s=await this.ctx.api.referral.activateReferralCode(i);if(s.ok){let r=s.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 s}async claimInviteReward(e){let t=e.trim();if(!t)return b("client","InviteRewardID is required.");let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${n.userID}`},s=await this.ctx.api.referral.claimInviteReward(i);if(s.ok){let r=s.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 s}async claimInviteRewardsBatch(e){let t=(e??[]).map(r=>r?.trim()).filter(Boolean);if(t.length===0)return b("client","InviteRewardIDs is required.");let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${n.userID}`},s=await this.ctx.api.referral.claimInviteRewardsBatch(i);if(s.ok){let r=s.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 s}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 yp=z.object({ServerTimeUtc:u,SourceType:g,SourceID:z.string(),TargetType:g,TargetID:z.string(),SourceSpent:H,FeeAmount:H,RateApplied:ne,TargetCredited:H}),Rp=z.object({ServerTimeUtc:u,SourceType:g,SourceID:z.string(),TargetType:g,TargetID:z.string(),SourceSpent:ne,FeeAmount:ne,RateApplied:ne,TargetCredited:ne}),Cp=z.object({ServerTimeUtc:u,SpendID:z.string(),Resources:O.nullish()}),Fn={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},CS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},Sp=z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),SS={Automatic:"Automatic",Manual:"Manual"},xS=z.enum(["Automatic","Manual"]).catch("Automatic"),bS=z.object({ValueInUSD:ne.nullish(),ValueInUSDUpdatedAt:u.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(),IS=z.object({IsTradable:z.boolean().nullish(),IsPurchasable:z.boolean().nullish(),IsRefundable:z.boolean().nullish()}).passthrough(),PS=z.object({TargetCurrencyType:g.nullish(),TargetCurrencyID:z.string(),Rate:ne.nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish(),DailyLimit:z.number().nullish()}).passthrough(),xp=z.object({Enabled:z.boolean().nullish(),RateMode:xS.nullish(),Fee:z.number().nullish(),Targets:z.array(PS).nullish()}).passthrough(),bp=z.object({CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough(),vS=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Economy:bS.nullish(),Recharge:DS.nullish(),Conversion:xp.nullish(),Permissions:IS.nullish(),Audit:bp.nullish(),Status:Sp.nullish()}).passthrough(),AS=z.object({NetworkID:z.string(),ContractAddress:z.string().nullish(),Decimals:z.number().nullish(),MinWithdraw:ne.nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),TS=z.object({DailyWithdrawUsd:ne.nullish(),MonthlyWithdrawUsd:ne.nullish(),KycRequiredAboveUsd:ne.nullish()}).passthrough(),zS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),SpendableInGame:z.boolean().nullish(),ConvertibleToVirtual:z.boolean().nullish()}).passthrough(),wS=z.object({Mode:z.string().nullish(),FundingNetworkID:z.string().nullish(),PerPlayerDailyTokens:z.number().nullish(),TitleDailyTokens:z.number().nullish(),RefuseOverCap:z.boolean().nullish()}).passthrough(),ha=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),DisplayDecimals:z.number().nullish(),ValueInUSD:ne.nullish(),ValueInUSDUpdatedAt:u.nullish(),UsdPriceRefreshMinutes:z.number().nullish(),DeveloperWithdrawalFeePercent:ne.nullish(),CommunityMarketingWithdrawalFeePercent:ne.nullish(),WithdrawalBurnPercent:ne.nullish(),PlayerTradeFeePercent:ne.nullish(),TradeShareCommunityMarketingPercent:ne.nullish(),Networks:z.array(AS).nullish(),Limits:TS.nullish(),Permissions:zS.nullish(),Conversion:xp.nullish(),Audit:bp.nullish(),Status:Sp.nullish(),ServerGrantPolicy:wS.nullish(),UnbackedRewardCurrencyID:z.string().nullish()}).passthrough(),kS=z.object({SpendID:z.string().nullish(),DisplayName:z.string().nullish(),PriceOptions:z.record(z.string(),qi).nullish()}).passthrough(),Ms=z.object({VirtualCurrencies:z.record(z.string(),vS).nullish(),CryptoCurrencies:z.record(z.string(),ha).nullish(),Spends:z.record(z.string(),kS).nullish()}).passthrough(),MS={Marketplace:"Marketplace",MailboxTransfer:"MailboxTransfer",Match:"Match",Workshop:"Workshop"},OS={Pending:"Pending",Released:"Released",Voided:"Voided"},gt=z.object({PayoutID:z.string().nullish(),Source:z.string().nullish(),SourceRefID:z.string().nullish(),Status:z.enum(["Pending","Released","Voided"]).catch("Pending").nullish(),Amount:ce.nullish(),CreatedAt:u.nullish(),ReleaseAt:u.nullish(),ReturnedGoods:ce.nullish(),GoodsReturned:z.boolean().nullish()}).passthrough(),Dp=z.object({Pending:z.array(gt).nullish(),Released:z.array(gt).nullish(),Voided:z.array(gt).nullish()}).passthrough();var ES={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Ip=z.enum(["System","Reward","Gift","Social"]).catch("System"),qS={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},US=z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),LS={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},BS=z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),ut={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},GS={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"},NS=100,_S=z.object({Subject:z.string().nullish(),Body:z.string().nullish()}).passthrough(),Pp=z.object({FeatureID:z.string().nullish(),Args:z.record(z.string(),z.string()).nullish(),Url:z.string().nullish(),Label:z.string().nullish()}).passthrough(),VS=z.object({Texts:z.record(z.string(),_S).nullish(),Category:Ip.nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Pp.nullish(),SenderName:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),jS=z.object({Enabled:z.boolean().nullish(),Grant:ce.nullish(),Cost:ce.nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:u.nullish(),SenderGate:ee.nullish(),TemplateID:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),FS=z.object({Type:z.string().nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxAmountPerGift:z.number().nullish()}).passthrough(),WS=z.object({Enabled:z.boolean().nullish(),AllowedResources:z.array(FS).nullish(),MaxEntriesPerGift:z.number().nullish(),AllowItemInstances:z.boolean().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:u.nullish(),FeePercent:z.number().nullish(),FeeCost:ce.nullish(),SenderGate:ee.nullish(),ExpirationDays:z.number().nullish(),TemplateID:z.string().nullish()}).passthrough(),vp=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(),VS).nullish(),Gifts:z.object({Social:z.record(z.string(),jS).nullish(),Transfer:WS.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(),KS=z.object({MessageID:z.string(),Source:US,Category:Ip,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:Pp.nullish(),SenderName:z.string().nullish(),SenderUserID:z.string().nullish(),SenderAvatarUrl:z.string().nullish(),SenderNote:z.string().nullish(),Rewards:$.nullish(),Instances:z.array(Cn).nullish(),HasRewards:z.boolean().nullish(),IsTransfer:z.boolean().nullish(),SentAt:u,ExpiresAt:u.nullish(),ReadAt:u.nullish(),ClaimedAt:u.nullish()}).passthrough(),QS=z.object({MessageID:z.string(),Module:BS,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:$.nullish()}).passthrough(),da=z.object({ID:z.string(),Error:z.string().nullish()}).passthrough(),Ap=z.object({ServerTimeUtc:u.nullish(),Messages:z.array(KS).default([]),NextCursor:z.string().nullish(),PendingRewards:z.array(QS).nullish(),UnreadCount:z.number().nullish(),UnclaimedCount:z.number().nullish(),DeliveredNow:z.number().nullish()}).passthrough(),Os=z.object({ServerTimeUtc:u.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),ma=z.object({ServerTimeUtc:u.nullish(),AffectedCount:z.number().default(0),Failed:z.array(da).default([]),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),HS=z.object({MessageID:z.string(),Rewards:ce.nullish(),Instances:z.array(Cn).nullish(),HeldPayout:gt.nullish()}).passthrough(),Es=z.object({ServerTimeUtc:u.nullish(),Claimed:z.array(HS).default([]),Failed:z.array(da).default([]),Resources:O.nullish(),Inventory:Q.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Tp=z.object({ServerTimeUtc:u.nullish(),GiftID:z.string().nullish(),Sent:z.array(z.string()).default([]),Failed:z.array(da).default([]),Resources:O.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:u.nullish()}).passthrough(),zp=z.object({ServerTimeUtc:u.nullish(),MessageID:z.string().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish(),RecipientReceives:ce.nullish(),RecipientInstances:z.array(Cn).nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:u.nullish(),IdempotentReplay:z.boolean().nullish()}).passthrough(),wp=z.object({ServerTimeUtc:u.nullish(),ResetsAt:u.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:u.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:u.nullish()}).passthrough().nullish()}).passthrough();var fa="Mailbox",ga={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},qs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ga,{schema:Os,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(ga,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(fa)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(fa,e);if(t)return a$1(t);let n=this.request();if(!n)return c;let i=await this.ctx.api.mailbox.getDefinitions(n);return i.ok&&this.ctx.data.config.patchSection(fa,i.data),i}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return c;let n=await this.ctx.api.mailbox.getMessages(t);return n.ok&&(this.emitCounters(n.data),this.ctx.emitter.emit("mailbox:messagesLoaded",n.data)),n}getUnreadCount(e){return this.ctx.cache.read(ga,()=>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 n=await this.ctx.api.mailbox.readMessages(t);return n.ok&&this.emitCounters(n.data),n}async claimReward(e){let t=e?.trim();if(!t)return b("client","MessageID is required.");let n=this.request({MessageID:t});return n?this.afterClaim(await this.ctx.api.mailbox.claimReward(n)):c}async claimRewards(e){let t=(e??[]).map(i=>i?.trim()).filter(Boolean);if(t.length===0)return b("client","MessageIDs are required.");let n=this.request({MessageIDs:t});return n?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(n)):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 n=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!n)return c;let i=await this.ctx.api.mailbox.deleteMessages(n);return i.ok&&this.emitCounters(i.data),i}async sendGift(e,t){if(!e?.trim())return b("client","GiftID is required.");let n=(t??[]).filter(Boolean);if(n.length===0)return b("client","Recipients are required.");let i=this.request({GiftID:e.trim(),RecipientUserIDs:n});if(!i)return c;let s=await this.ctx.api.mailbox.sendGift(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",s.data)),s}async sendTransfer(e,t,n){if(!e?.trim())return b("client","RecipientUserID is required.");if(!n?.requestID?.trim())return b("client","requestID is required.");let i=this.request({RecipientUserID:e.trim(),TransferEntries:t,TransferInstanceIDs:n.instanceIDs?.length?n.instanceIDs:void 0,Note:n.note,RelatedEntityID:n.requestID.trim()});if(!i)return c;let s=await this.ctx.api.mailbox.sendTransfer(i);return s.ok&&(s.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(s.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",s.data)),s}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):c}};var $S={Head:"Head",Torso:"Torso",Legs:"Legs"},Us=z.enum(["Head","Torso","Legs"]).catch("Head"),JS={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},ya=z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Mp=z.object({AttackTarget:Us,DefenseTarget:Us});var ZS=z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),YS=z.object({RoundIndex:z.number().nullish(),AttackerID:z.string().nullish(),DefenderID:z.string().nullish(),AttackZone:Us.nullish(),DefenseZone:Us.nullish(),HitType:ZS.nullish(),DamageDealt:z.number().nullish(),DefenderHpRemaining:z.number().nullish()}).passthrough(),XS=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(),ex=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:u,ExpiresAt:u.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),kp=z.object({UserID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),SelectedCharacter:Vn.nullish(),BattleStrategy:z.array(Mp).nullish(),UnstackableItems:z.record(z.string(),ex).nullish(),Stats:XS.nullish()}).passthrough(),Wn=z.object({WinnerUserID:z.string().nullish(),LoserUserID:z.string().nullish(),Entry:ce.nullish(),NetReward:ce.nullish(),BattleLog:z.array(YS).nullish(),IsDraw:z.boolean().nullish(),P1BattleProfile:kp.nullish(),P2BattleProfile:kp.nullish()}).passthrough(),Op=z.object({MatchID:z.string(),TitleID:z.string().nullish(),RuleID:z.string().nullish(),CreatedAt:u.nullish(),CreatorID:z.string().nullish(),CreatorCharacterID:z.string().nullish(),CreatorStrategy:z.array(Mp).nullish(),TargetUserID:z.string().nullish(),Entry:ce.nullish(),CreationCostPaid:ce.nullish(),RefundCreationCostOnCancel:z.boolean().nullish(),ExpiresAt:u.nullish(),JoinedByUserID:z.string().nullish(),JoinedByCharacterID:z.string().nullish(),JoinedAt:u.nullish(),Status:ya.nullish(),WinnerUserID:z.string().nullish(),CompletedAt:u.nullish(),IsRewardDistributed:z.boolean().nullish(),RewardDistributedAt:u.nullish()}).passthrough(),Ep=z.object({Status:ya,MatchID:z.string(),Entry:ce.nullish(),Resources:O.nullish()}),qp=z.object({Match:Op.nullish()}),Up=z.object({MatchID:z.string(),Status:ya,Resources:O.nullish()}),Lp=z.object({Battle:Wn.nullish(),Resources:O.nullish(),ResourcesDual:Ut.nullish(),HeldPayout:gt.nullish()}),Ra=z.object({Matches:z.array(Op).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}),kt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var tx=z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var nx=z.enum(["Constant","Variable","Curve"]).catch("Constant"),ix=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(),sx=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:sx.nullish(),MaxArmorReduction:z.number().nullish()}).passthrough(),ox=z.object({Kind:nx.nullish(),Constant:z.number().nullish(),VariableID:z.string().nullish(),Argument:z.string().nullish(),Curve:$e.nullish(),OnePlus:z.boolean().nullish()}).passthrough(),ax=z.object({Coefficient:z.number().nullish(),Factors:z.array(ox).nullish()}).passthrough(),an=z.object({Terms:z.array(ax).nullish()}).passthrough(),lx=z.object({Health:an.nullish(),Damage:an.nullish(),Armor:an.nullish(),AttackSpeed:an.nullish(),CritChance:an.nullish(),CritDamage:an.nullish(),Dodge:an.nullish()}).passthrough(),Bp=z.object({StatMapping:ix.nullish(),Combat:rx.nullish(),Formula:lx.nullish()}).passthrough(),ux=z.object({BurnRate:z.number().nullish()}).passthrough(),Kn=z.object({Kind:tx.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),TokenType:o.nullish(),EntityID:z.string().nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish()}).passthrough(),Gp=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Kn).nullish(),MaxPositions:z.number().nullish()}).passthrough(),Np=z.object({PriceOptions:he.nullish(),RefundCostOnCancel:z.boolean().nullish(),MaxOpenMatches:z.number().nullish(),OfferLifetimeSeconds:z.number().nullish(),Limits:Ie.nullish(),AllowPrivateMatches:z.boolean().nullish(),MaxMatchesPerOpponentPerDay:z.number().nullish()}).passthrough(),cx=z.object({RuleID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Economy:ux.nullish(),Entry:Gp.nullish(),Creation:Np.nullish(),Settings:Bp.nullish()}).passthrough(),px=z.object({Rules:z.record(z.string(),cx).nullish(),Defaults:Bp.nullish(),EntryDefaults:Gp.nullish(),CreationDefaults:Np.nullish()}).passthrough(),Ca=z.object({InstantBattle:px.nullish()}).passthrough(),_p=Ca;var hx={Open:"Open",Request:"Request",InviteOnly:"InviteOnly"},dx=z.enum(["Open","Request","InviteOnly"]).catch("Open"),mx={Application:"Application",Invite:"Invite"},fx={Invite:"invite",ManageApplications:"manage_applications",Kick:"kick",SetRole:"set_role",EditInfo:"edit_info",EditAnnouncement:"edit_announcement",ModerateChat:"moderate_chat",CreateRequest:"create_request",SpendTreasury:"spend_treasury",ManageProjects:"manage_projects",StartActivity:"start_activity",SelectQuests:"select_quests"},Ue={GetDefinitions:"GetDefinitions",GetMyClans:"GetMyClans",SearchClans:"SearchClans",GetRecommendedClans:"GetRecommendedClans",GetClan:"GetClan",GetClanMembers:"GetClanMembers",GetRankings:"GetRankings",CreateClan:"CreateClan",UpdateClan:"UpdateClan",DisbandClan:"DisbandClan",JoinClan:"JoinClan",ApplyToClan:"ApplyToClan",CancelApplication:"CancelApplication",GetApplications:"GetApplications",AcceptApplication:"AcceptApplication",RejectApplication:"RejectApplication",InvitePlayer:"InvitePlayer",GetMyInvites:"GetMyInvites",AcceptInvite:"AcceptInvite",DeclineInvite:"DeclineInvite",LeaveClan:"LeaveClan",KickMember:"KickMember",SetMemberRole:"SetMemberRole",TransferLeadership:"TransferLeadership",GetClanLog:"GetClanLog",CreateRequest:"CreateRequest",Donate:"Donate",Help:"Help",ClaimRequest:"ClaimRequest",GetRequests:"GetRequests",GetGifts:"GetGifts",ClaimGift:"ClaimGift",ClaimAllGifts:"ClaimAllGifts",GetRewards:"GetRewards",ClaimRewards:"ClaimRewards",GetTreasury:"GetTreasury",DepositToTreasury:"DepositToTreasury",BuyTreasuryPurchase:"BuyTreasuryPurchase",GetProjects:"GetProjects",ContributeToProject:"ContributeToProject",SetRecommendedProject:"SetRecommendedProject",GetActivities:"GetActivities",StartActivity:"StartActivity",SubmitActivityScore:"SubmitActivityScore",ClaimActivityRewards:"ClaimActivityRewards",GetClanQuests:"GetClanQuests",SelectClanQuests:"SelectClanQuests",TakeClanQuest:"TakeClanQuest",AbandonClanQuest:"AbandonClanQuest",ClaimClanQuestRewards:"ClaimClanQuestRewards",GetCompetitions:"GetCompetitions",RegisterForCompetition:"RegisterForCompetition",GetBracket:"GetBracket",ClaimCompetitionRewards:"ClaimCompetitionRewards",StartWarAttack:"StartWarAttack",GetDiplomacy:"GetDiplomacy",SetDiplomacy:"SetDiplomacy",GetRevenges:"GetRevenges",TakeRevenge:"TakeRevenge",GetLeague:"GetLeague",ClaimSeasonReward:"ClaimSeasonReward"},gx={Disabled:"CLAN_DISABLED",UnknownKind:"CLAN_UNKNOWN_KIND",KindRequired:"CLAN_KIND_REQUIRED",NotFound:"CLAN_NOT_FOUND",NotMember:"CLAN_NOT_MEMBER",AlreadyInClan:"CLAN_ALREADY_IN_CLAN",Full:"CLAN_FULL",NoPermission:"CLAN_NO_PERMISSION",RankTooLow:"CLAN_RANK_TOO_LOW",RoleFull:"CLAN_ROLE_FULL",UnknownRole:"CLAN_UNKNOWN_ROLE",NameTaken:"CLAN_NAME_TAKEN",TagTaken:"CLAN_TAG_TAKEN",NameInvalid:"CLAN_NAME_INVALID",TagInvalid:"CLAN_TAG_INVALID",TextInvalid:"CLAN_TEXT_INVALID",TextBlocked:"CLAN_TEXT_BLOCKED",GateFailed:"CLAN_GATE_FAILED",RequirementsNotMet:"CLAN_REQUIREMENTS_NOT_MET",JoinModeMismatch:"CLAN_JOIN_MODE_MISMATCH",JoinCooldown:"CLAN_JOIN_COOLDOWN",RejoinCooldown:"CLAN_REJOIN_COOLDOWN",TooManyApplications:"CLAN_TOO_MANY_APPLICATIONS",ApplicationNotFound:"CLAN_APPLICATION_NOT_FOUND",InviteNotFound:"CLAN_INVITE_NOT_FOUND",PlayerNotFound:"CLAN_PLAYER_NOT_FOUND",LeaderMustTransfer:"CLAN_LEADER_MUST_TRANSFER",CannotTargetSelf:"CLAN_CANNOT_TARGET_SELF",KickLimit:"CLAN_KICK_LIMIT",RenameCooldown:"CLAN_RENAME_COOLDOWN",InvalidArgument:"CLAN_INVALID_ARGUMENT",FeatureDisabled:"CLAN_FEATURE_DISABLED",RequestNotFound:"CLAN_REQUEST_NOT_FOUND",RequestClosed:"CLAN_REQUEST_CLOSED",RequestCooldown:"CLAN_REQUEST_COOLDOWN",RequestLimit:"CLAN_REQUEST_LIMIT",RequestFilled:"CLAN_REQUEST_FILLED",DonateLimit:"CLAN_DONATE_LIMIT",AlreadyHelped:"CLAN_ALREADY_HELPED",NothingToClaim:"CLAN_NOTHING_TO_CLAIM",GiftNotFound:"CLAN_GIFT_NOT_FOUND",TenureRequired:"CLAN_TENURE_REQUIRED",Conflict:"CLAN_CONFLICT",SystemCapReached:"CLAN_SYSTEM_CAP_REACHED",ItemNotAllowed:"CLAN_ITEM_NOT_ALLOWED",ItemLevelTooHigh:"CLAN_ITEM_LEVEL_TOO_HIGH",ItemEquipped:"CLAN_ITEM_EQUIPPED",ItemWrongLevel:"CLAN_ITEM_WRONG_LEVEL",NotEnoughTreasury:"CLAN_NOT_ENOUGH_TREASURY",DepositLimit:"CLAN_DEPOSIT_LIMIT",PurchaseNotFound:"CLAN_PURCHASE_NOT_FOUND",BuffActive:"CLAN_BUFF_ACTIVE",LevelTooLow:"CLAN_LEVEL_TOO_LOW",ProjectNotFound:"CLAN_PROJECT_NOT_FOUND",ProjectLocked:"CLAN_PROJECT_LOCKED",ProjectMaxed:"CLAN_PROJECT_MAXED",ContributeLimit:"CLAN_CONTRIBUTE_LIMIT",ActivityNotFound:"CLAN_ACTIVITY_NOT_FOUND",ActivityNotActive:"CLAN_ACTIVITY_NOT_ACTIVE",ActivityRunning:"CLAN_ACTIVITY_RUNNING",ActivityCooldown:"CLAN_ACTIVITY_COOLDOWN",NoAttempts:"CLAN_NO_ATTEMPTS",ScoreRejected:"CLAN_SCORE_REJECTED",BossDefeated:"CLAN_BOSS_DEFEATED",BoardNotFound:"CLAN_BOARD_NOT_FOUND",QuestNotFound:"CLAN_QUEST_NOT_FOUND",QuestFull:"CLAN_QUEST_FULL",TakeLimit:"CLAN_TAKE_LIMIT",QuestNotTaken:"CLAN_QUEST_NOT_TAKEN",QuestDone:"CLAN_QUEST_DONE",AbandonCooldown:"CLAN_ABANDON_COOLDOWN",SelectionLocked:"CLAN_SELECTION_LOCKED",ClaimAfterEnd:"CLAN_CLAIM_AFTER_END",NotEligible:"CLAN_NOT_ELIGIBLE",ClaimExpired:"CLAN_CLAIM_EXPIRED",CompetitionNotFound:"CLAN_COMPETITION_NOT_FOUND",CompetitionNotActive:"CLAN_COMPETITION_NOT_ACTIVE",RegistrationClosed:"CLAN_REGISTRATION_CLOSED",NotRegistered:"CLAN_NOT_REGISTERED",TooFewMembers:"CLAN_TOO_FEW_MEMBERS",WarPreparation:"CLAN_WAR_PREPARATION",NotInRoster:"CLAN_NOT_IN_ROSTER",TargetInvalid:"CLAN_TARGET_INVALID",AttackPending:"CLAN_ATTACK_PENDING",AttackNotFound:"CLAN_ATTACK_NOT_FOUND",AttackExpired:"CLAN_ATTACK_EXPIRED",RelationExists:"CLAN_RELATION_EXISTS",RelationLimit:"CLAN_RELATION_LIMIT",RelationNotFound:"CLAN_RELATION_NOT_FOUND",RelationDisabled:"CLAN_RELATION_DISABLED"},yx={Duel:"Duel",Battle:"Battle",League:"League",War:"War"},Rx={Ally:"Ally",Pact:"Pact",Enemy:"Enemy",None:"None"},Ls="clan",ln=z.array(z.string()).nullish(),Z=z.number().nullish(),Cx=z.record(z.string(),z.number()).nullish(),Sx=z.object({NounKey:z.string().nullish(),DisplayName:z.string().nullish(),Icon:z.string().nullish(),SortOrder:Z}).passthrough(),xx=z.object({NameMinLength:Z,NameMaxLength:Z,TagRequired:z.boolean().nullish(),TagMinLength:Z,TagMaxLength:Z,DescriptionMaxLength:Z,AnnouncementMaxLength:Z,Emblem:z.object({Backgrounds:ln,Symbols:ln,Colors:ln}).passthrough().nullish(),Languages:ln,Attributes:z.record(z.string(),z.object({NameKey:z.string().nullish(),Values:ln,Required:z.boolean().nullish()}).passthrough()).nullish(),RenameCooldownHours:Z}).passthrough(),bx=z.object({BaseCapacity:Z,JoinModes:z.array(z.string()).nullish(),DefaultJoinMode:z.string().nullish(),ApplicationHours:Z,InviteHours:Z,JoinCooldownHours:Z,TenureHoursForRewards:Z,NoBoardAttacksOnClanmates:z.boolean().nullish(),SuggestJoinAfterHours:Z,KickInactiveDays:Z}).passthrough(),Dx=z.object({Rank:z.number().catch(0),NameKey:z.string().nullish(),DisplayName:z.string().nullish(),MaxCount:Z,Permissions:ln}).passthrough(),Ix=z.object({Enabled:z.boolean().nullish(),Type:z.string().catch("Resource"),NameKey:z.string().nullish(),CooldownMinutes:Z,LifetimeHours:Z,MaxOpenPerMember:Z,Resources:z.array(vt.passthrough()).nullish(),Funding:z.string().nullish(),MaxPerDonor:Z,MaxHelps:Z,MaxItemLevel:Z,MinMembershipHoursToDonate:Z}).passthrough(),Px=z.object({Enabled:z.boolean().nullish(),Identity:Sx.nullish(),Create:xx.nullish(),Membership:bx.nullish(),Roles:z.object({Roles:z.record(z.string(),Dx).nullish(),LeaderRoleID:z.string().nullish(),DefaultRoleID:z.string().nullish()}).passthrough().nullish(),Rankings:z.object({Metrics:ln,ByLanguage:z.boolean().nullish(),ByRegion:z.boolean().nullish()}).passthrough().nullish(),Counters:z.record(z.string(),z.object({}).passthrough()).nullish(),Progression:z.object({}).passthrough().nullish(),Requests:z.record(z.string(),Ix).nullish(),Gifts:z.object({Gifts:z.record(z.string(),z.object({}).passthrough()).nullish(),ShowSender:z.boolean().nullish()}).passthrough().nullish(),Treasury:z.object({Currencies:z.record(z.string(),z.object({NameKey:z.string().nullish(),Icon:z.string().nullish(),Deposits:z.array(z.object({Resource:vt.passthrough().nullish(),Gives:z.number().catch(1)}).passthrough()).nullish(),DailyDepositCapPerMember:Z,Max:Z}).passthrough()).nullish(),Purchases:z.record(z.string(),z.object({Enabled:z.boolean().nullish(),NameKey:z.string().nullish(),Icon:z.string().nullish(),Cost:Cx,DurationHours:z.number().catch(24),MinClanLevel:Z}).passthrough()).nullish()}).passthrough().nullish(),Projects:z.record(z.string(),z.object({Enabled:z.boolean().nullish(),NameKey:z.string().nullish(),Icon:z.string().nullish(),SortOrder:Z,Inputs:z.array(z.object({Resource:vt.passthrough().nullish(),TreasuryCurrencyID:z.string().nullish(),PointsPerUnit:Z}).passthrough()).nullish()}).passthrough()).nullish(),Activities:z.record(z.string(),z.object({Enabled:z.boolean().nullish(),Type:z.string().catch("Goal"),NameKey:z.string().nullish(),Icon:z.string().nullish()}).passthrough()).nullish(),Quests:z.record(z.string(),z.object({Enabled:z.boolean().nullish(),Mode:z.string().catch("Shared"),NameKey:z.string().nullish()}).passthrough()).nullish(),Competitions:z.record(z.string(),z.object({Enabled:z.boolean().nullish(),Type:z.string().catch("Battle"),NameKey:z.string().nullish(),Icon:z.string().nullish(),Registration:z.string().nullish(),MinMembers:Z,BracketSize:Z,Phases:z.array(z.object({DurationHours:z.number().catch(24),NameKey:z.string().nullish()}).passthrough()).nullish(),War:z.object({AttacksPerMember:Z,MaxStars:Z,RosterSize:Z,PreparationHours:Z,ResultSource:z.string().nullish()}).passthrough().nullish()}).passthrough()).nullish(),Leagues:z.object({StartRating:Z,Tiers:z.array(z.object({LeagueID:z.string(),MinRating:z.number().catch(0),NameKey:z.string().nullish(),Icon:z.string().nullish(),SeasonReward:$.nullish()}).passthrough()).nullish(),Season:z.object({IntervalSeconds:Z,AnchorUtc:z.string().nullish(),KeepPercent:Z}).passthrough().nullish()}).passthrough().nullish(),Revenge:z.object({Enabled:z.boolean().nullish(),WindowHours:Z,MaxPerMemberPerDay:Z}).passthrough().nullish(),ChatNotices:z.object({Enabled:z.boolean().nullish(),Events:z.array(z.string()).nullish()}).passthrough().nullish(),Diplomacy:z.object({MaxAllies:Z,MaxPacts:Z,MaxEnemies:Z,ProposalHours:Z}).passthrough().nullish()}).passthrough(),vx=z.object({IsEnabled:z.boolean().nullish(),Kinds:z.record(z.string(),Px).nullish(),RefreshSeconds:Z}).passthrough(),xa=z.record(z.string(),z.string()).nullish(),Sa=z.record(z.string(),z.number()).nullish(),Jt=z.object({ClanID:z.string(),KindID:z.string().catch(Ls),Name:z.string().catch(""),Tag:z.string().nullish(),Description:z.string().nullish(),Announcement:z.string().nullish(),Emblem:z.object({Background:z.string().nullish(),Symbol:z.string().nullish(),Color:z.string().nullish()}).passthrough().nullish(),Language:z.string().nullish(),Country:z.string().nullish(),Attributes:xa,JoinMode:dx,MinPower:Z,MinLevel:Z,LeaderUserID:z.string().nullish(),MemberCount:z.number().catch(0),Capacity:z.number().catch(0),Level:z.number().catch(1),Xp:z.number().catch(0),NextLevelXp:Z,GiftPoints:z.number().catch(0),GiftLevel:z.number().catch(0),Power:z.number().catch(0),Trophies:z.number().catch(0),Counters:Sa,Perks:Sa,Modifiers:z.array(z.object({}).passthrough()).nullish(),Treasury:Sa,RecommendedProjectID:z.string().nullish(),LeagueRating:z.number().catch(0),LeagueID:z.string().nullish(),CreatedAt:u.nullish(),ActiveAt:u.nullish()}).passthrough(),ba=z.object({RoleID:z.string().catch(""),JoinedAt:u.nullish(),Permissions:z.array(z.string()).catch([]),IsLeader:z.boolean().catch(false),ContributionTotal:z.number().catch(0),ContributionToday:z.number().catch(0),ContributionWeek:z.number().catch(0),DonatedTotal:z.number().catch(0),RewardsFrom:u.nullish()}).passthrough(),Ax=z.object({KindID:z.string(),Clan:Jt.nullish(),Membership:ba.nullish(),JoinAllowedAt:u.nullish(),InvitesCount:z.number().catch(0),MyApplicationsCount:z.number().catch(0),ClaimableRewards:z.number().catch(0),ClaimableGifts:z.number().catch(0),ClaimableCompetitions:z.number().catch(0),SuggestJoin:z.boolean().catch(false)}).passthrough(),jp=z.object({ServerTimeUtc:u.nullish(),RefreshSeconds:z.number().catch(30),Kinds:z.array(Ax).catch([])}).passthrough(),Da=z.object({ServerTimeUtc:u.nullish(),Clans:z.array(Jt).catch([]),NextCursor:z.string().nullish()}).passthrough(),Fp=z.object({ServerTimeUtc:u.nullish(),Clan:Jt,Membership:ba.nullish(),Applied:z.boolean().catch(false)}).passthrough(),Wp=z.object({UserID:z.string(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),PlayerLevel:z.number().catch(0),RoleID:z.string().catch(""),JoinedAt:u.nullish(),ActiveAt:u.nullish(),Power:z.number().catch(0),Trophies:z.number().catch(0),ContributionTotal:z.number().catch(0),ContributionWeek:z.number().catch(0),ContributionToday:z.number().catch(0),DonatedTotal:z.number().catch(0)}).passthrough(),Kp=z.object({ServerTimeUtc:u.nullish(),ClanID:z.string().nullish(),Members:z.array(Wp).catch([])}).passthrough(),Vp=z.object({Rank:z.number().catch(0),Value:z.number().catch(0),Clan:Jt}).passthrough(),Qp=z.object({ServerTimeUtc:u.nullish(),Metric:z.string().nullish(),Slice:z.string().nullish(),Rows:z.array(Vp).catch([]),Mine:Vp.nullish()}).passthrough(),Tx=z.object({ID:z.string(),Type:z.string().catch("Application"),KindID:z.string().nullish(),ClanID:z.string().nullish(),Clan:Jt.nullish(),UserID:z.string().nullish(),Player:Wp.nullish(),InviterUserID:z.string().nullish(),Message:z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),Ia=z.object({ServerTimeUtc:u.nullish(),Items:z.array(Tx).catch([])}).passthrough(),zx=z.object({Type:z.string().catch(""),ActorUserID:z.string().nullish(),TargetUserID:z.string().nullish(),Params:xa,At:u.nullish()}).passthrough(),Hp=z.object({ServerTimeUtc:u.nullish(),Entries:z.array(zx).catch([]),NextCursor:z.string().nullish()}).passthrough(),$p=z.object({RequestID:z.string(),RequestKindID:z.string().catch(""),Type:z.string().catch("Resource"),UserID:z.string().catch(""),Username:z.string().nullish(),Resource:vt.passthrough().nullish(),ItemLevel:z.number().nullish(),Needed:z.number().catch(0),Filled:z.number().catch(0),Claimed:z.number().catch(0),MyDonation:z.number().catch(0),TaskKey:z.string().nullish(),Helps:z.number().catch(0),MaxHelps:z.number().catch(0),HelpedByMe:z.boolean().catch(false),Status:z.string().catch("Open"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),Jp=z.object({ServerTimeUtc:u.nullish(),Requests:z.array($p).catch([])}).passthrough(),wx=z.object({GiftUid:z.string(),GiftID:z.string().catch(""),SenderUserID:z.string().nullish(),Level:z.number().catch(0),Content:$.nullish(),Claimed:z.boolean().catch(false),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),Zp=z.object({ServerTimeUtc:u.nullish(),GiftLevel:z.number().catch(0),GiftPoints:z.number().catch(0),NextGiftLevelPoints:Z,Gifts:z.array(wx).catch([])}).passthrough(),Bs=z.object({Key:z.string(),Source:z.string().nullish(),MilestoneID:z.string().nullish(),RequiredProgress:z.number().catch(0),Rewards:$.nullish(),ReachedAt:u.nullish(),Claimed:z.boolean().catch(false),Claimable:z.boolean().catch(false),Blocked:z.string().nullish()}).passthrough(),Yp=z.object({ServerTimeUtc:u.nullish(),Rewards:z.array(Bs).catch([])}).passthrough(),Xp=z.object({AttackID:z.string(),AttackerUserID:z.string().nullish(),TargetUserID:z.string().nullish(),Status:z.string().catch("Pending"),Stars:z.number().catch(0),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),eh=z.object({ClanID:z.string(),Clan:Jt.nullish(),Relation:z.string().catch("None"),Status:z.string().catch("Active"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),th=z.object({ServerTimeUtc:u.nullish(),Clan:Jt.nullish(),Membership:ba.nullish(),Request:$p.nullish(),Resources:O.nullish(),Inventory:Q.nullish(),Done:z.array(z.string()).nullish(),Failed:xa,WarAttack:Xp.nullish(),WarBattle:Wn.nullish(),Relation:eh.nullish()}).passthrough(),nh=z.object({ServerTimeUtc:u.nullish(),Definitions:vx.nullish(),DefaultKindID:z.string().nullish()}).passthrough(),kx=z.object({Target:z.string().catch(""),Operation:z.string().catch("AddPercent"),Value:z.number().catch(0),Tag:z.string().nullish()}).passthrough(),Mx=z.object({PurchaseID:z.string(),ExpiresAt:u.nullish(),Modifiers:z.array(kx).nullish()}).passthrough(),Ox=z.object({CurrencyID:z.string().catch(""),Delta:z.number().catch(0),Kind:z.string().nullish(),ActorUserID:z.string().nullish(),RefID:z.string().nullish(),At:u.nullish()}).passthrough(),ih=z.object({ServerTimeUtc:u.nullish(),Balances:z.record(z.string(),z.number()).catch({}),Buffs:z.array(Mx).catch([]),Ledger:z.array(Ox).catch([]),NextCursor:z.string().nullish(),MyDepositsToday:z.record(z.string(),z.number()).catch({})}).passthrough(),Ex=z.object({ProjectID:z.string(),Points:z.number().catch(0),Level:z.number().catch(0),MaxLevel:z.number().catch(0),NextLevelPoints:Z,Locked:z.string().nullish(),MyPointsToday:z.number().catch(0),DailyCap:Z,Recommended:z.boolean().catch(false)}).passthrough(),sh=z.object({ServerTimeUtc:u.nullish(),RecommendedProjectID:z.string().nullish(),Projects:z.array(Ex).catch([])}).passthrough(),qx=z.object({ActivityID:z.string(),Type:z.string().catch("Goal"),Status:z.string().catch("Idle"),InstanceKey:z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),Points:z.number().catch(0),MyPoints:z.number().catch(0),MyPointsToday:z.number().catch(0),BossLevel:z.number().catch(0),BossHp:z.number().catch(0),BossDamage:z.number().catch(0),BossDefeated:z.boolean().catch(false),AttemptsLeft:z.number().catch(0),CanStart:z.boolean().catch(false),StartAllowedAt:u.nullish(),Rewards:z.array(Bs).catch([])}).passthrough(),rh=z.object({ServerTimeUtc:u.nullish(),Activities:z.array(qx).catch([])}).passthrough(),Ux=z.object({ObjectiveID:z.string().catch(""),Target:z.number().catch(0),Progress:z.number().catch(0),MyProgress:z.number().catch(0)}).passthrough(),Lx=z.object({QuestID:z.string(),Identity:z.object({DisplayName:z.string().nullish(),Description:z.string().nullish()}).passthrough().nullish(),Objectives:z.array(Ux).catch([]),Reward:z.object({Grant:$.nullish(),PointsReward:Z}).passthrough().nullish(),ClanXp:Z,Status:z.string().catch("Available"),Takers:z.number().catch(0),MyContribution:z.number().catch(0),Claimable:z.boolean().catch(false),Claimed:z.boolean().catch(false),Blocked:z.string().nullish()}).passthrough(),Bx=z.object({BoardID:z.string(),Mode:z.string().catch("Shared"),CycleKey:z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),Ended:z.boolean().catch(false),Points:z.number().catch(0),MyPoints:z.number().catch(0),MyTaken:z.number().catch(0),MaxTaken:z.number().catch(0),TakeAllowedAt:u.nullish(),SelectedBy:z.string().nullish(),CanSelect:z.boolean().catch(false),Quests:z.array(Lx).catch([]),Rewards:z.array(Bs).catch([])}).passthrough(),oh=z.object({ServerTimeUtc:u.nullish(),Boards:z.array(Bx).catch([])}).passthrough(),Gx=z.object({CompetitionID:z.string(),Type:z.string().catch("Battle"),Status:z.string().catch("Idle"),InstanceKey:z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),PhaseIndex:Z,PhaseEndsAt:u.nullish(),Registered:z.boolean().catch(false),CanRegister:z.boolean().catch(false),RegisterBlocked:z.string().nullish(),RegistrationClosesAt:u.nullish(),BracketID:z.string().nullish(),ClansInBracket:z.number().catch(0),Score:z.number().catch(0),Place:Z,Finalized:z.boolean().catch(false),NoContest:z.boolean().catch(false),RatingDelta:Z,MyPoints:z.number().catch(0),MyPointsToday:z.number().catch(0),AttacksLeft:Z,InRoster:z.boolean().nullish(),AttacksFrom:u.nullish(),Rewards:z.array(Bs).catch([])}).passthrough(),ah=z.object({ServerTimeUtc:u.nullish(),LeagueRating:z.number().catch(0),LeagueID:z.string().nullish(),Competitions:z.array(Gx).catch([])}).passthrough(),Nx=z.object({Place:z.number().catch(0),Clan:Jt.nullish(),Score:z.number().catch(0),RatingDelta:Z,IsMine:z.boolean().catch(false)}).passthrough(),_x=z.object({UserID:z.string(),ClanID:z.string().nullish(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),Power:z.number().catch(0),BestStars:z.number().catch(0),AttacksUsed:z.number().catch(0)}).passthrough(),lh=z.object({ServerTimeUtc:u.nullish(),BracketID:z.string().nullish(),CompetitionID:z.string().nullish(),Type:z.string().catch("Battle"),InstanceKey:z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),Finalized:z.boolean().catch(false),NoContest:z.boolean().catch(false),Rows:z.array(Nx).catch([]),War:z.array(_x).nullish(),MyAttacks:z.array(Xp).nullish()}).passthrough(),uh=z.object({ServerTimeUtc:u.nullish(),CanManage:z.boolean().catch(false),Relations:z.array(eh).catch([]),Limits:z.record(z.string(),z.number()).catch({}),Counts:z.record(z.string(),z.number()).catch({})}).passthrough(),Vx=z.object({RevengeID:z.string(),VictimUserID:z.string().nullish(),VictimName:z.string().nullish(),AttackerUserID:z.string().nullish(),AttackerName:z.string().nullish(),AttackerAvatarUrl:z.string().nullish(),Action:z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish(),TakenBy:z.string().nullish(),TakenByName:z.string().nullish(),IsMine:z.boolean().catch(false)}).passthrough(),ch=z.object({ServerTimeUtc:u.nullish(),Revenges:z.array(Vx).catch([]),TakenToday:z.number().catch(0),DailyLimit:z.number().catch(0)}).passthrough(),jx=z.object({Key:z.string().nullish(),LeagueID:z.string().nullish(),Rating:z.number().catch(0),EndedAt:u.nullish(),Reward:$.nullish(),Claimable:z.boolean().catch(false),Claimed:z.boolean().catch(false)}).passthrough(),ph=z.object({ServerTimeUtc:u.nullish(),LeagueRating:z.number().catch(0),LeagueID:z.string().nullish(),SeasonKey:z.string().nullish(),SeasonEndsAt:u.nullish(),LastSeason:jx.nullish()}).passthrough();var Pa="Clan",Gs=class{constructor(e){this.ctx=e;}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}get definitions(){return this.ctx.data.config.getSection(Pa)}get enabled(){let e=this.definitions;return !e||e.IsEnabled===false?false:Object.values(e.Kinds??{}).some(t=>t?.Enabled!==false)}get kindIDs(){let e=this.definitions?.Kinds??{};return Object.entries(e).filter(([,t])=>t?.Enabled!==false).sort(([,t],[,n])=>(t?.Identity?.SortOrder??0)-(n?.Identity?.SortOrder??0)).map(([t])=>t)}kind(e){return (this.definitions?.Kinds??{})[e??this.kindIDs[0]??Ls]}async getDefinitions(e){let t=this.ctx.cache.configSection(Pa,e);if(t)return a$1(t);let n=this.request();if(!n)return c;let i=await this.ctx.api.clan.getDefinitions(n);if(!i.ok)return i;let s=i.data.Definitions??{};return this.ctx.data.config.patchSection(Pa,s),a$1(s)}async getMyClans(){let e=this.request();if(!e)return c;let t=await this.ctx.api.clan.getMyClans(e);return t.ok&&this.ctx.emitter.emit("clan:myClansLoaded",t.data),t}async searchClans(e){let t=this.request({KindID:e?.kindID,Query:e?.query,OnlyOpen:e?.onlyOpen,NotFull:e?.notFull,Language:e?.language,PageSize:e?.pageSize});return t?this.ctx.api.clan.searchClans(t):c}async getRecommendedClans(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRecommendedClans(t):c}async getClan(e,t){if(!e?.trim())return b("client","ClanID is required.");let n=this.request({ClanID:e.trim(),KindID:t});return n?this.ctx.api.clan.getClan(n):c}async getMembers(e,t){let n=this.request({ClanID:e,KindID:t});return n?this.ctx.api.clan.getClanMembers(n):c}async getRankings(e){let t=this.request({KindID:e?.kindID,Metric:e?.metric,Slice:e?.slice,PageSize:e?.pageSize});return t?this.ctx.api.clan.getRankings(t):c}async getApplications(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getApplications(t):c}async getMyInvites(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getMyInvites(t):c}async getLog(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getClanLog(t):c}async getRequests(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRequests(t):c}async getGifts(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getGifts(t):c}async getRewards(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRewards(t):c}async getTreasury(e,t){let n=this.request({KindID:e,Cursor:t});return n?this.ctx.api.clan.getTreasury(n):c}async getProjects(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getProjects(t):c}async getActivities(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getActivities(t):c}async getClanQuests(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getClanQuests(t):c}async getCompetitions(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getCompetitions(t):c}async getBracket(e,t){let n=this.request({CompetitionID:e,BracketID:t?.bracketID,InstanceKey:t?.instanceKey,KindID:t?.kindID});return n?this.ctx.api.clan.getBracket(n):c}async getDiplomacy(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getDiplomacy(t):c}async getRevenges(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRevenges(t):c}async getLeague(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getLeague(t):c}async mutate(e,t){let n=this.request(t);if(!n)return c;let i=await this.ctx.api.clan.mutate(e,n);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("clan:changed",{action:e,...i.data})),i}info(e){return {ClanName:e.name,Tag:e.tag,Description:e.description,Announcement:e.announcement,Emblem:e.emblem,Language:e.language,Attributes:e.attributes,JoinMode:e.joinMode,MinPower:e.minPower,MinLevel:e.minLevel,PriceOptionID:e.priceOptionID}}createClan(e,t){return e?.name?.trim()?this.mutate("CreateClan",{KindID:t,...this.info(e)}):Promise.resolve(b("client","Name is required."))}updateClan(e,t){return this.mutate("UpdateClan",{KindID:t,...this.info(e)})}disbandClan(e){return this.mutate("DisbandClan",{KindID:e})}joinClan(e,t){return this.mutate("JoinClan",{ClanID:e,KindID:t})}applyToClan(e,t,n){return this.mutate("ApplyToClan",{ClanID:e,Message:t,KindID:n})}cancelApplication(e,t){return this.mutate("CancelApplication",{ClanID:e,KindID:t})}acceptApplication(e,t){return this.mutate("AcceptApplication",{TargetUserID:e,KindID:t})}rejectApplication(e,t){return this.mutate("RejectApplication",{TargetUserID:e,KindID:t})}invitePlayer(e,t,n){return this.mutate("InvitePlayer",{TargetUserID:e,Message:t,KindID:n})}acceptInvite(e,t){return this.mutate("AcceptInvite",{ClanID:e,KindID:t})}declineInvite(e,t){return this.mutate("DeclineInvite",{ClanID:e,KindID:t})}leaveClan(e){return this.mutate("LeaveClan",{KindID:e})}kickMember(e,t){return this.mutate("KickMember",{TargetUserID:e,KindID:t})}setMemberRole(e,t,n){return this.mutate("SetMemberRole",{TargetUserID:e,RoleID:t,KindID:n})}transferLeadership(e,t){return this.mutate("TransferLeadership",{TargetUserID:e,KindID:t})}createRequest(e,t){return this.mutate("CreateRequest",{RequestKindID:e,Resource:t?.resource,TaskKey:t?.taskKey,ItemInstanceID:t?.itemInstanceID,KindID:t?.kindID})}donateItems(e,t,n){return this.mutate("Donate",{RequestID:e,ItemInstanceIDs:t,KindID:n})}donate(e,t=1,n){return this.mutate("Donate",{RequestID:e,Amount:t,KindID:n})}help(e,t){return this.mutate("Help",{RequestID:e,KindID:t})}claimRequest(e,t){return this.mutate("ClaimRequest",{RequestID:e,KindID:t})}claimGift(e,t){return this.mutate("ClaimGift",{GiftUid:e,KindID:t})}claimAllGifts(e){return this.mutate("ClaimAllGifts",{KindID:e})}claimRewards(e,t){return this.mutate("ClaimRewards",{RewardKeys:e,KindID:t})}depositToTreasury(e,t,n=1,i){return this.mutate("DepositToTreasury",{CurrencyID:e,PayWith:t,Steps:n,KindID:i,RelatedEntityID:`clan_deposit_${a()}`})}buyTreasuryPurchase(e,t){return this.mutate("BuyTreasuryPurchase",{PurchaseID:e,KindID:t})}contributeToProject(e,t){return this.mutate("ContributeToProject",{ProjectID:e,Amount:t.amount,PayWith:t.payWith,FromTreasury:t.fromTreasury,CurrencyID:t.currencyID,KindID:t.kindID,RelatedEntityID:`clan_project_${a()}`})}setRecommendedProject(e,t){return this.mutate("SetRecommendedProject",{ProjectID:e??void 0,KindID:t})}startActivity(e,t){return this.mutate("StartActivity",{ActivityID:e,KindID:t})}submitActivityScore(e,t,n){return this.mutate("SubmitActivityScore",{ActivityID:e,Score:t,KindID:n})}claimActivityRewards(e){return this.mutate("ClaimActivityRewards",{ActivityID:e?.activityID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}selectClanQuests(e,t,n){return this.mutate("SelectClanQuests",{BoardID:e,QuestIDs:t,KindID:n})}takeClanQuest(e,t,n){return this.mutate("TakeClanQuest",{BoardID:e,QuestID:t,KindID:n})}abandonClanQuest(e,t,n){return this.mutate("AbandonClanQuest",{BoardID:e,QuestID:t,KindID:n})}claimClanQuestRewards(e){return this.mutate("ClaimClanQuestRewards",{BoardID:e?.boardID,QuestID:e?.questID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}registerForCompetition(e,t){return this.mutate("RegisterForCompetition",{CompetitionID:e,KindID:t})}claimCompetitionRewards(e){return this.mutate("ClaimCompetitionRewards",{CompetitionID:e?.competitionID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}startWarAttack(e,t,n){return this.mutate("StartWarAttack",{CompetitionID:e,TargetUserID:t,CharacterID:n?.characterID,KindID:n?.kindID})}setDiplomacy(e,t,n){return this.mutate("SetDiplomacy",{TargetClanID:e,Relation:t,KindID:n})}takeRevenge(e,t){return this.mutate("TakeRevenge",{RevengeID:e,KindID:t})}claimSeasonReward(e){return this.mutate("ClaimSeasonReward",{KindID:e})}};var An={GetDefinitions:"GetDefinitions",GetAvatars:"GetAvatars",GetShop:"GetShop",BuyItem:"BuyItem"},Fx={TooManyUsers:"AVATAR_TOO_MANY_USERS",Disabled:"AVATAR_DISABLED",NotForSale:"AVATAR_ITEM_NOT_FOR_SALE"},Ns=50,_s=z.object({Enabled:z.boolean().nullish(),Styles:z.array(z.string()).nullish(),BlockedSlots:z.array(z.string()).nullish(),HeightMin:z.number().nullish(),HeightMax:z.number().nullish()}).passthrough(),Wx=48,Kx=z.object({UserID:z.string(),Rev:z.string(),NotModified:z.boolean().nullish(),HasAvatar:z.boolean(),Spec:z.record(z.string(),z.unknown()).nullish()}).passthrough(),hh=z.object({id:z.string(),slot:z.string()}).passthrough(),dh=z.object({Enabled:z.boolean(),Avatars:z.array(Kx).nullish().transform(o=>o??[]),Items:z.record(z.string(),hh).nullish().transform(o=>o??{})}).passthrough(),Qx=z.object({ItemID:z.string(),Slot:z.string(),PriceCredits:z.number(),OnSale:z.boolean().nullish(),Name:z.string().nullish(),Source:z.enum(["platform","authors"]).nullish().catch(null),AuthorName:z.string().nullish(),IsOwned:z.boolean().nullish()}).passthrough(),mh=z.object({Enabled:z.boolean(),Offers:z.array(Qx).nullish().transform(o=>o??[]),Owned:z.array(z.string()).nullish().transform(o=>o??[]),LoginRequired:z.boolean().nullish().transform(o=>o??false),Items:z.record(z.string(),hh).nullish().transform(o=>o??{}),Paged:z.boolean().nullish(),Next:z.string().nullish(),Slots:z.array(z.string()).nullish(),AuthorsOpen:z.boolean().nullish()}).passthrough(),fh=z.object({ItemID:z.string().nullish(),Owned:z.boolean().nullish().transform(o=>o??false),TestPurchase:z.boolean().nullish().transform(o=>o??false),CreditsConfirmation:ge.nullish()}).passthrough();var Hx="Avatar",Vs=class{constructor(e){this.ctx=e;e.emitter.on("auth:loggedOut",()=>{this.held.clear(),this.inflight.clear(),this.disabled=false;});}ctx;held=new Map;inflight=new Map;disabled=false;get definitions(){return this.ctx.cache.configSection(Hx)??null}get enabled(){return this.definitions?.Enabled===true&&!this.disabled}peek(e){return this.held.get(e)}async getMine(){let e=this.ctx.auth.context?.userID;if(!e)return c;let t=await this.get([e]);return t.ok?a$1(t.data[0]??null):t}async get(e){if(!this.ctx.authedRequest())return c;let n=[...new Set(e.map(r=>r?.trim()).filter(r=>!!r))];if(n.length===0)return a$1([]);let i=new Set,s=[];for(let r of n){let p=this.inflight.get(r);p?i.add(p):s.push(r);}for(let r=0;r<s.length;r+=Ns){let p=s.slice(r,r+Ns),m=this.request(p);for(let R of p)this.inflight.set(R,m);m.finally(()=>{for(let R of p)this.inflight.get(R)===m&&this.inflight.delete(R);}),i.add(m);}for(let r of await Promise.all(i)){if(!r.ok)return r;if(!r.data.Enabled)return a$1([])}return a$1(n.map(r=>this.held.get(r)).filter(r=>!!r))}async getShop(){let e=this.ctx.authedRequest();return e?this.ctx.api.avatar.getShop(e):c}async browseShop(e={}){let t=this.ctx.authedRequest();if(!t)return c;t.Sort=e.sort??"new",e.slot&&(t.Slot=e.slot);let n=e.query?.trim();return n&&(t.Query=n),e.ownedOnly&&(t.OwnedOnly=true),e.source&&(t.Source=e.source),e.cursor&&(t.Cursor=e.cursor),this.ctx.api.avatar.getShop(t)}async buyItem(e,t,n){let i=this.ctx.authedRequest();return i?(i.ItemID=e,i.PriceCredits=t,n&&(i.CreditsConfirmationID=n),this.ctx.api.avatar.buyItem(i)):c}async request(e){let t=this.ctx.authedRequest();if(!t)return c;t.UserIDs=e;let n={};for(let s of e){let r=this.held.get(s);r&&(n[s]=r.rev);}Object.keys(n).length>0&&(t.KnownRevs=n);let i=await this.ctx.api.avatar.getAvatars(t);if(!i.ok)return i;if(this.disabled=!i.data.Enabled,!i.data.Enabled){for(let s of e)this.held.delete(s);return i}if(i.data.Avatars.some(s=>s.NotModified&&this.held.get(s.UserID)?.rev!==s.Rev)){for(let p of e)this.held.delete(p);let s=this.ctx.authedRequest();if(!s)return c;s.UserIDs=e;let r=await this.ctx.api.avatar.getAvatars(s);return r.ok?r.data.Avatars.some(p=>p.NotModified)?b("client","AVATAR_REVISION_MISMATCH"):(this.apply(r.data),r):r}return this.apply(i.data),i}apply(e){let t=[];for(let n of e.Avatars){if(n.NotModified)continue;let i=n.HasAvatar?n.Spec??null:null;this.held.set(n.UserID,{userID:n.UserID,rev:n.Rev,hasAvatar:n.HasAvatar&&!!i,spec:i,items:i?$x(i,e.Items):[]}),t.push(n.UserID);}t.length>0&&this.ctx.emitter.emit("avatar:changed",{userIDs:t});}};function $x(o,e){let t=o.wear;if(!t||typeof t!="object")return [];let n=[];for(let i of Object.values(t))typeof i=="string"&&e[i]&&n.push(e[i]);return n}var js={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},va="idos-app",gh=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()}),yh=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:O.nullish()});var Jx=new Set(["CANCELLED","DECLINED","CLOSED"]),Zx=45e3,Yx=o=>new Promise(e=>setTimeout(e,o)),Fs=class{constructor(e){this.ctx=e;}ctx;get available(){return this.ctx.host.supports.rewardedAds}async showRewarded(e){if(!this.ctx.host.supports.rewardedAds)return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let n=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!n.ok)return {status:"unavailable",reason:n.error};let i=n.data;if(!i.Allowed)return {status:"denied",reason:i.DenyReason??void 0,retryAfterSeconds:i.RetryAfterSeconds??void 0};if(!i.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let s=null;if(i.ProviderID!==va&&(s=this.titleProvider(i.ProviderID),!s))return {status:"unavailable",reason:"NO_WEB_ADS"};let r=await this.ctx.host.showRewardedAd({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:i.RequestID,placementID:e,adUnitID:i.AdUnitID,provider:s});return r.ok?{...await this.awaitReward(i.RequestID,r.via),requestID:i.RequestID}:{status:Jx.has(r.error??"")?"cancelled":"unavailable",reason:r.error}}titleProvider(e){if(!this.ctx.host.supports.titleAds||!e)return null;let n=this.ctx.data.config.getSection("Advertising")?.Providers?.[e];if(!n||n.Enabled===false)return null;let i=this.ctx.host.getClientPlatform(),s=i===j.Android?n.AndroidAppID:i===j.Ios?n.IosAppID:n.WebAppID;return s?{id:e,kind:n.Kind??"AppLovinMax",appKey:s}:null}async awaitReward(e,t){let n=Date.now()+Zx;for(;;){let i=this.ctx.authedRequest();if(!i)return {status:"pending",via:t};let s=await this.ctx.api.advertising.completeView({...i,RequestID:e});if(s.ok&&s.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:s.data.CreditsAwarded??0,via:t};let r=Math.min(Math.max((s.ok?s.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+r>n)return {status:"pending",via:t,reason:s.ok?void 0:s.error};await Yx(r);}}};var Nt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},Xx={Client:"Client",Server:"Server",System:"System"},eb=z.enum(["Client","Server","System"]).catch("Client"),Aa=z.object({Value:z.string().nullish(),UpdatedAt:u.nullish(),Version:z.number().nullish(),LastWriter:eb.nullish(),ExpiresAt:u.nullish()}).passthrough(),Ws=z.record(z.string(),Aa),Rh=z.object({Version:z.number().nullish(),Private:Ws.nullish(),Public:Ws.nullish(),ReadOnly:Ws.nullish()}),Ta=z.object({UserID:z.string().nullish(),Version:z.number().nullish(),Public:Ws.nullish()}),za=z.object({ServerTimeUtc:u.nullish(),Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:u.nullish()}),tb=z.object({Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:u.nullish()}),Ch=z.object({ServerTimeUtc:u.nullish(),Results:z.array(tb).nullish()}),Sh=z.object({ServerTimeUtc:u.nullish(),DeletedCount:z.number().nullish()}),xh=z.object({Results:z.array(Ta).nullish(),NotFoundUserIDs:z.array(z.string()).nullish()}),nb={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},ib=z.enum(["String","Int","Bool","Json"]).catch("String"),sb=z.object({KeyID:z.string(),Bucket:z.string().nullish(),ValueType:ib.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),Ks=z.object({Keys:z.record(z.string(),sb).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),Pt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var rb={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},ob={Title:"Title",Platform:"Platform"},bh=z.object({UserID:z.string(),PublicData:Be.nullish(),Source:z.enum(["Title","Platform"]).nullish()});var ab=z.object({StageLevel:z.number().nullish(),SpecialPlayedCount:z.number().nullish()}),Dh=z.object({UserID:z.string(),IsSelf:z.boolean().nullish(),PublicData:Be.nullish(),Characters:z.record(z.string(),Vn).nullish(),StrongestCharacterID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),Board:ab.nullish(),PublicCustomData:z.record(z.string(),Aa).nullish(),Relation:z.enum(["None","Friend","RequestSent","RequestReceived"]).nullish(),FriendSource:z.enum(["Title","Platform"]).nullish(),BlockedByMe:z.boolean().nullish(),FriendRequestsAllowed:z.boolean().nullish()});var Qn=z.object({Friends:z.array(bh).nullish()}),lb=z.object({FriendsCount:z.number().nullish(),IncomingRequestsCount:z.number().nullish(),OutgoingRequestsCount:z.number().nullish()}),Hn=z.object({TargetUserID:z.string().nullish(),Status:z.string().nullish(),Target:bh.nullish(),Counters:lb.nullish()}),ub={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},cb={Like:"Like",Favorite:"Favorite"},pb={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},hb={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},db={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived",ArenaDefeat:"ArenaDefeat"},mb=z.object({Key:z.string().nullish(),DisplayName:z.string().nullish(),AvatarUrl:z.string().nullish()}).passthrough(),fb=z.object({Id:z.string(),Verb:z.string().nullish(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),Count:z.number().nullish(),LastActors:z.array(mb).nullish(),Payload:z.object({Title:z.string().nullish(),Excerpt:z.string().nullish(),ImageUrl:z.string().nullish()}).passthrough().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),OccurredAt:u.nullish(),OwnerImpact:O.nullish(),IsBlocked:z.boolean().nullish(),TargetObjectName:z.string().nullish()}).passthrough(),Ih=z.object({Items:z.array(fb).nullish(),HasMore:z.boolean().nullish(),NextBeforeUpdatedAt:z.string().nullish(),NextBeforeID:z.string().nullish(),UnreadCount:z.number().nullish(),SeenAt:u.nullish()}).passthrough(),$n=z.object({UnreadCount:z.number().nullish(),SeenAt:u.nullish()}).passthrough(),gb=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(),Zt=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Counts:gb.nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish(),Following:z.boolean().nullish(),Blocked:z.boolean().nullish()}).passthrough(),Ph=z.object({Items:z.array(Zt).nullish()}).passthrough(),wa={HasMore:z.boolean().nullish(),NextCursorAt:z.string().nullish(),NextCursorID:z.string().nullish()},yb=z.object({UserID:z.string(),PublicData:Be.nullish(),Mutual:z.boolean().nullish(),Since:u.nullish()}).passthrough(),Qs=z.object({Items:z.array(yb).nullish(),...wa}).passthrough(),Rb=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Kind:z.string().nullish(),At:u.nullish()}).passthrough(),vh=z.object({Items:z.array(Rb).nullish(),...wa}).passthrough(),Hs=z.object({CommentID:z.string(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),ParentCommentID:z.string().nullish(),AuthorUserID:z.string().nullish(),AuthorPublicData:Be.nullish(),Text:z.string().nullish(),Status:z.string().nullish(),Pinned:z.boolean().nullish(),CreatedAt:u.nullish(),EditedAt:u.nullish(),Likes:z.number().nullish(),Replies:z.number().nullish(),Liked:z.boolean().nullish(),IsMine:z.boolean().nullish()}).passthrough(),Ah=z.object({Items:z.array(Hs).nullish(),...wa,TotalCount:z.number().nullish()}).passthrough(),Th=z.object({CommentID:z.string().nullish(),Deleted:z.boolean().nullish()}).passthrough(),zh=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish(),AutoHidden:z.boolean().nullish()}).passthrough(),wh=z.object({CommentsEnabled:z.boolean().nullish(),CommentableTypes:z.array(z.string()).nullish(),CommentMaxLength:z.number().nullish(),CommentMaxLinks:z.number().nullish()}).passthrough(),Cb="FRIENDS_FROM_PLATFORM",Sb={Off:"Off",Default:"Default",Always:"Always"},xb={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},kh=z.object({Profile:z.enum(["Off","Default","Always"]).nullish(),Friends:z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:z.boolean().nullish()}).passthrough(),be={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report",GetPlayerProfile:"GetPlayerProfile"};var ka={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},$s=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ka,{schema:$n,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 n=await this.ctx.api.social.getRecommendedFriends(t);return n.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",n.data),n}async getPlayerProfile(e){if(!e)return b("client","TargetUserID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.getPlayerProfile(t);return n.ok&&this.ctx.emitter.emit("social:playerProfileLoaded",n.data),n}async sendFriendRequest(e){if(!e)return b("client","TargetUserID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.sendFriendRequest(t);return n.ok&&(n.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",n.data)),n}async acceptFriendRequest(e){if(!e)return b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.acceptFriendRequest(t);return n.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",n.data)),n}async declineFriendRequest(e){if(!e)return b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.declineFriendRequest(t);return n.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",n.data)),n}async removeFriend(e){if(!e)return b("client","FriendUserID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.removeFriend(t);return n.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRemoved",n.data)),n}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return c;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let n=await this.ctx.api.social.getInbox(t);return n.ok&&this.ctx.emitter.emit("social:inboxLoaded",n.data),n}getInboxUnread(e){return this.ctx.cache.read(ka,()=>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(ka,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let n=this.ctx.authedRequest();return n?(n.ReactionKind=e,n.EntityType=t.entityType,this.applyPage(n,t.cursor,t.limit),this.ctx.api.social.getMyReactions(n)):c}async getEntityStates(e,t){if(!t?.length)return b("client","EntityIDs are required.");let n=this.ctx.authedRequest();return n?(n.EntityType=e,n.EntityIDs=t,this.ctx.api.social.getEntityStates(n)):c}async addComment(e,t,n,i){let s=this.targetRequest(e,t);if("ok"in s)return s;if(!n?.trim())return b("client","Text is required.");s.Text=n,s.ParentCommentID=i;let r=await this.ctx.api.social.addComment(s);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 n=this.ctx.authedRequest();if(!n)return c;n.CommentID=e,n.Text=t;let i=await this.ctx.api.social.editComment(n);return i.ok&&this.ctx.emitter.emit("social:commentEdited",i.data),i}async deleteComment(e){if(!e)return b("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.CommentID=e;let n=await this.ctx.api.social.deleteComment(t);return n.ok&&this.ctx.emitter.emit("social:commentDeleted",n.data),n}async getComments(e,t,n={}){let i=this.targetRequest(e,t);return "ok"in i?i:(i.ParentCommentID=n.parentCommentID,this.applyPage(i,n.cursor,n.limit),this.ctx.api.social.getComments(i))}async report(e,t,n,i){let s=this.targetRequest(e,t);if("ok"in s)return s;if(!n)return b("client","ReportReason is required.");s.ReportReason=n,s.ReportComment=i;let r=await this.ctx.api.social.report(s);return r.ok&&this.ctx.emitter.emit("social:reported",r.data),r}async mutate(e,t,n,i){let s=this.targetRequest(t,n);if("ok"in s)return s;s.ReactionKind=i;let r=await this.ctx.api.social[e](s);return r.ok&&this.ctx.emitter.emit("social:entityStateChanged",r.data),r}async page(e,t,n){let i=this.ctx.authedRequest();return i?(this.applyPage(i,t,n),this.ctx.api.social[e](i)):c}applyPage(e,t,n){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=n;}targetRequest(e,t){if(!e)return b("client","EntityType is required.");if(!t)return b("client","EntityID is required.");let n=this.ctx.authedRequest();return n?(n.EntityType=e,n.EntityID=t,n):c}};var Mh="TimedBoost";function bb(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Js=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Mh,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.timedBoost.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Mh,i.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",i.data)),i}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 n=e.trim();if(!bb(n))return b("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),BoostID:n,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${n}_${a()}`},s=await this.ctx.api.timedBoost.activate(i);if(s.ok&&!s.data.CreditsConfirmation){let r=s.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 s}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 Db="UserCustomData";function Oh(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Zs=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(Db,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 n=this.ctx.authedRequest();if(!n)return c;n.TargetUserID=t;let i=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(n);return i.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",i.data),i}async setPrivateData(e,t){return this.setData(e,t,Nt.Private)}async setPublicData(e,t){return this.setData(e,t,Nt.Public)}async setData(e,t,n){let i=e.trim();if(!Oh(i))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 s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Value:t},p=await(n===Nt.Private?this.ctx.api.userCustomData.setPrivateData(s):this.ctx.api.userCustomData.setPublicData(s));if(p.ok){let m=p.data;this.ctx.data.user.patchUserCustomDataKey(n,m.KeyID,t,m.Version??0,m.ExpiresAt),this.ctx.emitter.emit(n===Nt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",m);}return p}async deleteKey(e,t){let n=e.trim();if(!Oh(n))return b("client",'KeyID is required and must not contain "." or "$".');if(t!==Nt.Private&&t!==Nt.Public)return b("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Bucket:t},s=await this.ctx.api.userCustomData.deleteKey(i);return s.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,n),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),s}async batchSet(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},n=await this.ctx.api.userCustomData.batchSet(t);if(n.ok){for(let i of n.data.Results??[]){let s=i.Bucket??Nt.Private,r=e.find(p=>p.Bucket===s&&p.KeyID===i.KeyID);r&&this.ctx.data.user.patchUserCustomDataKey(s,i.KeyID,r.Value,i.Version??0,i.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",n.data);}return n}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},n=await this.ctx.api.userCustomData.batchDelete(t);if(n.ok){for(let i of e)this.ctx.data.user.removeUserCustomDataKey(i.Bucket,i.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",n.data);}return n}async batchGetPublicUserCustomDataOf(e){if(!e.length)return b("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return c;t.TargetUserIDs=e;let n=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return n.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",n.data),n}};var Ib="TitleCustomDataDefinitions",Eh=50;function Pb(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}function Ma(o){if(o.ExpiresAt==null)return false;let e=Date.parse(o.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function vb(o){let e={};for(let[t,n]of Object.entries(o))Ma(n)||(e[t]=n);return e}var Ys=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(Ib,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 n=await this.ctx.api.titleCustomData.getPublicTitleData(t);return n.ok&&this.absorb(n.data),n}async getPublicTitleDataKeys(e){let t=e.map(s=>s.trim()).filter(s=>s.length>0);if(!t.length)return b("client","At least one KeyID is required.");if(t.some(s=>!Pb(s)))return b("client",'KeyID must not contain "." or "$".');if(t.length>Eh)return b("client",`At most ${Eh} keys per call \u2014 request them in chunks.`);let n=this.ctx.authedRequest();if(!n)return c;n.KeyIDs=t;let i=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(n);return i.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",i.data),i}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Ma(t))return t.Value;let n=this.staticCache[e];if(n?.Value!=null&&!Ma(n))return n.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=vb(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 Xs=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 Ab={Fast:"Fast",Sequential:"Sequential"},Tb={Instant:"Instant",Timed:"Timed"};var zb={Hit:"Hit",Blocked:"Blocked"},wb=z.object({SlotIndex:z.number(),Level:z.number().nullish(),IsDamaged:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish()}).passthrough(),kb=z.object({Symbol:z.union([z.string(),z.number()]).nullish(),OnOpenBonus:$.nullish(),BonusTag:z.string().nullish()}).passthrough();z.object({ElapsedSeconds:z.number().nullish(),Reward:$.nullish()}).passthrough();var Mb=z.object({RequiredValue:z.number().nullish(),Reward:$.nullish()}).passthrough(),Ob=z.object({Reward:$.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(Mb).nullish(),Rate:Ob.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 qh=z.object({}).passthrough().transform(o=>o),Uh=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),Ze=z.object({Operation:O.nullish(),ScaleWithRollMultiplier:z.boolean().nullish()}).passthrough(),Eb=z.object({Count:z.number().nullish(),Sides:z.number().nullish()}).passthrough(),qb=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(),Ub=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(),Lb=z.object({CostMatrix:z.array(z.array(z.number())).nullish(),PerBoardGrowth:z.number().nullish(),EconomyScale:z.number().nullish(),ScaledResources:ce.nullish()}).passthrough(),Lh=z.object({SlotIndex:z.number().nullish(),Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxLevel:z.number().nullish(),MaxLevelReward:$.nullish()}).passthrough(),Bb=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(),Gb=z.object({Tiles:z.record(z.string(),Bb).nullish()}).passthrough(),Nb=z.object({Weight:z.number().nullish(),Bonus:Ze.nullish(),Tag:z.string().nullish()}).passthrough(),_b=z.object({Weight:z.number().nullish(),Tag:z.string().nullish(),MinBonusCells:z.number().nullish(),MaxBonusCells:z.number().nullish(),BonusPool:z.array(Nb).nullish(),GuaranteedBonus:Ze.nullish(),IsJackpot:z.boolean().nullish(),JackpotFinalMultiplier:z.number().nullish(),JackpotSymbolDistribution:z.record(z.string(),z.number()).nullish()}).passthrough(),Vb=z.object({Variants:z.array(_b).nullish()}).passthrough(),jb=z.object({Weight:z.number().nullish(),OutcomeID:z.string().nullish(),Reward:Ze.nullish(),ForceAction:z.string().nullish(),SpecialModeID:z.string().nullish()}).passthrough(),Fb=z.object({Outcomes:z.array(jb).nullish()}).passthrough(),Bh=z.object({PerAdMultiplierRange:Uh.nullish(),MaxAdViews:z.number().nullish(),AdCreditCost:z.number().nullish(),FormulaKind:z.string().nullish(),ApplyMultiplierOnEarlyClaim:z.boolean().nullish(),PremiumMultiplier:z.number().nullish(),MinPremiumTier:z.number().nullish()}).passthrough(),Wb=z.object({ElapsedSeconds:z.number().nullish(),Reward:Ze.nullish()}).passthrough(),Kb=z.object({Tiers:z.array(Wb).nullish(),TierMode:z.string().nullish(),BelowFirstTierReward:Ze.nullish()}).passthrough(),Qb=z.object({RequiredValue:z.number().nullish(),Reward:Ze.nullish()}).passthrough(),Hb=z.object({Reward:Ze.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough(),$b=z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(Qb).nullish(),Rate:Hb.nullish()}).passthrough(),Gh=z.object({MetricsByID:z.record(z.string(),$b).nullish()}).passthrough(),Jb=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:Ze.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:he.nullish(),Multipliers:Bh.nullish(),Gradation:Kb.nullish(),RunStats:Gh.nullish()}).passthrough(),Zb=z.object({Choices:z.array(Jb).nullish(),OfferExpireSeconds:z.number().nullish(),ClaimExpireSeconds:z.number().nullish()}).passthrough(),Yb=z.object({Chance:z.number().nullish(),RequiredOutcome:z.string().nullish(),Reward:Ze.nullish(),Tag:z.string().nullish()}).passthrough(),Xb=z.object({OnPassStart:Ze.nullish(),OnTileLanding:z.record(z.string(),Ze).nullish(),OnAttack:z.record(z.string(),Ze).nullish(),OnRaid:z.record(z.string(),Ze).nullish(),OnBuild:Ze.nullish(),OnStageComplete:Ze.nullish(),OnAttackBonusDrops:z.array(Yb).nullish(),ChanceTablesByID:z.record(z.string(),Fb).nullish(),SpecialModesByID:z.record(z.string(),Zb).nullish()}).passthrough(),Nh=z.object({BaseAttackReward:$.nullish(),BaseRaidReward:$.nullish(),MaxRollMultiplier:z.number().nullish(),MaxShields:z.number().nullish(),Buildings:z.array(Lh).nullish(),HeistGridBonusConfig:Vb.nullish(),StageOperations:Xb.nullish(),TileLandingMultiplier:Uh.nullish(),EconomyOverride:Lb.nullish()}).passthrough(),eD=z.object({Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BoardTemplateID:z.string().nullish(),Buildings:z.array(Lh).nullish(),StageTemplateID:z.string().nullish(),CostMatrixTemplateID:z.string().nullish(),UnitValue:z.number().nullish(),Override:Nh.nullish()}).passthrough(),tD=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(),nD=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(),iD=z.object({Enabled:z.boolean().nullish(),Sources:z.array(z.string()).nullish(),AdMultiplier:z.number().nullish(),PremiumMultiplier:z.number().nullish(),AdCreditCost:z.number().nullish(),AdDailyLimit:z.number().nullish(),PremiumDailyLimit:z.number().nullish(),TtlSeconds:z.number().nullish(),MinPremiumTier:z.number().nullish()}).passthrough(),er=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(),Gb).nullish(),StageTemplatesByID:z.record(z.string(),Nh).nullish(),StagesByLevel:z.record(z.string(),eD).nullish(),SoftCurrencyID:z.string().nullish(),ProceduralEconomy:Ub.nullish(),Dice:Eb.nullish(),Bots:qb.nullish(),Targeting:tD.nullish(),BotRaids:nD.nullish(),RewardBoost:iD.nullish()}).passthrough(),sD=z.object({IsActive:z.boolean().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AnchorUtc:u.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(),Ve).nullish(),GrandPrize:$.nullish()}).passthrough(),tr=z.object({Board:er.nullish(),CommunityChest:sD.nullish()}).passthrough(),_h=z.object({AttackerGainByOutcome:z.record(z.string(),ce).nullish()}).passthrough(),rD=z.object({TargetUserID:z.string().nullish(),IsBot:z.boolean().nullish(),PublicData:Be.nullish(),TargetBuildingStates:z.array(wb).nullish(),TargetHasShield:z.boolean().nullish(),TargetStageLevel:z.number().nullish(),RaidRewardPreview:_h.nullish()}).passthrough(),oD=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:Ze.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:he.nullish(),Multipliers:Bh.nullish(),RunStats:Gh.nullish()}).passthrough(),aD=z.object({ModeID:z.string().nullish(),Choices:z.array(oD).nullish()}).passthrough(),lD=z.object({GroupID:z.string().nullish(),Delta:H.nullish(),NewProgress:H.nullish(),MaxProgress:H.nullish(),UnlockedMilestoneIDs:z.array(z.string()).nullish(),Completed:z.boolean().nullish()}).passthrough(),Vh=z.object({UsedMultiplier:z.number().nullish(),Steps:z.number().nullish(),DiceValues:z.array(z.number()).nullish(),OldPosition:z.number().nullish(),NewPosition:z.number(),CyclesCompletedDelta:H.nullish(),LandedTileType:z.string().nullish(),Operation:O.nullish(),Inventory:Q.nullish(),ActionRequired:z.string().nullish(),ActionData:rD.nullish(),SpecialModeOffer:aD.nullish(),CommunityChestContribution:lD.nullish()}).passthrough(),nr={Ad:"Ad",Premium:"Premium"},jh=z.object({BoostID:z.string().nullish(),Source:z.string().nullish(),ExpiresAtUtc:u.nullish(),AdMultiplier:z.number().nullish(),PremiumMultiplier:z.number().nullish(),AdCreditCost:z.number().nullish(),MinPremiumTier:z.number().nullish(),AdRemainingToday:z.number().nullish(),PremiumRemainingToday:z.number().nullish(),BaseEntries:z.array(vt).nullish()}).passthrough(),Fh=z.object({BoostID:z.string().nullish(),Mode:z.string().nullish(),Multiplier:z.number().nullish(),AlreadyApplied:z.boolean().nullish(),Operation:O.nullish(),Inventory:Q.nullish(),AdRemainingToday:z.number().nullish(),PremiumRemainingToday:z.number().nullish()}).passthrough(),Wh=z.object({Outcome:z.string().nullish(),IsBotTarget:z.boolean().nullish(),BuildingIndexHit:z.number().nullish(),Operation:O.nullish(),Inventory:Q.nullish(),DualResult:Ut.nullish(),RewardBoost:jh.nullish()}).passthrough(),Oa=z.object({Status:z.string().nullish(),Outcome:z.string().nullish(),FoundSymbol:z.union([z.string(),z.number()]).nullish(),FoundBonus:$.nullish(),OpenedIndex:z.number().nullish(),AttemptsLeft:z.number().nullish(),RaidLayout:z.array(kb).nullish(),HeistVariantTag:z.string().nullish(),IsJackpot:z.boolean().nullish(),Operation:O.nullish(),Inventory:Q.nullish(),DualResult:Ut.nullish(),RaidRewardPreview:_h.nullish(),RewardBoost:jh.nullish()}).passthrough(),Kh=z.object({BuiltIndex:z.number(),NewLevel:z.number().nullish(),StageComplete:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish(),Operation:O.nullish(),Inventory:Q.nullish()}).passthrough(),Qh=z.object({CreditsConfirmation:ge.nullish(),Mode:z.union([z.string(),z.number()]).nullish(),Operation:O.nullish(),Inventory:Q.nullish(),DurationSeconds:z.number().nullish(),StartedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish()}).passthrough(),Hh=z.object({AdViewsUsed:z.number().nullish(),RolledMultiplier:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),RemainingAdViews:z.number().nullish(),PremiumApplied:z.boolean().nullish()}).passthrough(),uD=z.object({MetricID:z.string().nullish(),ReachedTierIndex:z.number().nullish(),RequiredValue:z.number().nullish(),RewardUnits:z.number().nullish()}).passthrough(),$h=z.object({FinalMultiplier:z.number().nullish(),AdViewsUsed:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),IsEarlyClaim:z.boolean().nullish(),ReachedTierIndex:z.number().nullish(),Operation:O.nullish(),Inventory:Q.nullish(),AcceptedRunStats:z.record(z.string(),z.number()).nullish(),RunStatAwards:z.array(uD).nullish(),RunStatsClamped:z.boolean().nullish(),RunStatGrant:$.nullish()}).passthrough(),cD={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Jh=z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),pD={Active:"Active",Left:"Left",Replaced:"Replaced"},hD=z.enum(["Active","Left","Replaced"]).catch("Active"),dD=z.object({CurrentProgress:H.nullish(),MaxProgress:H.nullish()}).passthrough(),mD=z.object({UserID:z.string().nullish(),PublicData:Be.nullish(),IsBot:z.boolean().nullish(),ContributionPoints:H.nullish(),MilestoneClaims:z.record(z.string(),Kl).nullish(),GrandPrizeClaimed:z.boolean().nullish(),MemberStatus:hD.nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),Zh=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),RoundIndex:z.number().nullish(),Members:z.array(mD).nullish(),SharedProgress:dD.nullish(),Status:Jh.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:z.number().nullish()}).passthrough(),fD=z.object({GroupID:z.string().nullish(),RoundIndex:z.number().nullish(),FinalStatus:Jh.nullish(),GrandPrizeReceived:z.boolean().nullish(),FinishedAtUtc:u.nullish()}).passthrough(),gD=z.object({ActiveGroupID:z.string().nullish(),ActiveRoundIndex:z.number().nullish(),History:z.array(fD).nullish()}).passthrough(),Yh=z.object({ServerTimeUtc:u.nullish(),UserState:gD.nullish(),ActiveGroup:Zh.nullish(),SecondsRemaining:H.nullish()}),Xh=z.object({ServerTimeUtc:u.nullish(),Group:Zh.nullish(),SecondsRemaining:H.nullish()}),Ea=z.object({ServerTimeUtc:u.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),ed=z.object({ServerTimeUtc:u.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),Fe={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",BoardRewardBoostApply:"BoardRewardBoostApply",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var yD=15,RD="GameLoop",td="BoardDefinition",Jn="InventoryV2",CD="GameLoop",ir=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(RD,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let n=this.ctx.cache.configSection(td,t);if(n)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n),a$1(n);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.gameLoop.getBoardDefinition(i,e);return s.ok&&(this.ctx.data.config.patchSection(td,s.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",s.data)),s}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return b("client","stageLevel must be > 0.");let n=this.ctx.authedRequest();if(!n)return c;n.StageLevel=e;let i=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(n,t);return i.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",i.data),i}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return c;let t=false,n=this.ctx.emitter.on("user:stateVersions",({versions:s})=>{s[Jn]!==void 0&&(t=true);}),i;try{i=await this.ctx.api.gameLoop.getUserBoardState(e);}finally{n();}return i.ok&&(this.ctx.data.user.applyBoardState(i.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",i.data),t&&(this.ctx.cache.invalidateState([Jn]),this.ctx.cache.ensureState([Jn]),this.ctx.emitter.emit("user:changedElsewhere",{containers:[Jn]}))),i}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 n={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${a()}`},i=await this.ctx.api.gameLoop.boardLoopRoll(n);if(i.ok){let s=i.data,r=Ru(new Date,yD);this.ctx.data.user.patchBoardState(p=>{p.Position=s.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(s.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),s.ActionRequired&&s.ActionData?p.Pending={Type:s.ActionRequired,TargetUserID:s.ActionData.TargetUserID,TargetPublicData:s.ActionData.PublicData,TargetBuildingStates:s.ActionData.TargetBuildingStates??void 0,TargetHasShield:s.ActionData.TargetHasShield??void 0,RollMultiplier:s.UsedMultiplier??1,ExpiresAtUtc:r}:s.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:s.UsedMultiplier??1,ExpiresAtUtc:r,Special:{ModeID:s.SpecialModeOffer.ModeID??void 0,Choices:s.SpecialModeOffer.Choices??void 0}});}),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),s.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",s);}return i}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return c;let n={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${a()}`},i=await this.ctx.api.gameLoop.boardLoopAttack(n);if(i.ok){let s=i.data;this.ctx.data.user.clearBoardPending(),s.IsBotTarget&&s.Operation?this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs):!s.IsBotTarget&&s.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(s.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",s);}else await this.getUserBoardState();return i}async boardLoopRaid(e,t){if(e<0||e>11)return b("client","digIndex must be between 0 and 11.");let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${n.userID}_${a()}`},s=await this.ctx.api.gameLoop.boardLoopRaid(i);if(s.ok){let r=s.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 s}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 n={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${a()}`},i=await this.ctx.api.gameLoop.boardLoopRaidFast(n);if(i.ok){let s=i.data;s.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(s)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",s);}else await this.getUserBoardState();return i}async boardLoopBuild(e){if(e<0)return b("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return c;let n={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${a()}`},i=await this.ctx.api.gameLoop.boardLoopBuild(n);if(!i.ok&&i.reason==="server"&&await this.ctx.cache.ensureState([Jn,CD],{force:true}),i.ok){let s=i.data;s.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(s.BuiltIndex,r=>{s.NewLevel!=null&&(r.Level=s.NewLevel),r.IsDamaged=false,s.MaxLevelRewardClaimed&&(r.MaxLevelRewardClaimed=true);}),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",s);}return i}async boardSpecialChoose(e,t,n){if(!e)return b("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:n,RelatedEntityID:`special_choose_${i.userID}_${a()}`},r=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(r.ok&&!r.data.CreditsConfirmation){let p=r.data;p.Mode==="Instant"||p.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(R=>{R.ChoiceID=e,R.ChosenMode=p.Mode??"Timed",R.StartedAtUtc=p.StartedAtUtc??null,R.DurationSeconds=p.DurationSeconds??null,R.AdViewsUsed=0;}),p.Operation&&this.ctx.data.user.applyResourcesWithDelta(p.Operation,p.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",p);}return r}async boardSpecialApplyMultiplier(e,t=nr.Ad){let n=this.ctx.auth.context;if(!n)return c;let i=t===nr.Premium,s={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_${i?"vip":"ad"}_${n.userID}_${a()}`,...i?{BoostMode:nr.Premium}:{}},r=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(s);if(r.ok){let p=r.data;this.ctx.data.user.patchBoardSpecialPending(m=>{m.AdViewsUsed=p.AdViewsUsed??0,m.AccumulatedMultiplier=p.AccumulatedMultiplier??0,p.PremiumApplied&&(m.PremiumApplied=true);}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",p);}return r}async boardRewardBoostApply(e,t){if(!this.ctx.auth.context)return c;if(!e)return b("client","boostID must not be empty.");let i={...this.ctx.buildAuthedBaseRequest(),BoostID:e,BoostMode:t,RelatedEntityID:`boost_${e}_${t}`},s=await this.ctx.api.gameLoop.boardRewardBoostApply(i);if(s.ok){let r=s.data;!r.AlreadyApplied&&r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardRewardBoostApplied",r);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return c;let n={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${a()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},i=await this.ctx.api.gameLoop.boardSpecialClaim(n);if(i.ok){let s=i.data;this.ctx.data.user.clearBoardPending(),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",s);}return i}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return 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 n=t.data.Group;n?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:n.GroupID,ActiveRoundIndex:n.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return b("client","milestoneID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},i=await this.ctx.api.gameLoop.claimCommunityChestMilestone(n);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",i.data)),i}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",n.data)),n}async leaveCommunityChest(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.gameLoop.leaveCommunityChest(t);return n.ok&&(n.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",n.data)),n}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var sr=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,n,i){let s=e.trim();if(!s)return b("client","FunctionName is required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),FunctionName:s,FunctionParameter:t,RevisionSelection:n,SpecificRevision:i},p=await this.ctx.api.cloudCode.execute(r);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var SD={EVM:"EVM",Solana:"Solana"},xD=z.enum(["EVM","Solana"]).catch("EVM"),bD={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},DD=z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),ID={Token:"Token",Nft:"Nft"},nd=z.enum(["Token","Nft"]).catch("Token"),PD={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},vD=z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),AD={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},TD=z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),zD={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},qa=z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),id={GameTopUp:"game_topup",CommunityReward:"community_reward"};function rr(o){let e=o?.trim();return e||id.GameTopUp}var wD={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},sd=z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),kD=z.object({ContractAddress:z.string().nullish(),ItemCatalogID:z.string().nullish(),DisplayName:z.string().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),rd=z.object({Ios:z.boolean().nullish(),Android:z.boolean().nullish(),Web:z.boolean().nullish()}).passthrough(),MD=z.object({NetworkID:z.string().nullish(),DisplayName:z.string().nullish(),Type:xD.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:rd.nullish(),NftCollections:z.array(kD).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(),OD=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:rd.nullish()}).passthrough(),ED=z.object({MinAccountAgeDays:z.number().nullish(),MultiAccountCheckEnabled:z.boolean().nullish(),BanOnSharedWithdrawalAddress:z.boolean().nullish(),PendingWithdrawalTtlHours:z.number().nullish()}).passthrough(),qD={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},UD=z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),od=z.object({Enabled:z.boolean().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),MinBalance:ne.nullish(),BalanceSource:UD.nullish(),DenyMessage:z.string().nullish()}).passthrough(),LD=z.object({Enabled:z.boolean().nullish(),WalletConnectProjectId:z.string().nullish(),ShowOnLoginScreen:z.boolean().nullish()}).passthrough(),BD={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Zn=z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),GD=z.object({Mode:Zn.nullish(),TokenGates:z.array(od).nullish()}).passthrough(),Ua=z.object({SystemState:OD.nullish(),Networks:z.record(z.string(),MD).nullish(),AccountSafety:ED.nullish(),WalletLogin:LD.nullish(),PlayAccess:GD.nullish(),IframeConnectHosts:z.array(z.string()).nullish()}).passthrough(),ND=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),LinkedAt:u.nullish(),LastUsedAt:u.nullish(),LinkType:DD.nullish(),IsSignatureVerified:z.boolean().nullish()}).passthrough(),ad=z.object({TitleTransactionID:z.string().nullish(),Type:nd.nullish(),NetworkID:z.string().nullish(),AssetID:z.string().nullish(),Amount:ne.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),_D=z.object({Status:vD.nullish(),Tier:TD.nullish(),VerifiedAt:u.nullish(),ExpiresAt:u.nullish(),RejectedAt:u.nullish(),ProviderReference:z.string().nullish(),RejectionReason:z.string().nullish()}).passthrough(),VD=z.object({CurrencyID:z.string().nullish(),Deposits:z.number().nullish(),DepositsVolumeNative:ne.nullish(),DepositsVolumeUsd:ne.nullish(),Withdrawals:z.number().nullish(),WithdrawalsVolumeNative:ne.nullish(),WithdrawalsVolumeUsd:ne.nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),jD=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),TotalDepositsVolumeUsd:ne.nullish(),TotalWithdrawalsVolumeUsd:ne.nullish(),PerCurrency:z.record(z.string(),VD).nullish()}).passthrough(),FD=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:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),WD=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),PerCollection:z.record(z.string(),FD).nullish()}).passthrough(),KD=z.object({Tokens:jD.nullish(),Nfts:WD.nullish()}).passthrough(),La=z.object({CurrencyID:z.string().nullish(),Balance:ne.nullish(),MinBalance:ne.nullish()}).passthrough(),Yt=z.object({Granted:z.boolean(),Mode:Zn.nullish(),Error:z.string().nullish(),WalletRequired:z.boolean().nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),GrantedUntil:u.nullish(),Balances:z.array(La).nullish()}).passthrough(),QD=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:u.nullish(),Passed:z.boolean().nullish(),GrantedUntil:u.nullish(),Error:z.string().nullish(),Balances:z.array(La).nullish()}).passthrough(),HD=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CanUnlink:z.boolean().nullish()}).passthrough(),ld=z.object({Mode:Zn.nullish(),TokenGates:z.array(od).nullish(),WalletLoginEnabled:z.boolean().nullish(),CanLinkWallet:z.boolean().nullish(),WalletsFromPlatformProfile:z.boolean().nullish(),LinkedWallets:z.array(HD).nullish(),Status:Yt.nullish()}).passthrough(),$D=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:u.nullish(),LoggedInAt:u.nullish(),GatePassed:z.boolean().nullish(),GatedBalances:z.array(La).nullish()}).passthrough(),JD=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),UnlinkedAt:u.nullish()}).passthrough(),ZD=z.object({Version:z.number().nullish(),Stats:KD.nullish(),LinkedWallets:z.record(z.string(),ND).nullish(),LastWalletLogin:$D.nullish(),PlayAccess:QD.nullish(),PendingWithdrawals:z.array(ad).nullish(),Kyc:_D.nullish(),FirstActivityAt:u.nullish(),LastActivityAt:u.nullish(),IsFlagged:z.boolean().nullish(),FlagReason:z.string().nullish(),UnlinkedWallets:z.array(JD).nullish()}).passthrough(),YD=z.object({CurrencyID:z.string(),AmountDelta:ne,FrozenDelta:ne,UpdatedAt:u}).passthrough(),Tn=z.object({CryptoBalances:z.record(z.string(),YD).nullish(),PendingAdded:ad.nullish(),PendingRemovedIDs:z.array(z.string()).nullish()}).passthrough(),XD=z.object({Amount:ne,Frozen:ne,CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough().transform(o=>o),eI=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.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:sd.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:ne.nullish(),Status:qa.nullish(),SignatureData:z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),TokenID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountUsd:ne.nullish(),NetPayoutAmount:ne.nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:u.nullish(),BurnAmount:z.number().nullish(),RefundedAt:u.nullish(),RefundCheckedAt:u.nullish()}).passthrough(),tI=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.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:sd.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:ne.nullish(),Status:qa.nullish(),SignatureData:z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.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:u.nullish()}).passthrough(),ud=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),Ba=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(ud).nullish(),Signature:z.string().nullish()}).passthrough(),Ga=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(ud).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(),cd=z.object({Blockchain:Ua.nullish(),CryptoCurrencies:z.record(z.string(),ha).nullish()}).passthrough(),pd=z.object({State:ZD.nullish(),CryptoBalances:z.record(z.string(),XD).nullish()}).passthrough(),hd=z.object({ServerTimeUtc:u.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:ne.nullish(),AmountUsd:ne.nullish(),StateDelta:Tn.nullish()}).passthrough(),dd=z.object({ServerTimeUtc:u.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:O.nullish(),Inventory:Q.nullish()}).passthrough(),md=z.object({ServerTimeUtc:u.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:ne.nullish(),NetAmountNative:ne.nullish(),BurnAmountNative:ne.nullish(),AmountUsd:ne.nullish(),ExpiresAt:u.nullish(),EvmSignature:Ba.nullish(),SolanaSignature:Ga.nullish(),StateDelta:Tn.nullish(),ChainID:z.number().nullish()}).passthrough(),fd=z.object({ServerTimeUtc:u.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:u.nullish(),Resources:O.nullish(),EvmSignature:Ba.nullish(),SolanaSignature:Ga.nullish(),StateDelta:Tn.nullish(),Inventory:Q.nullish()}).passthrough(),gd=z.object({TokenTransactions:z.array(eI).nullish(),NFTTransactions:z.array(tI).nullish(),RefundedIDs:z.array(z.string()).nullish()}).passthrough(),Na=z.object({ServerTimeUtc:u.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:ne.nullish(),AmountUsd:ne.nullish(),Target:z.string().nullish()}).passthrough(),yd=z.object({TitleTransactionID:z.string().nullish(),Kind:nd.nullish(),EvmSignature:Ba.nullish(),SolanaSignature:Ga.nullish()}).passthrough(),Rd=z.object({TitleTransactionID:z.string().nullish(),OnChainTxHash:z.string().nullish(),Status:qa.nullish(),StateDelta:Tn.nullish()}).passthrough(),nt={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 nI="Blockchain",Cd="Blockchain:Definitions",or=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Cd,e);if(t)return a$1(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let n=this.ctx.authedRequest();if(!n)return c;let i=this.ctx.api.blockchain.getDefinitions(n).then(s=>(s.ok&&(this.ctx.data.config.patchSection(nI,s.data.Blockchain),this.ctx.data.config.patchSection(Cd,s.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",s.data)),s)).finally(()=>{this.definitionsInflight===i&&(this.definitionsInflight=null);});return this.definitionsInflight=i,i}async getUserState(){let e=this.ctx.authedRequest();if(!e)return 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 n=this.ctx.authedRequest();if(!n)return c;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.depositToken(n);return i.ok&&(this.ctx.data.user.applyBlockchainStateDelta(i.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",i.data)),i}async depositNFT(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return c;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.depositNFT(n);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",i.data)),i}async requestTokenWithdrawal(e,t,n,i,s){if(!e)return b("client","CurrencyID is required.");if(!t)return b("client","NetworkID is required.");if(!n)return b("client","WalletAddress is required.");if(!i)return b("client","Amount is required.");let r=this.ctx.authedRequest();if(!r)return c;r.CurrencyID=e,r.NetworkID=t,r.WalletAddress=n,r.Amount=i,r.Category=rr(s);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,n,i,s,r,p){if(!e)return b("client","ItemID is required.");if(!t)return b("client","NetworkID is required.");if(!n)return b("client","WalletAddress is required.");if(!i)return b("client","Amount is required.");let m=this.ctx.authedRequest();if(!m)return c;m.ItemID=e,m.NetworkID=t,m.WalletAddress=n,m.Amount=i,m.Category=rr(s),r!==void 0&&(m.Level=r),p&&(m.ItemInstanceID=p);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(m);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 n=await this.ctx.api.blockchain.getTransactionHistory(t);return n.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",n.data),n}async retryWithdrawal(e){if(!e)return b("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.TitleTransactionID=e;let n=await this.ctx.api.blockchain.retryWithdrawal(t);return n.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",n.data),n}async confirmWithdrawal(e,t){if(!e)return b("client","TitleTransactionID is required.");if(!t)return b("client","On-chain TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return c;n.TitleTransactionID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.confirmWithdrawal(n);return i.ok&&(this.ctx.data.user.applyBlockchainStateDelta(i.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",i.data)),i}async donateToDeveloper(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return c;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.donateToDeveloper(n);return i.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",i.data),i}async donateToUsersPool(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return c;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.donateToUsersPool(n);return i.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",i.data),i}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return 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 n=await this.ctx.api.blockchain.confirmPlayAccess(t);return n.ok&&this.ctx.auth.setPlayAccess(n.data),n}};var iI={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},_a=z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),sI={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Va=z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),rI={Burn:"Burn",Ledger:"Ledger"},oI=z.enum(["Burn","Ledger"]).catch("Burn"),lr={Item:"Item",VirtualCurrency:"VirtualCurrency"},ja=z.enum(["Item","VirtualCurrency"]).catch("Item"),aI=z.object({Percent:z.number().nullish(),MinPerPosition:H.nullish()}).passthrough(),ur=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Kn).nullish(),MaxPositions:z.number().nullish()}).passthrough(),Fa=z.object({Percent:z.number().nullish(),MinPerPosition:H.nullish(),Sink:oI.nullish(),LedgerAccountID:z.string().nullish(),PerCatalogOverrides:z.record(z.string(),aI).nullish(),ApplyToDirectTrades:z.boolean().nullish()}).passthrough(),lI=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(),uI=z.object({Enabled:z.boolean().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),MaxActiveListings:z.number().nullish(),CreateLimits:Ie.nullish(),BuyLimits:Ie.nullish(),ListingFeeOptions:he.nullish(),RefundListingFeeOnCancel:z.boolean().nullish()}).passthrough(),cI=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:H.nullish(),BidLimits:Ie.nullish()}).passthrough(),pI=z.object({Enabled:z.boolean().nullish(),MaxActiveOrders:z.number().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),CreateLimits:Ie.nullish(),FillLimits:Ie.nullish()}).passthrough(),hI=z.object({Enabled:z.boolean().nullish(),OfferExpirationHours:z.number().nullish(),MaxPendingOutgoing:z.number().nullish(),AllowGifts:z.boolean().nullish(),CreateLimits:Ie.nullish()}).passthrough(),dI=z.object({Enabled:z.boolean().nullish()}).passthrough(),Wa=z.object({Enabled:z.boolean().nullish(),Gate:ee.nullish(),Schedule:Re.nullish(),PricePolicy:ur.nullish(),Commission:Fa.nullish(),Tradability:lI.nullish(),Listings:uI.nullish(),Auctions:cI.nullish(),BuyOrders:pI.nullish(),DirectTrades:hI.nullish(),Matching:dI.nullish()}).passthrough(),Sd=z.object({BidIndex:z.number().nullish(),UserID:z.string().nullish(),Amount:H.nullish(),Settled:z.boolean().nullish(),SettledAt:u.nullish()}).passthrough(),mI=z.object({BidAxisType:i.nullish(),BidCurrencyID:z.string().nullish(),BidCatalogID:z.string().nullish(),BidItemID:z.string().nullish(),StartingBid:H.nullish(),CurrentBid:H.nullish(),CurrentBidderID:z.string().nullish(),BidCount:z.number().nullish(),ExtensionCount:z.number().nullish(),PendingRefunds:z.array(Sd).nullish()}).passthrough(),ar=z.object({LastAt:u.nullish(),DailyCount:z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),fI=z.object({Create:ar.nullish(),Buy:ar.nullish(),Sell:ar.nullish(),Bid:ar.nullish()}).passthrough(),gI=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),yI=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:u,ExpiresAt:u.nullish(),EquippedSlot:gI.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),_t=z.object({OfferID:z.string().nullish(),OfferType:_a.nullish(),Status:Va.nullish(),CreatorUserID:z.string().nullish(),CreatorPublicData:Be.nullish(),TargetUserID:z.string().nullish(),GoodsType:ja.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:H.nullish(),GoodsInstances:z.array(yI).nullish(),Price:ce.nullish(),Auction:mI.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),RI=z.object({GoodsType:ja.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),CountsByType:z.partialRecord(_a,H).nullish()}).passthrough(),xd=z.object({Definitions:Wa.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish()}).passthrough(),Ka=z.object({Offers:z.array(_t).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),bd=z.object({Groups:z.array(RI).nullish()}).passthrough(),Dd=z.object({Offer:_t.nullish()}).passthrough(),yt=z.object({OfferID:z.string().nullish(),Status:Va.nullish(),Settlement:Ut.nullish(),Resources:O.nullish(),CommissionTaken:ce.nullish(),HeldPayout:gt.nullish()}).passthrough(),Yn=z.object({OfferID:z.string().nullish(),Offer:_t.nullish(),Resources:O.nullish(),Matched:z.boolean().nullish(),Settlement:yt.nullish()}).passthrough(),Id=z.object({OfferID:z.string().nullish(),CurrentBid:H.nullish(),BidCount:z.number().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish()}).passthrough(),cr=z.object({MyOffers:z.array(_t).nullish(),MyBids:z.array(_t).nullish(),MyBuyOrders:z.array(_t).nullish(),IncomingTrades:z.array(_t).nullish(),OutgoingTrades:z.array(_t).nullish(),Claimables:z.array(_t).nullish(),DrainedRefunds:z.array(Sd).nullish(),Limits:fI.nullish(),PendingPayouts:z.array(gt).nullish(),ReleasedPayouts:z.array(gt).nullish(),VoidedPayouts:z.array(gt).nullish(),PayoutOperations:z.array(O).nullish()}).passthrough(),CI=z.object({OfferID:z.string().nullish(),OfferType:_a.nullish(),FinalStatus:Va.nullish(),SellerUserID:z.string().nullish(),BuyerUserID:z.string().nullish(),GoodsType:ja.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:H.nullish(),PricePaid:ce.nullish(),CommissionTaken:ce.nullish(),CompletedAt:u.nullish(),MyRole:z.string().nullish()}).passthrough(),Pd=z.object({Entries:z.array(CI).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Le={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 SI="Marketplace",vd={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"]},pr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(vd,{schema:cr,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(SI,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,n,i=20){if(!e)return b("client","ItemID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.ItemID=e,s.OfferTypeFilter=t,s.ContinuationToken=n,s.PageSize=i;let r=await this.ctx.api.marketplace.getOffersByItem(s);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;t.OfferID=e;let n=await this.ctx.api.marketplace.getOffer(t);return n.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",n.data),n}async getBuyOrders(e,t,n=20){let i=this.ctx.authedRequest();if(!i)return c;i.ItemID=e,i.ContinuationToken=t,i.PageSize=n;let s=await this.ctx.api.marketplace.getBuyOrders(i);return s.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",s.data),s}getMyState(e,t){return this.ctx.cache.read(vd,()=>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 n=await this.ctx.api.marketplace.getMyState(t);if(n.ok){for(let i of n.data.PayoutOperations??[])this.ctx.data.user.applyResourceOperation(i,this.ctx.data.config.itemDefinitions);this.applyMyState(n.data);}return n}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,n){let i=this.ctx.authedRequest();if(!i)return c;n&&(i.HistoryFilter=n),i.ContinuationToken=e,i.PageSize=t;let s=await this.ctx.api.marketplace.getHistory(i);return s.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",s.data),s}async createListing(e,t,n,i,s,r,p){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!i)return b("client","PriceBundle is required.");let m=this.ctx.authedRequest();if(!m)return c;m.ItemID=e,m.CatalogID=t,m.GoodsAmount=n,m.PriceBundle=i,m.DurationHours=s,m.ItemInstanceIDs=r,m.SelectedOptionID=p;let R=await this.ctx.api.marketplace.createListing(m);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 n=await this.ctx.api.marketplace.buy(t);return n.ok&&(this.applyDualPartySettlement(n.data.Settlement),this.ctx.emitter.emit("marketplace:bought",n.data)),n}async marketBuy(e,t,n){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let i=this.ctx.authedRequest();if(!i)return c;let s=this.applyGoodsSelector(i,n);if(s)return s;i.GoodsAmount=e,i.PriceBundle=t;let r=await this.ctx.api.marketplace.marketBuy(i);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",r.data)),r}async marketSell(e,t,n){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let i=this.ctx.authedRequest();if(!i)return c;let s=this.applyGoodsSelector(i,n);if(s)return s;i.GoodsAmount=e,i.PriceBundle=t;let r=await this.ctx.api.marketplace.marketSell(i);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",r.data)),r}async createAuction(e,t,n,i,s,r,p={}){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");let m=this.ctx.authedRequest();if(!m)return c;m.ItemID=e,m.CatalogID=t,m.GoodsAmount=n,m.BidAxisType=i,m.BidCurrencyID=p.bidCurrencyID,m.BidCatalogID=p.bidCatalogID,m.BidItemID=p.bidItemID,m.StartingBid=s,m.DurationHours=r,m.ItemInstanceIDs=p.itemInstanceIDs,m.SelectedOptionID=p.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(m);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 n=this.ctx.authedRequest();if(!n)return c;n.OfferID=e,n.BidAmount=t;let i=await this.ctx.api.marketplace.placeBid(n);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",i.data)),i}async claimAuction(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.OfferID=e;let n=await this.ctx.api.marketplace.claimAuction(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",n.data)),n}async createBuyOrder(e,t,n,i,s){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!i)return b("client","PriceBundle is required.");let r=this.ctx.authedRequest();if(!r)return c;r.ItemID=e,r.CatalogID=t,r.GoodsAmount=n,r.PriceBundle=i,r.DurationHours=s;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;t.OfferID=e;let n=await this.ctx.api.marketplace.fillBuyOrder(t);return n.ok&&(this.applyDualPartySettlement(n.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",n.data)),n}async createDirectTrade(e,t,n,i,s){if(!e)return b("client","TargetUserID is required.");if(!t)return b("client","CatalogID is required.");if(!n)return b("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return c;r.TargetUserID=e,r.CatalogID=t,r.ItemID=n,r.ItemInstanceIDs=i,r.RequestedBundle=s;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 n=this.ctx.authedRequest();if(!n)return c;n.OfferID=e,n.Accept=t;let i=await this.ctx.api.marketplace.respondDirectTrade(n);return i.ok&&(t&&(i.data.Settlement?this.applyDualPartySettlement(i.data.Settlement):i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",i.data)),i}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return c;t.OfferID=e;let n=await this.ctx.api.marketplace.claimBack(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",n.data)),n}async cancelOffer(e,t,n){if(!e)return b("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.OfferID=e;let s=await t(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(n,s.data)),s}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=lr.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=lr.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):b("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let n=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,n):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,n);}};var hr=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return b("client","RoomName is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomName=e,n.Topology=t.topology,n.ChatMode=t.chatMode,n.MaxPlayers=t.maxPlayers,n.Visibility=t.visibility,n.JoinCode=t.joinCode,n.Mode=t.mode,n.Voice=t.voice;let i=await this.ctx.api.multiplayer.createRoom(n);return i.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",i.data),i}async joinRoom(e,t){if(!e)return b("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.JoinCode=t;let i=await this.ctx.api.multiplayer.joinRoom(n);return i.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",i.data),i}async leaveRoom(e,t={}){if(!e)return b("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.SuccessorUserID=t.successorUserID;let i=await this.ctx.api.multiplayer.leaveRoom(n,t.keepalive??false);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",i.data),i}async claimHost(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.RoomID=e;let n=await this.ctx.api.multiplayer.claimHost(t);return n.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",n.data),n}async kickMember(e,t,n=false){if(!e)return 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,i.Ban=n;let s=await this.ctx.api.multiplayer.kickMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",s.data),s}async unbanMember(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.TargetUserID=t;let i=await this.ctx.api.multiplayer.unbanMember(n);return i.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",i.data),i}async listRooms(e=0,t=20){let n=this.ctx.authedRequest();if(!n)return c;n.Page=e,n.PageSize=t;let i=await this.ctx.api.multiplayer.listRooms(n);return i.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",i.data),i}async getRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.RoomID=e;let n=await this.ctx.api.multiplayer.getRoom(t);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",n.data),n}async closeRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.RoomID=e;let n=await this.ctx.api.multiplayer.closeRoom(t);return n.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",n.data),n}async poll(e,t){if(!e)return b("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.LastSeq=t;let i=await this.ctx.api.multiplayer.poll(n);return i.ok&&this.ctx.emitter.emit("multiplayer:polled",i.data),i}async sendSignal(e,t,n,i){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");if(!n)return b("client","SignalKind is required.");let s=this.ctx.authedRequest();if(!s)return c;s.RoomID=e,s.TargetUserID=t,s.SignalKind=n,s.Payload=i;let r=await this.ctx.api.multiplayer.sendSignal(s);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 n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.ChatText=t;let i=await this.ctx.api.multiplayer.sendChat(n);return i.ok&&this.ctx.emitter.emit("multiplayer:chatSent",i.data),i}async setMemberState(e,t,n){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.Ready=t,i.MemberState=n;let s=await this.ctx.api.multiplayer.setMemberState(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",s.data),s}};var Ad=" (if the network is fine, the storage bucket has no CORS rule for this origin)",dr=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,n){if(!e)return b("client","CreatorUserID is required.");let i=this.ctx.authedRequest();return i?(i.CreatorUserID=e,i.ContinuationToken=t,i.PageSize=n,this.ctx.api.workshop.getCreatorProfile(i)):c}async publish(e){if(!e.files||e.files.length===0)return b("client","At least one file is required.");let t=new Map,n=e.files.map((m,R)=>{if("sourceAssetUrl"in m)return {Role:m.role,ContentType:m.contentType,SourceAssetUrl:m.sourceAssetUrl};let W=Td(m.data,m.contentType);return t.set(R,W),{Role:m.role,ContentType:m.contentType,Size:W.size}}),i=e.thumbnail?Td(e.thumbnail.data,e.thumbnail.contentType):null,s=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:n,Thumbnail:e.thumbnail&&i?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:i.size}:void 0});if(!s.ok)return s;let r=s.data.Uploads??[];for(let m=0;m<r.length;m++){let R=r[m];if(!R||R.ServerCopy||!R.Url)continue;let W=t.get(m);if(!W)return b("client",`No bytes for file #${m+1}.`);let me=await this.putBytes(R.Url,W,R.ContentType??W.type);if(!me.ok)return me}let p=s.data.ThumbnailUpload;if(p?.Url&&i){let m=await this.putBytes(p.Url,i,p.ContentType??i.type);if(!m.ok)return m}return this.ctx.credits.pay(m=>this.publishUploaded({CreditsConfirmationID:m,ContentID:s.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID}),e.credits)}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):c}async publishUploaded(e){if(!e.ContentID)return b("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return c;let n=await this.ctx.api.workshop.publish({...t,...e});return n.ok&&!n.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",n.data)),n}async updateContent(e,t){let n=this.contentRequest(e);if("ok"in n)return n;n.Title=t.title,n.Description=t.description,n.Tags=t.tags,n.Metadata=t.metadata,n.Visibility=t.visibility,n.Access=t.access;let i=await this.ctx.api.workshop.updateContent(n);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let n=await this.ctx.api.workshop.unpublish(t);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async getMyContent(e,t,n){let i=this.ctx.authedRequest();return i?(i.ContentType=e,i.ContinuationToken=t,i.PageSize=n,this.ctx.api.workshop.getMyContent(i)):c}async acquire(e,t){let n=this.contentRequest(e);if("ok"in n)return n;n.OptionID=t?.OptionID??void 0,n.ExpectedPrice=t?.Price??void 0;let i=await this.ctx.api.workshop.acquire(n);return i.ok&&(i.data.Settlement?this.applyDualPartySettlement(i.data.Settlement):this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",i.data)),i}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let n=[];for(let i of t.data.Files??[])if(i.Url)try{let s=await this.ctx.fetchImpl(i.Url);if(!s.ok)return b("connection",`Download failed (HTTP ${s.status}).`);n.push({role:i.Role??"main",contentType:i.ContentType??"application/octet-stream",data:await s.arrayBuffer()});}catch(s){return b("connection",`Download failed: ${s instanceof Error?s.message:String(s)}${Ad}`)}return a$1({download:t.data,files:n})}async getMyLicenses(e,t){let n=this.ctx.authedRequest();return n?(n.ContinuationToken=e,n.PageSize=t,this.ctx.api.workshop.getMyLicenses(n)):c}async getMyFavorites(e,t){let n=this.ctx.authedRequest();return n?(n.ContinuationToken=e,n.PageSize=t,this.ctx.api.workshop.getMyFavorites(n)):c}async putBytes(e,t,n){try{let i=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":n},body:t});return i.ok?a$1(!0):b("connection",`Upload failed (HTTP ${i.status}).`)}catch(i){return b("connection",`Upload failed: ${i instanceof Error?i.message:String(i)}${Ad}`)}}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 n=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,n):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,n);}};function Td(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 xI={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},bI=z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),DI={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},zd=z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),II={Everyone:"Everyone",Owner:"Owner",Server:"Server"},wd=z.enum(["Everyone","Owner","Server"]).catch("Everyone"),PI={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},vI=z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),AI={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},TI=z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),zI={Count:"Count",Sum:"Sum"},wI=z.enum(["Count","Sum"]).catch("Count"),kI={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},MI=z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),OI={Strict:"Strict",Loose:"Loose"},EI=z.enum(["Strict","Loose"]).catch("Strict"),qI=z.object({Kind:TI,Collection:z.string().nullish(),Validate:z.boolean().nullish()}),UI=z.object({Type:zd,ItemType:zd.nullish(),Ref:qI.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:wd.optional(),ClientWritable:z.boolean().nullish(),Immutable:z.boolean().optional(),Description:z.string().nullish(),AllowedMimeTypes:z.array(z.string()).nullish(),MaxFileBytes:z.number().nullish()}),LI=z.object({ID:z.string(),Components:z.array(z.object({Field:z.string(),Descending:z.boolean().optional()})).default([])}),mr=z.object({Mode:vI,Role:z.string().nullish(),MembersField:z.string().nullish()}),BI=z.object({Read:z.array(mr).nullish(),Create:z.array(mr).nullish(),Update:z.array(mr).nullish(),Delete:z.array(mr).nullish()}),Qa=z.object({Cost:ce.nullish(),Grant:ce.nullish()}),GI=z.object({ID:z.string(),SortKey:z.string(),PartitionField:z.string().nullish(),PageSize:z.number().optional(),MaxItems:z.number().optional(),PublishItems:z.boolean().optional()}),NI=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:bI,Mode:EI.optional(),SchemaVersion:z.number().optional(),Fields:z.record(z.string(),UI).nullish(),SortKeys:z.array(LI).nullish(),Access:BI.nullish(),Limits:z.object({MaxItemBytes:z.number().nullish(),MaxItemsPerOwner:z.number().nullish(),TtlSeconds:z.number().nullish()}).nullish(),OnOwnerDeleted:MI.optional(),Counters:z.array(z.object({ID:z.string(),Kind:wI,SumField:z.string().nullish(),GroupBy:z.string().nullish(),Visibility:wd.optional()})).nullish(),Economy:z.object({OnCreate:Qa.nullish(),OnUpdate:Qa.nullish(),OnDelete:Qa.nullish()}).nullish(),WriteGate:ee.nullish(),PublicViews:z.array(GI).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()}),kd=z.object({Enabled:z.boolean().optional(),Collections:z.record(z.string(),NI).default({})}),_I=z.object({FileID:z.string(),Url:z.string(),ContentType:z.string().nullish(),Size:z.number()}),Md=z.object({FileID:z.string(),UploadUrl:z.string(),ContentType:z.string(),MaxBytes:z.number(),ExpiresAt:z.string()}),zn=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(),_I).nullish()}),Ha=z.object({Item:zn}),Od=z.object({Items:z.array(zn).default([]),Missing:z.array(z.string()).default([])}),$a=z.object({Items:z.array(zn).default([]),NextCursor:z.string().nullish()}),Ed=z.object({Count:z.number(),Capped:z.boolean().optional()}),Ja=z.object({Item:zn,AlreadyExists:z.boolean().optional(),Economy:O.nullish()}),qd=z.object({ItemID:z.string(),Deleted:z.boolean(),Economy:O.nullish()}),Ud=z.object({CounterID:z.string(),Group:z.unknown().optional(),Value:z.number()}),Ld=z.object({Results:z.array(z.object({Op:z.string(),Collection:z.string(),ItemID:z.string(),Item:zn.nullish(),Deleted:z.boolean().optional()})).default([])}),Bd=z.object({Roles:z.array(z.string()).default([])}),Gd=z.object({Views:z.record(z.string(),z.string()).default({}),ItemUrlTemplate:z.string().nullish()}),Nd=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({})}),_d=z.object({Page:z.number(),HasMore:z.boolean(),Items:z.array(zn).default([])}),VI={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 jI=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Fd=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Ya=100,Vd=25,jd=100;function FI(o,e,t){return {Field:o,Op:e,Value:t}}var fr=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(c)}get(e,t,n={}){let i=ct(e)??Xn(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.get({...s,Collection:e,ItemID:t,Expand:n.expand}))}getMany(e,t,n={}){let i=ct(e);if(i)return Promise.resolve(i);let s=[...new Set(t.filter(r=>Fd.test(r)))];return s.length?s.length>jd?Promise.resolve(b("client",`At most ${jd} ids per call.`)):this.call(r=>this.ctx.api.dataCollections.getMany({...r,Collection:e,ItemIDs:s,Expand:n.expand})):Promise.resolve(b("client","At least one valid item id is required."))}query(e,t={},n={}){let i=ct(e)??Za(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.query({...s,Collection:e,Query:t,Expand:n.expand}))}async queryAll(e,t={},n={}){let i=Math.max(1,n.maxItems??500),s=[],r=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:r,Limit:t.Limit??Ya},n);if(!p.ok)return p;if(s.push(...p.data.Items),r=p.data.NextCursor??void 0,!r||s.length>=i)return a$1(s.slice(0,i))}}count(e,t={}){let n=ct(e)??Za(t);return n?Promise.resolve(n):this.call(i=>this.ctx.api.dataCollections.count({...i,Collection:e,Query:t}))}create(e,t,n={}){let i=ct(e)??(n.itemID?Xn(n.itemID):null);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.create({...s,Collection:e,ItemID:n.itemID,Data:t}))}update(e,t,n,i={}){let s=ct(e)??Xn(t);return s?Promise.resolve(s):this.call(r=>this.ctx.api.dataCollections.update({...r,Collection:e,ItemID:t,Update:n,ExpectedVersion:i.expectedVersion}))}set(e,t,n,i={}){return this.update(e,t,{Set:n},i)}increment(e,t,n,i=1){return this.update(e,t,{Inc:{[n]:i}})}delete(e,t,n={}){let i=ct(e)??Xn(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.delete({...s,Collection:e,ItemID:t,ExpectedVersion:n.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(b("client","Operations are empty."));if(e.length>Vd)return Promise.resolve(b("client",`At most ${Vd} operations per batch.`));let t=e.map(n=>ct(n.Collection)).find(n=>n!=null);return t?Promise.resolve(t):this.call(n=>this.ctx.api.dataCollections.batch({...n,Operations:e}))}getCounter(e,t,n){let i=ct(e);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.getCounter({...s,Collection:e,CounterID:t,Group:n}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,n,i){let s=ct(e);return s?Promise.resolve(s):t?i>0?this.call(r=>this.ctx.api.dataCollections.beginFileUpload({...r,Collection:e,Field:t,ContentType:n,FileSize:i})):Promise.resolve(b("client","File size must be positive.")):Promise.resolve(b("client","Field is required."))}async uploadFile(e,t,n,i={}){let s=i.contentType||n.type||"application/octet-stream",r=await this.beginFileUpload(e,t,s,n.size);if(!r.ok)return r;let p=await this.putBytes(r.data.UploadUrl,n,r.data.ContentType||s);return p.ok?r:p}async getPublicViews(e){let t=ct(e);if(t)return t;let n=this.publicViews.get(e);if(n)return a$1(n);let i=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return i.ok&&this.publicViews.set(e,i.data),i}async readPublicView(e,t,n={}){let i=await this.getPublicViews(e);if(!i.ok)return i;let s=i.data.Views[t];if(!s)return b("client",`Collection '${e}' has no public view '${t}'.`);let r=await this.fetchJson(s,Nd);if(!r.ok)return r;let p=r.data.Partitions[n.partition??""],m=Math.max(1,n.page??1);if(!p||m>p.Pages)return a$1({pointer:r.data,page:{Page:m,HasMore:false,Items:[]}});let R=await this.fetchJson(`${r.data.BaseUrl}${p.Segment}/page-${m}.json`,_d);return R.ok?a$1({pointer:r.data,page:R.data}):R}getPublic(e,t){let n=ct(e)??Xn(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let n=ct(e)??Za(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(c)}async putBytes(e,t,n){try{let i=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":n},body:t});return i.ok?a$1(!0):b("connection",`Upload failed (HTTP ${i.status}).`)}catch(i){return b("connection",`Upload failed: ${i instanceof Error?i.message:String(i)}`)}}async fetchJson(e,t){let n;try{n=await this.ctx.fetchImpl(e);}catch{return b("connection","Internet Connection Error")}if(!n.ok)return b("server",`CDN answered ${n.status}.`);let i;try{i=await n.json();}catch{return b("server","CDN answer is not JSON.")}let s=t.safeParse(i);return s.success?a$1(s.data):b("server","CDN answer has an unexpected shape.")}};function ct(o){return jI.test(o??"")?null:b("client",`Collection id '${o}' is invalid (letters, digits, '_', '-', ':').`)}function Xn(o){return Fd.test(o??"")?null:b("client",`Item id '${o}' is invalid.`)}function Za(o){return o.Limit!=null&&(o.Limit<1||o.Limit>Ya)?b("client",`Limit must be 1..${Ya}.`):(o.Where?.length??0)>8?b("client","At most 8 filters per query."):null}var Xa={Open:"Open",Declared:"Declared"},WI=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Blocked:z.boolean().nullish(),Highlight:z.number().nullish()}).passthrough(),KI=z.object({ParamName:z.string().nullish(),DisplayName:z.string().nullish()}).passthrough(),Wd=z.object({Enabled:z.boolean().nullish(),EventNaming:z.string().nullish(),Events:z.record(z.string(),WI).nullish(),Dimensions:z.array(KI).nullish(),RetentionDays:z.number().nullish(),AutomaticEvents:z.boolean().nullish()}).passthrough(),Xt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Mt={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},gr=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,QI={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},HI=z.object({Index:z.number().nullish(),Name:z.string().nullish(),Reason:z.string().nullish()}).passthrough(),Kd=z.object({Accepted:z.number().nullish(),Dropped:z.array(HI).nullish(),Duplicate:z.boolean().nullish(),Disabled:z.boolean().nullish()}).passthrough(),el={LogEvents:"LogEvents"};function Qd(o,e=0){let t=o??"",n=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(n){let p=n[1]??"iPhone";return {osName:"iOS",osVersion:(n[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let i=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(i){let p=(i[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:i[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let s=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(s)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(s[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let 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 Hd(o){let e=typeof navigator>"u"?void 0:navigator,t=Qd(e?.userAgent??"",e?.maxTouchPoints??0),n={};o.appVersion&&(n.AppVersion=o.appVersion),t.osName&&(n.OsName=t.osName),t.osVersion&&(n.OsVersion=t.osVersion),t.deviceCategory&&(n.DeviceCategory=t.deviceCategory),t.deviceModel&&(n.DeviceModel=t.deviceModel);let i=o.locale||e?.language;return i&&(n.Language=i),n}var $I=25,JI=3e4,$d=1800*1e3,Jd=500,ZI=5,YI=1e3,XI=3600*1e3,Zd="idos_analytics_queue",tl="idos_analytics_pending",nl="idos_analytics_opt_out",Yd="idos_analytics_first_open",Xd="idos_analytics_last_activity",em="idos_analytics_last_context",tm="idos_analytics_owner",yr=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;stopVisibility=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,n){return typeof e!="string"||!gr.test(e)?b("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):eP(e)?b("client",`Event name "${e}" uses a reserved prefix (${Mt.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,n,false))}logScreenView(e,t){if(!e)return b("client","screenName is required.");let n={screen_name:e};return t&&(n.screen_class=t),this.enqueue(Xt.ScreenView,n,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return a$1(null);if(this.config()?.Enabled===false)return this.clear(),a$1(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return a$1(null);this.pending={BatchID:a(),Events:this.queue.splice(0,Mt.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 n=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return n.ok?(this.pending=null,n.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),n.data.Dropped&&n.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",n.data.Dropped),this.ctx.emitter.emit("analytics:flushed",n.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),n):(n.reason!=="throttled"&&t.Attempts++,(n.reason==="validation"||t.Attempts>=ZI)&&(this.pending=null),this.persist(),n)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(nl);return}this.write(nl,"1"),this.clear();}get isEnabled(){return this.read(nl)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(tm);e&&t&&t!==e&&this.clear(),e&&this.write(tm,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},JI),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide),this.beginAutomatic(),this.flush();}async stop(){this.started&&(this.started=false,this.automaticDone=false,this.timer&&clearInterval(this.timer),this.drainTimer&&clearTimeout(this.drainTimer),this.timer=null,this.drainTimer=null,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null,this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),await this.flush());}beginAutomatic(){if(this.automaticDone||!this.started)return;if(this.config()?.Enabled!==true){this.stopWaitingForConfig??=this.ctx.emitter.on("title:publicConfigurationReceived",()=>this.beginAutomatic());return}this.automaticDone=true,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null;let e=Number(this.read(Xd)??"0");this.read(Yd)||(this.write(Yd,new Date().toISOString()),this.enqueue(Xt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),n=this.readJson(em);n?.AppVersion&&t.AppVersion&&n.AppVersion!==t.AppVersion&&this.enqueue(Xt.AppUpdate,{previous_app_version:n.AppVersion},void 0,true),n?.OsVersion&&t.OsVersion&&n.OsVersion!==t.OsVersion&&this.enqueue(Xt.OsUpdate,{previous_os_version:n.OsVersion},void 0,true),this.writeJson(em,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=$d)&&this.enqueue(Xt.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=e=>{if(!e){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=$d&&this.enqueue(Xt.SessionStart,void 0,void 0,true),this.hiddenAt=null;};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,n,i){if(!this.isEnabled||this.disabledByServer)return a$1(null);let s=this.config();if(s?.Enabled===false)return a$1(null);if(i&&s?.AutomaticEvents===false)return a$1(null);if(s?.Events?.[e]?.Blocked)return b("client",`Event "${e}" is blocked by the title.`);if(!i&&s?.EventNaming?.toLowerCase()===Xa.Declared.toLowerCase()&&!s.Events?.[e])return b("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(n!==void 0&&!Number.isFinite(n))return b("client","value must be a finite number.");let r=tP(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),n!==void 0&&(p.Value=n),this.queue.push(p),this.queue.length>Jd&&this.queue.splice(0,this.queue.length-Jd),this.touch(),this.persist(),this.started&&this.queue.length>=$I&&this.flush(),a$1(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},YI));}dropStale(){let e=Date.now()-(Mt.maxEventAgeMs-XI);this.queue=this.queue.filter(t=>{let n=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(n)||n>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=Hd({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(n=>typeof n?.Name=="string").concat(this.queue));let t=this.readJson(tl);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(tl,this.pending):this.remove(tl);}touch(){this.write(Xd,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.host.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.host.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.host.storage.remove(this.key(e));}catch{}}readJson(e){let t=this.read(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}writeJson(e,t){this.write(e,JSON.stringify(t));}};function eP(o){let e=o.toLowerCase();return Mt.reservedPrefixes.some(t=>e.startsWith(t))}function tP(o){if(!o)return {};let e=Object.keys(o);if(e.length===0)return {};if(e.length>Mt.maxParams)return {error:`Too many parameters: ${e.length}, max ${Mt.maxParams}.`};let t={};for(let n of e){if(!gr.test(n))return {error:`Invalid parameter name "${n}".`};let i=o[n];typeof i=="string"?t[n]=i.length>Mt.maxStringValueLength?i.slice(0,Mt.maxStringValueLength):i:typeof i=="number"?Number.isFinite(i)&&(t[n]=i):typeof i=="boolean"&&(t[n]=i);}return {params:t}}var nP="idos_experiments",Rr=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 n=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),n.length>0&&this.ctx.emitter.emit("experiments:changed",n);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,n){let i=this.getParams(e)[t];if(i===void 0)return n;if(typeof n=="number"){let s=Number(i);return i.trim()!==""&&Number.isFinite(s)?s:n}if(typeof n=="boolean"){let s=i.trim().toLowerCase();return s==="true"||s==="1"?true:s==="false"||s==="0"?false:n}return i}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let i of e.Experiments??[])i?.ExperimentID&&t.set(i.ExperimentID,i);let n=[];for(let[i,s]of t){let r=this.views.get(i);(!r||r.VariantID!==s.VariantID||r.Status!==s.Status)&&n.push(s);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,n}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.host.storage.getString(this.key());if(!t)return;let n=JSON.parse(t);n?.UserID===e&&n.Data&&this.apply(n.Data);}catch{}}save(e,t){try{let n={UserID:e,Data:t};this.ctx.host.storage.setString(this.key(),JSON.stringify(n));}catch{}}key(){return `${nP}:${this.ctx.settings.titleID}`}};function en(o,e,t,n){let s=`api/v2/${o&&o.length>0?o:"0"}/Client/${e}/${t}`;return n==null?s:`${s}/${n}`}var _=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return en(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,n,i){return this.ctx.transport.post(this.endpoint(e,t),t,n,{...i,ticket:t.ClientSessionTicket})}};var Cr=class extends _{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(el.LogEvents,e,Kd,{silent:true})}};var iP=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(),sP={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},rP=z.object({MetricID:z.string().nullish(),Kind:z.string().nullish(),EventName:z.string().nullish(),IsPrimary:z.boolean().nullish()}).passthrough(),oP=z.object({ExperimentID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),IsEnabled:z.boolean().nullish(),Schedule:Re.nullish(),Gate:ee.nullish(),Variants:z.array(iP).nullish(),Salt:z.string().nullish(),LayerID:z.string().nullish(),StickyAssignment:z.boolean().nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Goals:z.array(rP).nullish(),ActivationEvent:z.string().nullish(),RolloutVariantID:z.string().nullish()}).passthrough(),nm=z.object({Experiments:z.record(z.string(),oP).nullish()}).passthrough(),aP={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},lP=z.object({ExperimentID:z.string().nullish(),VariantID:z.string().nullish(),Status:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),im=z.object({Experiments:z.array(lP).nullish(),IsAbTestingAvailable:z.boolean().nullish()}).passthrough(),il={GetExperiments:"GetExperiments"};var Sr=class extends _{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(il.GetExperiments,e,im)}};var uP={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},sm=z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),cP=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),IsEnabled:z.boolean().nullish(),Order:z.number().nullish()}).passthrough(),rm=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),Locales:z.record(z.string(),cP).nullish(),MissingKeyMode:sm.nullish(),MaxEntriesPerLocale:z.number().nullish(),MaxValueLengthBytes:z.number().nullish()}).passthrough(),pP=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish()}).passthrough(),om=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish(),Fallback:pP.nullish()}).passthrough(),xr={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},hP=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),Order:z.number().nullish(),Version:z.number().nullish()}).passthrough(),am=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),MissingKeyMode:sm.nullish(),ResolvedLocale:z.string().nullish(),Locales:z.array(hP).nullish()}).passthrough(),lm=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 ei=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:om.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(),PeerPayouts:Dp.nullish()}).passthrough().transform(o=>o),um=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish()}).passthrough().transform(o=>o),cm=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),User:z.unknown().nullish()}).passthrough().transform(o=>o),pm=z.object({}).passthrough().transform(o=>o),hm=z.object({}).passthrough().transform(o=>o),dm=z.object({Today:z.number(),Yesterday:z.number(),CurrentWeek:z.number(),CurrentMonth:z.number(),Total:z.number(),TotalSessions:z.number(),FirstActiveAt:u.nullish(),LastActiveAt:u.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(),mm=z.object({Username:z.string()}),Rt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var fm=z.object({PlatformUserID:z.string().nullish(),PlatformAuthToken:z.string().nullish(),PlatformAuthTokenExpiration:u.nullish(),TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:u,PlayAccess:Yt.nullish(),RefreshToken:z.string().nullish(),RefreshTokenExpiration:u.nullish(),ClientState:ei.nullish()}),gm=z.object({TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:u,RefreshToken:z.string(),RefreshTokenExpiration:u.nullish(),PlayAccess:Yt.nullish()}),dP=z.object({ReturnMode:z.string().nullish(),UrlScheme:z.string().nullish(),UserCodeSupported:z.boolean().nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),ym=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:Zn.nullish(),WalletLoginNetworks:z.array(z.object({NetworkID:z.string().nullish(),Type:z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:z.boolean().nullish(),NativeSso:dP.nullish()}).passthrough(),Rm=z.object({Linked:z.boolean().nullish(),Challenge:z.string().nullish(),ExpiresAt:u.nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),PlayAccess:Yt.nullish()}).passthrough(),Cm=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CooldownUntil:u.nullish(),PlayAccess:Yt.nullish()}).passthrough(),Sm=z.object({CodeTtlMinutes:z.number().nullish(),ResendCooldownSeconds:z.number().nullish()}),Ke=z.object({IsCompleted:z.boolean().nullish(),ServerTime:u.nullish()}),xm=z.object({Message:z.string(),ExpiresAt:u}),We={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 br=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return en(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,fm,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(We.RefreshSession),e,gm,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(We.GetAuthOptions),e,ym,{ticket:null})}linkWallet(e){return this.ctx.transport.post(en(this.ctx.settings.titleID,"Authentication",We.LinkWallet,e.UserID??""),e,Rm,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(en(this.ctx.settings.titleID,"Authentication",We.UnlinkWallet,e.UserID??""),e,Cm,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(We.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(We.LoginWithTelegram,e)}loginWithEmail(e){return this.login(We.LoginWithEmail,e)}loginWithGoogle(e){return this.login(We.LoginWithGoogle,e)}loginWithApple(e){return this.login(We.LoginWithApple,e)}loginWithSsoCode(e){return this.login(We.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(We.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(We.RegisterWithEmail),e,Sm,{ticket:null})}confirmEmailRegistration(e){return this.login(We.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(We.ResendVerificationCode),e,Ke,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(We.RequestWalletChallenge),e,xm,{ticket:null})}loginWithWallet(e){return this.login(We.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(We.ForgotPassword),e,Ke,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(We.ResetPassword),e,Ke,{ticket:null})}};var Dr=class extends _{constructor(e){super(e,"User");}getClientState(e){return this.send(Rt.GetClientState,e,ei)}getClientStateExcept(e){return this.send(Rt.GetClientStateExcept,e,ei)}getStateVersions(e){return this.send(Rt.GetStateVersions,e,um)}getUserState(e){return this.send(Rt.GetUserState,e,cm)}getInventory(e){return this.send(Rt.GetInventory,e,pm)}getEventTokens(e){return this.send(Rt.GetEventTokens,e,hm)}getUsageTime(e){return this.send(Rt.GetUsageTime,e,dm)}addUsageTime(e){return this.send(Rt.AddUsageTime,e,Ke,{silent:true})}deleteUserAccount(e){return this.send(Rt.DeleteUserAccount,e,Ke)}changeUsername(e){return this.send(Rt.ChangeUsername,e,mm)}};var Ir=class extends _{constructor(e){super(e,"Currency");}convert(e){return this.send(Fn.Convert,e,yp)}spend(e){return this.send(Fn.Spend,e,Cp)}cryptoConvert(e){return this.send(Fn.CryptoConvert,e,Rp)}};var mP=z.object({ItemInstanceID:z.string(),Units:z.number(),Level:z.number()}),sl=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u,ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Level:z.number(),Resources:O.nullish(),FodderConsumed:z.array(mP).nullish()}),bm=z.array(ke(sl)),Pr={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},fP={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},gP=z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),yP={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},RP=z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),CP=z.object({ContractAddress:z.string().nullish(),TokenID:z.string().nullish(),TokenStandard:z.string().nullish(),MaxLevel:z.number().nullish()}).passthrough(),SP=z.object({Networks:z.record(z.string(),CP).nullish(),MetadataUrl:z.string().nullish()}).passthrough(),xP=z.object({FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),bP=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(),DP=z.object({ValuationMode:gP.nullish(),WeightCurve:$e.nullish(),Selection:RP.nullish()}).passthrough(),IP=z.object({MaxLevel:z.number().nullish(),PriceOptions:he.nullish(),CostCurve:$e.nullish(),FlatBonusCurve:$e.nullish(),PercentBonusCurve:$e.nullish(),PowerCurve:$e.nullish(),Fodder:DP.nullish()}).passthrough(),PP=z.object({RarityID:z.string().nullish(),CollectionID:z.string().nullish(),AuthorID:z.string().nullish()}).passthrough(),vP=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:SP.nullish(),Stats:xP.nullish(),Equipment:bP.nullish(),Upgrade:IP.nullish(),Metadata:PP.nullish(),ExpirationDurationSeconds:z.number().nullish(),MaxSupply:z.number().nullish()}).passthrough(),AP=z.object({Items:z.record(z.string(),vP).nullish()}).passthrough(),TP={Cumulative:"Cumulative",HighestOnly:"HighestOnly"},zP=z.enum(["Cumulative","HighestOnly"]).catch("Cumulative"),wP=z.object({Pieces:z.number().nullish(),FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),kP=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BonusMode:z.enum(["Cumulative","HighestOnly"]).nullish().catch(null),Bonuses:z.array(wP).nullish()}).passthrough(),MP=z.object({BonusMode:zP.nullish()}).passthrough(),vr=z.object({Catalogs:z.record(z.string(),AP).nullish(),Sets:z.record(z.string(),kP).nullish(),SetSettings:MP.nullish()}).passthrough();function Ae(o){return z.unknown().transform((e,t)=>{let n=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(n!=null){let s=ge.safeParse(n);return s.success?{...e,CreditsConfirmation:s.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${s.error.message}`}),z.NEVER)}let i=o.safeParse(e);return i.success?i.data:(t.addIssue({code:"custom",message:i.error.message}),z.NEVER)})}var Ar=class extends _{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(Pr.UpgradeLevel,e,Ae(sl))}upgradeLevelsBatch(e){return this.send(Pr.UpgradeLevelsBatch,e,bm)}};var Tr=class extends _{constructor(e){super(e,"Store");}purchase(e){return this.send(Bt.Purchase,e,Fo)}purchaseBatch(e){return this.send(Bt.PurchaseBatch,e,Pu)}getDefinitions(e){return this.send(Bt.GetDefinitions,e,Li)}getUserState(e){return this.send(Bt.GetUserState,e,vu)}getStorefront(e){return this.send(Bt.GetStorefront,e,Bi)}getCreditsConfirmation(e){return this.send(Bt.GetCreditsConfirmation,e,ge)}getCreditsBalance(e){return this.send(Bt.GetCreditsBalance,e,Iu)}};var OP={Apple:"Apple",Google:"Google"},zr=z.object({PremiumID:z.string().nullish(),PurchaseDate:z.string().nullish(),ExpirationDate:z.string().nullish(),TransactionID:z.string().nullish(),IsAutoRenewEnabled:z.boolean().nullish()}).passthrough(),wr=z.object({Subscriptions:z.record(z.string(),zr).nullish(),ActivatedTrialIDs:z.array(z.string()).nullish(),MaxActiveTier:z.number().nullish()}).passthrough().transform(o=>o),EP=z.object({PremiumID:z.string().nullish(),DisplayName:z.string().nullish(),Tier:z.number().nullish(),DurationDays:z.number().nullish(),TrialDurationDays:z.number().nullish(),PriceOptions:he.nullish(),Benefits:z.record(z.string(),z.string()).nullish()}).passthrough(),ol=z.object({Definitions:z.record(z.string(),EP).nullish()}).passthrough(),Dm=z.object({Premium:ol.nullish()}),Im=z.object({ServerTimeUtc:u.nullish(),Premium:wr.nullish()}),kr=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u.nullish(),Premium:wr.nullish(),Subscription:zr.nullish(),Resources:O.nullish()}),un={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var qP={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},UP=z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Pm=z.object({StartUtc:u.nullish(),EndUtc:u.nullish(),Gate:ee.nullish(),Limits:Ie.nullish()}).passthrough(),al=z.object({ResourceAction:z.string().nullish(),RevokeEntitlement:z.boolean().nullish(),BlockFuturePurchases:z.boolean().nullish()}).passthrough(),LP=z.object({PremiumID:z.string().nullish(),RenewalRewards:$.nullish(),FallbackDurationDays:z.number().nullish(),RevokeOnRefund:z.boolean().nullish()}).passthrough(),BP=z.object({Rewards:J.nullish(),Rules:J.nullish(),Refund:J.nullish()}).passthrough(),GP=z.object({ProductID:z.string().nullish(),Name:z.string().nullish(),Type:UP.nullish(),Enabled:z.boolean().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish(),Rewards:$.nullish(),PriceUsdCents:z.number().nullish(),TelegramStarsPrice:z.number().nullish(),Rules:Pm.nullish(),Refund:al.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Subscription:LP.nullish(),Presets:BP.nullish()}).passthrough(),NP=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(),_P=z.object({Rewards:$.nullish()}).passthrough(),VP=z.object({Rules:Pm.nullish()}).passthrough(),jP=z.object({Refund:al.nullish()}).passthrough(),FP=z.object({Rewards:z.record(z.string(),_P).nullish(),Rules:z.record(z.string(),VP).nullish(),Refund:z.record(z.string(),jP).nullish()}).passthrough(),WP=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(),KP=z.object({Enabled:z.boolean().nullish(),Products:z.record(z.string(),GP).nullish(),Stores:z.record(z.string(),NP).nullish(),Presets:FP.nullish(),Validation:WP.nullish(),Refund:al.nullish()}).passthrough(),vm=z.object({ProductID:z.string().nullish(),TotalPurchases:z.number().nullish(),DailyPurchases:z.number().nullish(),DailyResetUtc:u.nullish(),LastPurchasedAt:u.nullish(),Owned:z.boolean().nullish(),Refunded:z.boolean().nullish(),PurchaseBlocked:z.boolean().nullish(),Store:z.string().nullish(),LastTransactionID:z.string().nullish()}).passthrough(),Am=z.object({ProductID:z.string().nullish(),PremiumID:z.string().nullish(),Store:z.string().nullish(),OriginalTransactionID:z.string().nullish(),LastTransactionID:z.string().nullish(),ExpiresAt:u.nullish(),AutoRenew:z.boolean().nullish(),Status:z.string().nullish(),RenewalCount:z.number().nullish(),LastStoreCheckAt:u.nullish(),LastStoreCheckError:z.string().nullish(),UpdatedAt:u.nullish()}).passthrough(),QP=z.object({Products:z.record(z.string(),vm).nullish(),LifetimeSpendUsdCents:z.number().nullish(),Subscriptions:z.record(z.string(),Am).nullish(),LastRefundCheckAt:u.nullish(),TotalPurchases:z.number().nullish(),FirstPurchaseAt:u.nullish(),LastPurchaseAt:u.nullish()}).passthrough(),HP=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(),Tm=z.object({ServerTimeUtc:u,Purchase:KP.nullish(),Availability:z.array(HP).nullish()}),zm=z.object({ServerTimeUtc:u,Purchase:QP.nullish()}),$P={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},JP=z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),ll=z.object({ServerTimeUtc:u,Store:m.nullish(),ProductID:z.string().nullish(),TransactionID:z.string().nullish(),Status:JP.nullish(),Granted:z.boolean().nullish(),Quantity:z.number().nullish(),Resources:O.nullish(),Inventory:Q.nullish(),ProductState:vm.nullish(),Premium:wr.nullish(),Subscription:zr.nullish(),SubscriptionMirror:Am.nullish()}).passthrough(),wm=z.object({ServerTimeUtc:u,ProductID:z.string().nullish(),Stars:z.number().nullish(),InvoiceLink:z.string(),ExpiresAt:u.nullish()}).passthrough(),km=Tt(ll),cn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var Mr=class extends _{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(cn.GetDefinitions,e,Tm)}getUserState(e){return this.send(cn.GetUserState,e,zm)}validatePurchase(e){return this.send(cn.ValidatePurchase,e,ll)}validatePurchasesBatch(e){return this.send(cn.ValidatePurchasesBatch,e,km)}createTelegramInvoice(e){return this.send(cn.CreateTelegramInvoice,e,wm)}};var ZP=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),Mm=z.object({Reward:$.nullish(),Weight:z.number().nullish(),AmountRange:ZP.nullish()}).passthrough(),wn=z.object({SlotID:z.string().nullish(),MinRolls:z.number().nullish(),MaxRolls:z.number().nullish(),Pool:z.array(Mm).nullish()}).passthrough(),kn=z.object({RuleID:z.string().nullish(),Threshold:z.number().nullish(),Pool:z.array(Mm).nullish()}).passthrough(),YP=z.object({RewardSlots:z.array(wn).nullish()}).passthrough(),XP=z.object({PityRules:z.array(kn).nullish()}).passthrough(),Or=z.object({SlotPresets:z.record(z.string(),YP).nullish(),PityPresets:z.record(z.string(),XP).nullish()}).passthrough();var ev=z.object({RuleID:z.string(),BoxIndex:z.number().nullish()}),Om=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u,LootboxID:z.string(),OpenedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish(),Results:z.array(O).nullish(),TriggeredPity:z.array(ev).nullish()}),tv=z.object({RewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),nv=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxDrops:H.nullish()}).passthrough(),iv=z.object({LootboxID:z.string(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:he.nullish(),RewardSlots:z.array(wn).nullish(),PityRules:z.array(kn).nullish(),Presets:tv.nullish(),RewardMultiplier:ui.nullish(),SupplyLimits:z.array(nv).nullish(),MaxOpenCount:z.number().nullish()}).passthrough(),sv=z.object({MaxOpenCount:z.number().nullish()}).passthrough(),ul=z.object({Definitions:z.record(z.string(),iv).nullish(),RewardPools:Or.nullish(),Settings:sv.nullish()}).passthrough(),Em=z.object({LootboxDefinitions:ul.nullish()}),Er={GetDefinitions:"GetDefinitions",Open:"Open"};var qr=class extends _{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(Er.GetDefinitions,e,Em)}open(e){return this.send(Er.Open,e,Ae(Om))}};var rv=z.object({}).passthrough().transform(o=>o),ov=z.object({}).passthrough().transform(o=>o),av=z.object({}).passthrough().transform(o=>o),lv=z.object({}).passthrough().transform(o=>o),uv=z.object({}).passthrough().transform(o=>o),cv=z.object({}).passthrough().transform(o=>o),qm=z.object({ServerTimeUtc:u,CalendarID:z.string(),DayNumber:z.number().nullish(),DailyState:rv,Resources:O.nullish(),Inventory:Q.nullish()}),Um=z.object({ServerTimeUtc:u,AccrualID:z.string(),AccruedSeconds:H.nullish(),AppliedRatePerSecond:z.number().nullish(),IdleState:ov,Resources:O.nullish(),Inventory:Q.nullish()}),Lm=z.object({ServerTimeUtc:u,ComebackID:z.string(),ClaimedTierIndex:z.number().nullish(),ComebackState:av,Resources:O.nullish(),Inventory:Q.nullish()}),Bm=z.object({ServerTimeUtc:u,ClaimID:z.string(),ClaimState:lv,Resources:O.nullish(),Inventory:Q.nullish()}),pv={None:"None",Ad:"Ad",Vip:"Vip"},Gm=z.object({ServerTimeUtc:u,WindowID:z.string(),Boost:z.string().nullish(),BaseAmount:H.nullish(),Multiplier:z.number().nullish(),Granted:H.nullish(),WindowState:uv,Resources:O.nullish(),Inventory:Q.nullish()}),Nm=z.object({Enabled:z.boolean(),Multiplier:z.number().nullish(),Progress:H.nullish(),Source:z.string().nullish(),SourceKey:z.string().nullish()}),hv=z.object({RewardMode:z.string().nullish(),RewardStackLowerTiers:z.boolean().nullish()}).passthrough(),dv=z.object({DayNumber:z.number().nullish(),Rewards:$.nullish(),IsMilestone:z.boolean().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),ti=z.object({Gate:ee.nullish(),Limits:Ie.nullish()}).passthrough(),cl=z.object({Availability:J.nullish()}).passthrough(),mv=z.object({Availability:z.record(z.string(),ti).nullish()}).passthrough(),fv=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(dv).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:ti.nullish(),Presets:cl.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),gv=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Multiplier:z.number().nullish()}).passthrough(),yv=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(gv).nullish()}).passthrough(),Rv=z.object({MinCharacterLevel:z.number().nullish(),RequirementsCharacterID:z.string().nullish(),Availability:ti.nullish(),RequiredItemIDs:z.array(z.string()).nullish(),RequiredEquippedItemIDs:z.array(z.string()).nullish()}).passthrough(),Cv=z.object({AccrualID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rate:yv.nullish(),Rewards:$.nullish(),MaxAccumulationSeconds:z.number().nullish(),MinClaimSeconds:z.number().nullish(),Requirements:Rv.nullish(),FirstClaimMode:z.string().nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),Sv=z.object({MinAbsenceSeconds:z.number().nullish(),Rewards:$.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),xv=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(Sv).nullish(),ClaimCooldownSeconds:z.number().nullish(),ClaimWindowSeconds:z.number().nullish(),TrackPresenceOnRead:z.boolean().nullish(),Availability:ti.nullish(),Presets:cl.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),bv=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(),Dv=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:$.nullish(),PremiumLimitOverrides:z.array(bv).nullish(),Availability:ti.nullish(),Presets:cl.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),Iv=z.object({CurrencyID:z.string().nullish(),MaxBaseAmount:z.number().nullish(),AdPlacementID:z.string().nullish(),AdMultiplier:z.number().nullish(),VipMultiplier:z.number().nullish(),VipPremiumID:z.string().nullish(),Limits:z.record(z.string(),z.unknown()).nullish()}).passthrough(),pl=z.object({TierRewards:hv.nullish(),MilestoneRewardMultiplier:ui.nullish(),DailyCalendars:z.record(z.string(),fv).nullish(),IdleAccruals:z.record(z.string(),Cv).nullish(),Comebacks:z.record(z.string(),xv).nullish(),Claims:z.record(z.string(),Dv).nullish(),Windows:z.record(z.string(),Iv).nullish(),Presets:mv.nullish()}).passthrough(),_m=z.object({RewardDefinitions:pl.nullish()}),Vm=z.object({Rewards:cv.nullish()}),Ot={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var Ur=class extends _{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Ot.GetRewardDefinitions,e,_m)}getUserRewardsState(e){return this.send(Ot.GetUserRewardsState,e,Vm)}getMilestoneRewardMultiplier(e){return this.send(Ot.GetMilestoneRewardMultiplier,e,Nm)}claimDailyReward(e){return this.send(Ot.ClaimDailyReward,e,qm)}collectIdleAccrual(e){return this.send(Ot.CollectIdleAccrual,e,Um)}claimComebackReward(e){return this.send(Ot.ClaimComebackReward,e,Lm)}claimReward(e){return this.send(Ot.ClaimReward,e,Bm)}claimRewardWindow(e){return this.send(Ot.ClaimRewardWindow,e,Gm)}};var Lr=class extends _{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(dt.GetTutorialDefinitions,e,ou)}getUserTutorialState(e){return this.send(dt.GetUserTutorialState,e,hi)}startFlow(e){return this.send(dt.StartFlow,e,Ft)}reportStepShown(e){return this.send(dt.ReportStepShown,e,Ft)}completeStep(e){return this.send(dt.CompleteStep,e,Ft)}completeStepsBatch(e){return this.send(dt.CompleteStepsBatch,e,uu)}skipStep(e){return this.send(dt.SkipStep,e,Ft)}skipFlow(e){return this.send(dt.SkipFlow,e,Ft)}claimFlowReward(e){return this.send(dt.ClaimFlowReward,e,lu)}resetFlow(e){return this.send(dt.ResetFlow,e,Ft)}};var Pv={Open:"Open",Application:"Application"},vv=z.enum(["Open","Application"]).catch("Open"),Av={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},jm=z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),Tv={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},hl=z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),zv={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var pn={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},wv=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(),Fm=z.object({IsEnabled:z.boolean().nullish(),CreatorPortalUrl:z.string().nullish(),ParticipationMode:vv.nullish(),IsCreator:z.boolean().nullish(),CreatorStatus:jm.nullish(),VerificationCode:z.string().nullish(),TeamID:z.string().nullish(),Campaigns:z.array(wv).nullish()}).passthrough(),kv=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(),Mv=z.object({CampaignID:z.string().nullish(),CurrencyKind:hl.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(),kv).nullish(),ComputedAt:z.string().nullish()}).passthrough(),Ov=z.object({PayoutID:z.string().nullish(),CampaignID:z.string().nullish(),Amount:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:hl.nullish(),NetworkID:z.string().nullish(),PaidAt:z.string().nullish()}).passthrough(),Wm=z.object({ServerTimeUtc:z.string().nullish(),HoldDays:z.number().nullish(),Campaigns:z.array(Mv).nullish(),Payouts:z.array(Ov).nullish()}).passthrough(),Km=z.object({CampaignID:z.string().nullish(),PayoutID:z.string().nullish(),Claimed:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:hl.nullish(),NetworkID:z.string().nullish(),RemainingFraction:z.number().nullish(),IdempotentReplay:z.boolean().nullish(),Message:z.string().nullish()}).passthrough(),Ev=z.object({To:z.string().nullish(),Amount:z.string().nullish()}).passthrough(),qv=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(Ev).nullish()}).passthrough(),Uv=z.object({Kind:z.string().nullish(),Target:z.string().nullish(),Required:z.number().nullish(),Actual:z.number().nullish(),Passed:z.boolean().nullish()}).passthrough(),Qm=z.object({Passed:z.boolean().nullish(),Approved:z.boolean().nullish(),Status:jm.nullish(),WalletMissing:z.boolean().nullish(),WalletConnectAllowed:z.boolean().nullish(),Conditions:z.array(Uv).nullish()}).passthrough(),Lv=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),Bv=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(Lv).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(),Hm=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:qv.nullish(),SolanaSignature:Bv.nullish(),StateDelta:Tn.nullish()}).passthrough();var Br=class extends _{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(pn.GetCommunityMarketingState,e,Fm)}getEarnings(e){return this.send(pn.GetEarnings,e,Wm)}claim(e){return this.send(pn.Claim,e,Km)}checkJoinEligibility(e){return this.send(pn.CheckJoinEligibility,e,Qm)}withdrawCryptoReward(e){return this.send(pn.WithdrawCryptoReward,e,Hm)}};var Gr=class extends _{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(et.GetChatDefinitions,e,Vu)}getChannels(e){return this.send(et.GetChannels,e,Ji)}poll(e){return this.send(et.Poll,e,ju)}getHistory(e){return this.send(et.GetHistory,e,Fu)}getConversations(e){return this.send(et.GetConversations,e,Qu)}sendMessage(e){return this.send(et.SendMessage,e,Wu)}openDirectChannel(e){return this.send(et.OpenDirectChannel,e,Ku)}markRead(e){return this.send(et.MarkRead,e,Pn)}joinChannel(e){return this.send(et.JoinChannel,e,Pn)}leaveChannel(e){return this.send(et.LeaveChannel,e,Pn)}reportMessage(e){return this.send(et.ReportMessage,e,Hu)}ignoreUser(e){return this.send(et.IgnoreUser,e,Pn)}unignoreUser(e){return this.send(et.UnignoreUser,e,Pn)}};var Nr=class extends _{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(vn.GetPushConfig,e,Zu)}subscribePush(e){return this.send(vn.SubscribePush,e,Qo)}unsubscribePush(e){return this.send(vn.UnsubscribePush,e,Ke)}getPushSubscriptions(e){return this.send(vn.GetPushSubscriptions,e,Yu)}};var _r=class extends _{constructor(e){super(e,"Localization");}send(e,t,n,i){let s=this.endpoint(e,t);return super.send(e,t,n,{throttleKey:t.Locale?`${s}:${t.Locale}`:s,...i})}getLocalizationManifest(e){return this.send(xr.GetLocalizationManifest,e,am)}getLocalizationTable(e){return this.send(xr.GetLocalizationTable,e,lm)}};var Vr=class extends _{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(bt.GetQuestDefinitions,e,pi)}getUserQuestState(e){return this.send(bt.GetUserQuestState,e,Hl)}refreshQuestCycles(e){return this.send(bt.RefreshQuestCycles,e,Ke)}claimQuestReward(e){return this.send(bt.ClaimQuestReward,e,Mo)}claimQuestRewardsBatch(e){return this.send(bt.ClaimQuestRewardsBatch,e,Zl)}claimMilestoneReward(e){return this.send(bt.ClaimMilestoneReward,e,Oo)}claimMilestoneRewardsBatch(e){return this.send(bt.ClaimMilestoneRewardsBatch,e,Yl)}claimGroupCompletionReward(e){return this.send(bt.ClaimGroupCompletionReward,e,$l)}addQuestProgress(e){return this.send(bt.AddQuestProgress,e,Jl)}};var jr=class extends _{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ft.GetActiveEvents,e,is)}getDefinitions(e){return this.send(ft.GetDefinitions,e,ns)}getUserLteState(e){return this.send(ft.GetUserLteState,e,nc)}grantTokens(e){return this.send(ft.GrantTokens,e,O)}spendTokens(e){return this.send(ft.SpendTokens,e,Jo)}claimMilestone(e){return this.send(ft.ClaimMilestone,e,Zo)}claimMilestonesBatch(e){return this.send(ft.ClaimMilestonesBatch,e,Yo)}claimAllMilestones(e){return this.send(ft.ClaimAllMilestones,e,Yo)}spendTokensBatch(e){return this.send(ft.SpendTokensBatch,e,ic)}grantTokensBatch(e){return this.send(ft.GrantTokensBatch,e,sc)}};var Fr=class extends _{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Je.GetDefinitions,e,cs)}getLeaderboard(e){return this.send(Je.GetLeaderboard,e,_n)}getMyProgress(e){return this.send(Je.GetMyProgress,e,rs)}submitScore(e){return this.send(Je.SubmitScore,e,os)}submitScoreFromSource(e){return this.send(Je.SubmitScoreFromSource,e,os)}claimCycleReward(e){return this.send(Je.ClaimCycleReward,e,as)}claimMilestone(e){return this.send(Je.ClaimMilestone,e,ls)}getFriendsLeaderboard(e){return this.send(Je.GetFriendsLeaderboard,e,_n)}getLeaderboardsBatch(e){return this.send(Je.GetLeaderboardsBatch,e,ac)}getProgressBatch(e){return this.send(Je.GetProgressBatch,e,us)}claimCycleRewardsBatch(e){return this.send(Je.ClaimCycleRewardsBatch,e,lc)}claimMilestonesBatch(e){return this.send(Je.ClaimMilestonesBatch,e,uc)}submitScoresBatch(e){return this.send(Je.SubmitScoresBatch,e,cc)}claimAllRewardsBatch(e){return this.send(Je.ClaimAllRewardsBatch,e,pc)}getOverviewBatch(e){return this.send(Je.GetOverviewBatch,e,hc)}};var Wr=class extends _{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Qt.GetDefinitions,e,ds)}getActiveSeason(e){return this.send(Qt.GetActiveSeason,e,hs)}getUserState(e){return this.send(Qt.GetUserState,e,Xo)}grantStatusTokens(e){return this.send(Qt.GrantStatusTokens,e,gc)}claimTierReward(e){return this.send(Qt.ClaimTierReward,e,ea)}claimTierRewardsBatch(e){return this.send(Qt.ClaimTierRewardsBatch,e,yc)}};var Kr=class extends _{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(un.GetDefinitions,e,Dm)}getUserState(e){return this.send(un.GetUserState,e,Im)}activateTrial(e){return this.send(un.ActivateTrial,e,kr)}purchaseItemOrCurrency(e){return this.send(un.PurchaseWithResources,e,Ae(kr))}purchaseRealMoney(e){return this.send(un.PurchaseRealMoney,e,kr)}};var Qr=class extends _{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(He.GetCharacterDefinitions,e,ys)}getUserCharacters(e){return this.send(He.GetUserCharacters,e,Dc)}unlockCharacter(e){return this.send(He.UnlockCharacter,e,Ae(ia))}upgradeStatLevel(e){return this.send(He.UpgradeStatLevel,e,Ae(ta))}upgradeCharacterLevel(e){return this.send(He.UpgradeCharacterLevel,e,Ae(na))}equipItems(e){return this.send(He.EquipItems,e,Ic)}unequipItems(e){return this.send(He.UnequipItems,e,Pc)}unequipAllCharacters(e){return this.send(He.UnequipAllCharacters,e,vc)}unlockCharactersBatch(e){return this.send(He.UnlockCharactersBatch,e,Mc)}upgradeCharacterLevelsBatch(e){return this.send(He.UpgradeCharacterLevelsBatch,e,Oc)}upgradeStatLevelsBatch(e){return this.send(He.UpgradeStatLevelsBatch,e,Ec)}unlockSkin(e){return this.send(He.UnlockSkin,e,Ae(Ac))}equipSkin(e){return this.send(He.EquipSkin,e,Tc)}unequipSkin(e){return this.send(He.UnequipSkin,e,zc)}getCharacterSkins(e){return this.send(He.GetCharacterSkins,e,wc)}selectCharacter(e){return this.send(He.SelectCharacter,e,kc)}};var Hr=class extends _{constructor(e){super(e,"Match");}createMatch(e){return this.send(kt.CreateMatch,e,Ep)}updateMatch(e){return this.send(kt.UpdateMatch,e,qp)}cancelMatch(e){return this.send(kt.CancelMatch,e,Up)}instantBattle(e){return this.send(kt.InstantBattle,e,Lp)}saveStrategy(e){return this.send(kt.SaveStrategy,e,Ke)}getMyMatches(e){return this.send(kt.GetMyMatches,e,Ra)}getAvailableMatches(e){return this.send(kt.GetAvailableMatches,e,Ra)}getDefinitions(e){return this.send(kt.GetDefinitions,e,_p)}};var Gv={Arena:"Arena"},Jm=z.string(),Mn={GetState:"GetState",RefreshOpponents:"RefreshOpponents",Attempt:"Attempt",ClaimMilestone:"ClaimMilestone"},Nv=z.object({TierID:z.string().nullish(),MinPowerRatio:z.number().nullish(),MaxPowerRatio:z.number().nullish(),PointsOnWin:z.number().nullish(),BotStatScale:z.number().nullish()}).passthrough(),_v=z.object({RuleID:z.string().nullish(),Tiers:z.array(Nv).nullish(),RefreshCooldownSeconds:z.number().nullish(),LiveOpponentActiveDays:z.number().nullish(),MaxCandidateReads:z.number().nullish(),RevengeEnabled:z.boolean().nullish(),RevengeCost:z.number().nullish(),RevengePoints:z.number().nullish(),WinReward:$.nullish()}).passthrough(),Vv=z.object({ChallengeID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish(),Mode:Jm.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AttemptCost:z.number().nullish(),DailyAttemptLimit:z.number().nullish(),Points:At.nullish(),Milestones:z.record(z.string(),Ve).nullish(),ClaimMode:z.string().nullish(),Arena:_v.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),jv=z.object({ChainID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:Re.nullish(),Challenges:z.array(Vv).nullish(),Ticket:At.nullish(),Gate:ee.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Zm=z.object({Chains:z.record(z.string(),jv).nullish()}).passthrough(),Ym=z.object({TierID:z.string().nullish(),OpponentID:z.string().nullish(),IsBot:z.boolean().nullish(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),Country:z.string().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),BotStatScale:z.number().nullish(),Defeated:z.boolean().nullish()}).passthrough(),Fv=z.object({RevengeID:z.string().nullish(),InstanceKey:z.string().nullish(),AttackerUserID:z.string().nullish(),AttackerName:z.string().nullish(),AttackerAvatarUrl:z.string().nullish(),AttackerPower:z.number().nullish(),CreatedAtUtc:u.nullish(),Used:z.boolean().nullish()}).passthrough(),Wv=z.object({AttemptID:z.string().nullish(),InstanceKey:z.string().nullish(),OpponentID:z.string().nullish(),TierID:z.string().nullish(),IsRevenge:z.boolean().nullish(),Win:z.boolean().nullish(),PointsGranted:z.number().nullish(),TicketsSpent:z.number().nullish(),AtUtc:u.nullish()}).passthrough(),Kv=z.object({Opponents:z.array(Ym).nullish(),Revenges:z.array(Fv).nullish(),RevengeCost:z.number().nullish(),RevengePoints:z.number().nullish(),RefreshAvailableAtUtc:u.nullish()}).passthrough(),$m=z.object({ChallengeID:z.string().nullish(),Mode:Jm.nullish(),InstanceKey:z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),AttemptCost:z.number().nullish(),AttemptsToday:z.number().nullish(),DailyAttemptLimit:z.number().nullish(),PointsEarned:z.number().nullish(),ClaimedMilestoneIDs:z.array(z.string()).nullish(),Arena:Kv.nullish()}).passthrough(),Qv=z.object({ChainID:z.string().nullish(),Tickets:z.number().nullish(),Active:$m.nullish(),Ended:z.array($m).nullish()}).passthrough(),Hv=z.object({ChainID:z.string().nullish(),InstanceKey:z.string().nullish(),TicketsBurned:z.number().nullish(),CurrencyID:z.string().nullish(),Converted:z.number().nullish(),CarriedToInstanceKey:z.string().nullish()}).passthrough(),dl=z.object({Chains:z.array(Qv).nullish(),ServerTimeUtc:u.nullish(),Burns:z.array(Hv).nullish(),Rewards:O.nullish(),Inventory:Q.nullish()}).passthrough(),Xm=z.object({ChainID:z.string().nullish(),InstanceKey:z.string().nullish(),Attempt:Wv.nullish(),IsReplay:z.boolean().nullish(),Battle:Wn.nullish(),Opponent:Ym.nullish(),Tickets:z.number().nullish(),PointsEarned:z.number().nullish(),Rewards:O.nullish(),Inventory:Q.nullish()}).passthrough(),ef=z.object({ChainID:z.string().nullish(),InstanceKey:z.string().nullish(),MilestoneID:z.string().nullish(),Rewards:O.nullish(),Inventory:Q.nullish()}).passthrough();var $r=class extends _{constructor(e){super(e,"Challenge");}getState(e){return this.send(Mn.GetState,e,dl)}refreshOpponents(e){return this.send(Mn.RefreshOpponents,e,dl)}attempt(e){return this.send(Mn.Attempt,e,Xm)}claimMilestone(e){return this.send(Mn.ClaimMilestone,e,ef)}};var $v={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},tf=z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),Jv={None:"None",Min:"Min",Average:"Average",Max:"Max",Weighted:"Weighted"},Zv=z.enum(["None","Min","Average","Max","Weighted"]).catch("None"),Yv={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},Xv=z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),eA={Clamp:"Clamp",Reject:"Reject"},tA=z.enum(["Clamp","Reject"]).catch("Clamp"),nA=z.object({ItemInstanceID:z.string().nullish(),ItemID:z.string().nullish(),Level:z.number().nullish(),Units:z.number().nullish()}),iA=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:vt.nullish(),OutputLevel:z.number().nullish(),BurnedInstances:z.array(nA).nullish()}),nf=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u,Type:tf.nullish(),CraftID:z.string(),CraftedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),InputRarity:z.string().nullish(),OutputRarity:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish(),Results:z.array(iA).nullish()}),sA=z.object({CraftID:z.string().nullish(),Type:tf.nullish(),CatalogID:z.string().nullish(),CollectionID:z.string().nullish(),InputRarityID:z.string().nullish(),OutputRarityID:z.string().nullish(),RequiredItemCount:z.number().nullish(),PriceOptions:he.nullish(),OutputLevelMode:Zv.nullish(),OutputLevelWeightPower:z.number().nullish(),InputSelection:Xv.nullish(),OutputLevelOverflow:tA.nullish()}).passthrough(),ml=z.object({Definitions:z.record(z.string(),sA).nullish()}).passthrough(),sf=z.object({ServerTimeUtc:u.nullish(),CraftDefinitions:ml.nullish()}),Jr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Zr=class extends _{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Jr.GetDefinitions,e,sf)}craft(e){return this.send(Jr.Craft,e,Ae(nf))}};var rA=2e5,Yr=class extends _{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,Ae(bs),{timeoutMs:rA,autoRetry:false})}readGeneration(e,t){return this.send(e,t,bs,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(je.GetDefinitions,e,Wc)}generateText(e){return this.generate(je.GenerateText,e)}getText(e){return this.readGeneration(je.GetText,e)}generateImage(e){return this.generate(je.GenerateImage,e)}editImage(e){return this.generate(je.EditImage,e)}getImage(e){return this.readGeneration(je.GetImage,e)}generateVideo(e){return this.generate(je.GenerateVideo,e)}getVideo(e){return this.readGeneration(je.GetVideo,e)}generateAudio(e){return this.generate(je.GenerateAudio,e)}getAudio(e){return this.readGeneration(je.GetAudio,e)}generateMusic(e){return this.generate(je.GenerateMusic,e)}getMusic(e){return this.readGeneration(je.GetMusic,e)}generateFromTemplate(e){return this.generate(je.GenerateFromTemplate,e)}estimateTemplatePrice(e){return this.send(je.EstimateTemplatePrice,e,Fc,{throttleKey:`AI:EstimateTemplatePrice:${e.FeatureKey??""}:${JSON.stringify(e.Params??{})}`})}generateThreeD(e){return this.generate(je.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(je.GetThreeD,e)}listGenerations(e){return this.send(je.ListGenerations,e,Vc)}getGeneration(e){return this.readGeneration(je.GetGeneration,e)}};var oA={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},aA=z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),rf=z.object({}).passthrough().transform(o=>o),On=z.object({CollectibleID:z.string(),Rarity:z.number().nullish(),IsSpecial:z.boolean().nullish(),IsDuplicate:z.boolean().nullish(),CollectionCurrencyConverted:z.number().nullish()}),of=z.object({GrantedCollectibles:z.array(On).nullish(),DuplicateCollectibles:z.array(On).nullish(),CollectionCurrencyEarned:H.nullish()}),af=z.object({CreditsConfirmation:ge.nullish(),OpenedCount:z.number().nullish(),Packs:z.array(of).nullish(),GrantedCollectibles:z.array(On).nullish(),DuplicateCollectibles:z.array(On).nullish(),CollectionCurrencyEarned:H.nullish(),NewCollectionCurrencyBalance:H.nullish(),NewlyCompletedSetIDs:z.array(z.string()).nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:O.nullish(),Inventory:Q.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),lf=z.object({OpenedCount:z.number().nullish(),Chests:z.array(of).nullish(),GrantedCollectibles:z.array(On).nullish(),DuplicateCollectibles:z.array(On).nullish(),CollectionCurrencyEarned:H.nullish(),NewCollectionCurrencyBalance:H.nullish(),Resources:O.nullish(),Inventory:Q.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),uf=z.object({GrantedCollectibleID:z.string().nullish(),NewlyCompletedSetID:z.string().nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),fl=z.object({SetID:z.string(),Resources:O.nullish(),Inventory:Q.nullish()}),cf=z.array(ke(fl)),pf=z.object({Resources:O.nullish(),Inventory:Q.nullish()}),lA=z.object({OfferID:z.string(),TitleID:z.string().nullish(),CollectionID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderPublicData:Be.nullish(),OfferedCollectibleID:z.string().nullish(),OfferedCollectibleIsSpecial:z.boolean().nullish(),ReceiverUserID:z.string().nullish(),RequestedCollectibleID:z.string().nullish(),RequestedCollectibleIsSpecial:z.boolean().nullish(),Status:aA.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RespondedAtUtc:u.nullish(),DeclineReason:z.string().nullish(),IsSpecialTradeEvent:z.boolean().nullish(),SpecialTradeEventID:z.string().nullish()}).passthrough(),hf=z.object({OfferID:z.string(),ExpiresAtUtc:u.nullish(),Resources:O.nullish()}),df=z.object({OfferID:z.string(),Resources:O.nullish()}),mf=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()}),ff=z.object({OfferID:z.string(),Resources:O.nullish()}),gl=z.object({Offers:z.array(lA).nullish()}),uA=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(),cA=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(uA).nullish(),SetCompletionReward:$.nullish()}).passthrough(),pA=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(cA).nullish(),GrandPrize:$.nullish()}).passthrough(),gf=z.object({BonusRewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),hA=z.object({PackTypeID:z.string().nullish(),PriceOptions:he.nullish(),BonusRewardSlots:z.array(wn).nullish(),PityRules:z.array(kn).nullish(),Presets:gf.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(),dA=z.object({Rarity:z.number().nullish(),CollectionCurrencyGranted:z.number().nullish()}).passthrough(),mA=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(wn).nullish(),PityRules:z.array(kn).nullish(),Presets:gf.nullish(),Tier:z.number().nullish()}).passthrough(),fA=z.object({SpecialTradeEventID:z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),AllowedSpecialCollectibleIDs:z.array(z.string()).nullish(),SpecialTradeEventDailyTradeLimit:z.number().nullish()}).passthrough(),gA=z.object({MaxPackOpenCount:z.number().nullish(),MaxChestOpenCount:z.number().nullish()}).passthrough(),Xr=z.object({Collections:z.record(z.string(),pA).nullish(),PackTypes:z.record(z.string(),hA).nullish(),CollectionChests:z.array(mA).nullish(),DuplicateConversions:z.array(dA).nullish(),DailyTradeLimit:z.number().nullish(),CollectibleJokerCatalogID:z.string().nullish(),CollectibleJokerItemID:z.string().nullish(),SpecialTradeEvents:z.array(fA).nullish(),RewardPools:Or.nullish(),Settings:gA.nullish()}).passthrough(),Ye={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 eo=class extends _{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ye.GetDefinitions,e,Xr)}getUserState(e){return this.send(Ye.GetUserState,e,rf)}openPack(e){return this.send(Ye.OpenPack,e,Ae(af))}openCollectionChest(e){return this.send(Ye.OpenCollectionChest,e,lf)}useCollectibleJoker(e){return this.send(Ye.UseCollectibleJoker,e,uf)}claimSetReward(e){return this.send(Ye.ClaimSetReward,e,fl)}claimSetRewardsBatch(e){return this.send(Ye.ClaimSetRewardsBatch,e,cf)}claimGrandPrize(e){return this.send(Ye.ClaimGrandPrize,e,pf)}sendTradeOffer(e){return this.send(Ye.SendTradeOffer,e,hf)}cancelTradeOffer(e){return this.send(Ye.CancelTradeOffer,e,df)}acceptTradeOffer(e){return this.send(Ye.AcceptTradeOffer,e,mf)}declineTradeOffer(e){return this.send(Ye.DeclineTradeOffer,e,ff)}getMyTradeOffers(e){return this.send(Ye.GetMyTradeOffers,e,gl)}getIncomingTradeOffers(e){return this.send(Ye.GetIncomingTradeOffers,e,gl)}};var to=class extends _{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(It.GetDefinitions,e,vs)}getActiveEvent(e){return this.send(It.GetActiveEvent,e,Hc)}getUserState(e){return this.send(It.GetUserState,e,Ps)}getGroupState(e){return this.send(It.GetGroupState,e,ua)}joinOrCreateGroup(e){return this.send(It.JoinOrCreateGroup,e,ua)}spin(e){return this.send(It.Spin,e,Ae(Jc))}claimObjectReward(e){return this.send(It.ClaimObjectReward,e,ca)}claimGrandPrize(e){return this.send(It.ClaimGrandPrize,e,ca)}leaveGroup(e){return this.send(It.LeaveGroup,e,Zc)}};var no=class extends _{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(wt.GetDefinition,e,lp)}getUserState(e){return this.send(wt.GetUserState,e,up)}getActiveDeals(e){return this.send(wt.GetActiveDeals,e,zs)}dismissDeal(e){return this.send(wt.DismissDeal,e,pp)}executeNode(e){return this.send(wt.ExecuteNode,e,Ae(cp))}recordShow(e){return this.send(wt.RecordShow,e,hp)}claimMilestone(e){return this.send(wt.ClaimMilestone,e,dp)}claimMilestonesBatch(e){return this.send(wt.ClaimMilestonesBatch,e,mp)}};var yA=z.object({}).passthrough().transform(o=>o),RA=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:Ie.nullish()}).passthrough(),yl=z.object({IsEnabled:z.boolean().nullish(),ActivationReward:$.nullish(),InviteRewards:z.record(z.string(),Ve).nullish(),SpendRewards:z.array(RA).nullish(),Qualification:z.object({}).passthrough().transform(o=>o).nullish()}).passthrough(),Rl=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(),yf=z.object({ReferralDefinitions:yl.nullish()}).passthrough(),Rf=z.object({Referral:yA.nullish(),InviteUrl:z.string().nullish(),Qualification:Rl.nullish()}).passthrough(),Cf=z.object({QualificationPending:z.boolean().nullish(),Qualification:Rl.nullish()}).passthrough(),Sf=z.object({ReferralCode:z.string().nullish(),ReferrerUserID:z.string().nullish(),IsFirstActivation:z.boolean().nullish(),Resources:O.nullish(),Inventory:Q.nullish(),QualificationPending:z.boolean().nullish(),Qualification:Rl.nullish()}).passthrough(),Cl=z.object({RewardID:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}).passthrough(),xf=Tt(Cl),tn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var io=class extends _{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(tn.GetDefinitions,e,yf)}getUserState(e){return this.send(tn.GetUserState,e,Rf)}activateReferralCode(e){return this.send(tn.ActivateReferralCode,e,Sf)}claimInviteReward(e){return this.send(tn.ClaimInviteReward,e,Cl)}claimInviteRewardsBatch(e){return this.send(tn.ClaimInviteRewardsBatch,e,xf)}checkQualification(e){return this.send(tn.CheckQualification,e,Cf)}};var so=class extends _{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(ut.GetDefinitions,e,vp)}getMessages(e){return this.send(ut.GetMessages,e,Ap)}getUnreadCount(e){return this.send(ut.GetUnreadCount,e,Os)}readMessages(e){return this.send(ut.ReadMessages,e,ma)}claimReward(e){return this.send(ut.ClaimReward,e,Es)}claimRewardsBatch(e){return this.send(ut.ClaimRewardsBatch,e,Es)}claimAll(e){return this.send(ut.ClaimAll,e,Es)}deleteMessages(e){return this.send(ut.DeleteMessages,e,ma)}sendGift(e){return this.send(ut.SendGift,e,Tp)}sendTransfer(e){return this.send(ut.SendTransfer,e,zp)}getGiftStatus(e){return this.send(ut.GetGiftStatus,e,wp)}};var ro=class extends _{constructor(e){super(e,"Clan");}getDefinitions(e){return this.send(Ue.GetDefinitions,e,nh)}getMyClans(e){return this.send(Ue.GetMyClans,e,jp)}searchClans(e){return this.send(Ue.SearchClans,e,Da)}getRecommendedClans(e){return this.send(Ue.GetRecommendedClans,e,Da)}getClan(e){return this.send(Ue.GetClan,e,Fp)}getClanMembers(e){return this.send(Ue.GetClanMembers,e,Kp)}getRankings(e){return this.send(Ue.GetRankings,e,Qp)}getApplications(e){return this.send(Ue.GetApplications,e,Ia)}getMyInvites(e){return this.send(Ue.GetMyInvites,e,Ia)}getClanLog(e){return this.send(Ue.GetClanLog,e,Hp)}getRequests(e){return this.send(Ue.GetRequests,e,Jp)}getGifts(e){return this.send(Ue.GetGifts,e,Zp)}getRewards(e){return this.send(Ue.GetRewards,e,Yp)}getTreasury(e){return this.send(Ue.GetTreasury,e,ih)}getProjects(e){return this.send(Ue.GetProjects,e,sh)}getActivities(e){return this.send(Ue.GetActivities,e,rh)}getClanQuests(e){return this.send(Ue.GetClanQuests,e,oh)}getCompetitions(e){return this.send(Ue.GetCompetitions,e,ah)}getBracket(e){return this.send(Ue.GetBracket,e,lh)}getDiplomacy(e){return this.send(Ue.GetDiplomacy,e,uh)}getRevenges(e){return this.send(Ue.GetRevenges,e,ch)}getLeague(e){return this.send(Ue.GetLeague,e,ph)}mutate(e,t){return this.send(e,t,th)}};var oo=class extends _{constructor(e){super(e,"Avatar");}getDefinitions(e){return this.send(An.GetDefinitions,e,_s)}getAvatars(e){return this.send(An.GetAvatars,e,dh)}getShop(e){return this.send(An.GetShop,e,mh)}buyItem(e){return this.send(An.BuyItem,e,fh)}};var ao=class extends _{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(js.RequestAdPermit,e,gh)}completeView(e){return this.send(js.CompleteView,e,yh)}};var lo=class extends _{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(be.GetFriendsList,e,Qn)}getIncomingRequests(e){return this.send(be.GetIncomingRequests,e,Qn)}getOutgoingRequests(e){return this.send(be.GetOutgoingRequests,e,Qn)}getRecommendedFriends(e){return this.send(be.GetRecommendedFriends,e,Qn)}sendFriendRequest(e){return this.send(be.SendFriendRequest,e,Hn)}acceptFriendRequest(e){return this.send(be.AcceptFriendRequest,e,Hn)}declineFriendRequest(e){return this.send(be.DeclineFriendRequest,e,Hn)}removeFriend(e){return this.send(be.RemoveFriend,e,Hn)}getPlayerProfile(e){return this.send(be.GetPlayerProfile,e,Dh)}getInbox(e){return this.send(be.GetInbox,e,Ih)}markInboxSeen(e){return this.send(be.MarkInboxSeen,e,$n)}getInboxUnread(e){return this.send(be.GetInboxUnread,e,$n)}follow(e){return this.send(be.Follow,e,Zt)}unfollow(e){return this.send(be.Unfollow,e,Zt)}getFollowers(e){return this.send(be.GetFollowers,e,Qs)}getFollowing(e){return this.send(be.GetFollowing,e,Qs)}block(e){return this.send(be.Block,e,Zt)}unblock(e){return this.send(be.Unblock,e,Zt)}getBlocked(e){return this.send(be.GetBlocked,e,Qs)}react(e){return this.send(be.React,e,Zt)}unreact(e){return this.send(be.Unreact,e,Zt)}getMyReactions(e){return this.send(be.GetMyReactions,e,vh)}getEntityStates(e){return this.send(be.GetEntityStates,e,Ph)}addComment(e){return this.send(be.AddComment,e,Hs)}editComment(e){return this.send(be.EditComment,e,Hs)}deleteComment(e){return this.send(be.DeleteComment,e,Th)}getComments(e){return this.send(be.GetComments,e,Ah)}report(e){return this.send(be.Report,e,zh)}};var CA={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var hn=z.object({Target:z.string().nullish(),Operation:z.string().nullish(),Value:z.number().nullish()}).passthrough(),SA=z.object({BoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:he.nullish(),Effect:hn.nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),uo=z.object({Schedule:Re.nullish(),Gate:ee.nullish()}).passthrough(),Sl=z.object({Availability:J.nullish(),Effects:J.nullish()}).passthrough(),xA=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(hn).nullish(),Availability:uo.nullish(),Presets:Sl.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),bA=z.object({ChainedBoostID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Effects:z.array(hn).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),DA=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(bA).nullish(),Availability:uo.nullish(),Presets:Sl.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),IA=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(ht).nullish(),Effects:z.array(hn).nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Availability:uo.nullish(),Presets:Sl.nullish()}).passthrough(),PA=z.object({MaxAddPercent:z.number().nullish(),MaxMultiply:z.number().nullish(),MaxAddFlat:z.number().nullish()}).passthrough(),vA=z.object({Effects:z.array(hn).nullish()}).passthrough(),AA=z.object({Availability:z.record(z.string(),uo).nullish(),Effects:z.record(z.string(),vA).nullish()}).passthrough(),TA=z.object({StackingCaps:z.record(z.string(),PA).nullish()}).passthrough(),co=z.object({Definitions:z.record(z.string(),SA).nullish(),ScheduledBoosts:z.record(z.string(),xA).nullish(),BoostChains:z.record(z.string(),DA).nullish(),TriggeredBoosts:z.record(z.string(),IA).nullish(),Settings:TA.nullish(),Presets:AA.nullish()}).passthrough(),bf=z.object({InstanceID:z.string(),BoostID:z.string(),ActivatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RemainingCharges:z.number().nullish(),EffectSnapshot:hn.nullish(),SourceType:z.string().nullish(),SourceRef:z.string().nullish()}).passthrough();z.object({Date:u.nullish(),DailyCount:z.number().nullish(),LastFiredUtc:u.nullish()}).passthrough();var Df=z.object({ServerTimeUtc:u.nullish(),Active:z.record(z.string(),bf).nullish()}),If=z.object({CreditsConfirmation:ge.nullish(),ServerTimeUtc:u.nullish(),BoostID:z.string().nullish(),StackingPolicy:z.string().nullish(),ActivatedBoost:bf.nullish(),Resources:O.nullish()}),zA={Scheduled:"Scheduled",Chain:"Chain"},wA=z.object({Kind:z.string().nullish(),SourceID:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),PhaseOrder:z.number().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),Effects:z.array(hn).nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Pf=z.object({ServerTimeUtc:u.nullish(),Windows:z.array(wA).nullish()}),dn={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var po=class extends _{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(dn.GetDefinitions,e,co)}getActive(e){return this.send(dn.GetActive,e,Df)}getActiveWindows(e){return this.send(dn.GetActiveWindows,e,Pf)}activate(e){return this.send(dn.Activate,e,Ae(If))}cleanupExpired(e){return this.send(dn.CleanupExpired,e,Ke)}};var ho=class extends _{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(Pt.GetUserCustomDataDefinitions,e,Ks)}getMyUserCustomData(e){return this.send(Pt.GetMyUserCustomData,e,Rh)}getPublicUserCustomDataOf(e){return this.send(Pt.GetPublicUserCustomDataOf,e,Ta)}setPrivateData(e){return this.send(Pt.SetPrivateData,e,za)}setPublicData(e){return this.send(Pt.SetPublicData,e,za)}deleteKey(e){return this.send(Pt.DeleteKey,e,Ke)}batchSet(e){return this.send(Pt.BatchSet,e,Ch)}batchDelete(e){return this.send(Pt.BatchDelete,e,Sh)}batchGetPublicUserCustomDataOf(e){return this.send(Pt.BatchGetPublicUserCustomDataOf,e,xh)}};var kA={Static:"Static",Runtime:"Runtime"},MA={Public:"Public",Private:"Private"},OA=z.enum(["Client","Server","System"]).catch("Client"),EA=z.enum(["String","Int","Bool","Json"]).catch("String"),qA=z.object({Value:z.string().nullish(),UpdatedAt:u.nullish(),Version:z.number().nullish(),LastWriter:OA.nullish(),ExpiresAt:u.nullish()}).passthrough(),vf=z.record(z.string(),qA),xl=z.object({StaticVersion:z.number().nullish(),RuntimeVersion:z.number().nullish(),Static:vf.nullish(),Runtime:vf.nullish(),NotModified:z.boolean().nullish()}),UA=z.object({KeyID:z.string(),Scope:z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:EA.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),mo=z.object({Keys:z.record(z.string(),UA).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),ni={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var fo=class extends _{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(ni.GetTitleCustomDataDefinitions,e,mo)}getPublicTitleData(e){return this.send(ni.GetPublicTitleData,e,xl)}getPublicTitleDataKeys(e){return this.send(ni.GetPublicTitleDataKeys,e,xl)}};var Af=z.object({Theme:z.record(z.string(),z.string()).nullish(),Radius:z.number().nullish(),ButtonRadius:z.number().nullish(),Outline:z.number().nullish(),Background:z.string().nullish(),MotionSpeed:z.number().nullish(),MotionIntensity:z.number().nullish(),Particles:z.boolean().nullish(),SoundSet:z.string().nullish()}).passthrough();var LA={Mesh:"Mesh",Host:"Host"},bl=z.enum(["Mesh","Host"]).catch("Mesh"),BA={ServerRelay:"ServerRelay",P2P:"P2P"},Dl=z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),GA={Public:"Public",Private:"Private"},NA=z.enum(["Public","Private"]).catch("Public"),_A={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},VA=z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Tf=z.object({Urls:z.string().nullish(),Username:z.string().nullish(),Credential:z.string().nullish()}).passthrough(),jA=z.object({Enabled:z.boolean().nullish()}).passthrough(),zf=z.object({SystemState:jA.nullish(),DefaultTopology:bl.nullish(),AllowCreatorTopologyOverride:z.boolean().nullish(),DefaultChatMode:Dl.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(Tf).nullish()}).passthrough(),FA=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(),WA=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),Topology:bl.nullish(),ChatMode:Dl.nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),MemberCount:z.number().nullish(),CreatedAt:z.number().nullish()}).passthrough(),KA=z.object({Seq:z.number().nullish(),Type:VA.nullish(),FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Kind:z.string().nullish(),Payload:z.string().nullish(),Ts:z.number().nullish()}).passthrough(),ii=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),OwnerUserID:z.string().nullish(),Topology:bl.nullish(),ChatMode:Dl.nullish(),Visibility:NA.nullish(),Status:z.string().nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),Members:z.array(FA).nullish(),IceServers:z.array(Tf).nullish(),Seq:z.number().nullish(),BannedUserIDs:z.array(z.string()).nullish()}).passthrough(),wf=z.object({Removed:z.boolean().nullish(),Banned:z.boolean().nullish()}).passthrough(),kf=z.object({WasBanned:z.boolean().nullish()}).passthrough(),Il=z.object({Closed:z.boolean().nullish(),NewHostUserID:z.string().nullish()}).passthrough(),Mf=z.object({Rooms:z.array(WA).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}).passthrough(),Of=z.object({Envelopes:z.array(KA).nullish(),MaxSeq:z.number().nullish()}).passthrough(),go=z.object({Seq:z.number().nullish()}).passthrough(),it={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 Pl=z.object({TitleCustomData:mo.nullish(),Character:ys.nullish(),Item:vr.nullish(),Currency:Ms.nullish(),Store:Li.nullish(),Lootbox:ul.nullish(),Quest:pi.nullish(),TimedEvent:ns.nullish(),Leaderboard:cs.nullish(),Season:ds.nullish(),Reward:pl.nullish(),Collection:Xr.nullish(),Craft:ml.nullish(),DealOffer:pa.nullish(),Premium:ol.nullish(),TimedBoost:co.nullish(),CoopEvent:vs.nullish(),GameLoop:tr.nullish(),Match:Ca.nullish(),Challenge:Zm.nullish(),Experiment:nm.nullish(),Blockchain:Ua.nullish(),Marketplace:Wa.nullish(),Multiplayer:zf.nullish(),UserCustomData:Ks.nullish(),Referral:yl.nullish(),Localization:rm.nullish(),Analytics:Wd.nullish(),Social:wh.nullish(),PlatformBridge:kh.nullish(),GameSpec:z.string().nullish(),Look:Af.nullish(),Avatar:_s.nullish()}).passthrough();var mn={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var yo=class extends _{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(mn.GetTitlePublicConfiguration,e,Pl)}getTitlePublicConfigurationExcept(e){return this.send(mn.GetTitlePublicConfigurationExcept,e,Pl)}getCurrencyDefinitions(e){return this.send(mn.GetCurrencyDefinitions,e,Ms)}getItemDefinitions(e){return this.send(mn.GetItemDefinitions,e,vr)}getServerTime(e){return this.send(mn.GetServerTime,e,Ke)}};var Ro=class extends _{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Fe.GetGameLoops,e,tr)}getBoardDefinition(e,t=false){return this.send(Fe.GetBoardDefinition,e,er,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Fe.GetBoardDefinitionForLevel,e,er,{silent:t})}getUserBoardState(e){return this.send(Fe.GetUserBoardState,e,qh)}boardLoopRoll(e){return this.send(Fe.BoardLoopRoll,e,Vh)}boardLoopAttack(e){return this.send(Fe.BoardLoopAttack,e,Wh)}boardLoopRaid(e){return this.send(Fe.BoardLoopRaid,e,Oa)}boardLoopRaidFast(e){return this.send(Fe.BoardLoopRaidFast,e,Oa)}boardLoopBuild(e){return this.send(Fe.BoardLoopBuild,e,Kh)}boardSpecialChoose(e){return this.send(Fe.BoardSpecialChoose,e,Ae(Qh))}boardSpecialApplyMultiplier(e){return this.send(Fe.BoardSpecialApplyMultiplier,e,Hh)}boardRewardBoostApply(e){return this.send(Fe.BoardRewardBoostApply,e,Fh)}boardSpecialClaim(e){return this.send(Fe.BoardSpecialClaim,e,$h)}getCommunityChestState(e){return this.send(Fe.GetCommunityChestState,e,Yh)}joinOrCreateCommunityChest(e){return this.send(Fe.JoinOrCreateCommunityChest,e,Xh)}claimCommunityChestMilestone(e){return this.send(Fe.ClaimCommunityChestMilestone,e,Ea)}claimCommunityChestGrandPrize(e){return this.send(Fe.ClaimCommunityChestGrandPrize,e,Ea)}leaveCommunityChest(e){return this.send(Fe.LeaveCommunityChest,e,ed)}};var QA={Live:"Live",Latest:"Latest",Specific:"Specific"},HA={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},$A=z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),JA={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"},ZA=z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),YA=z.object({Level:$A,Message:z.string().nullish(),Data:Ht.nullish()}),XA=z.object({Error:ZA,Message:z.string().nullish(),StackTrace:z.string().nullish()}),qf=z.object({FunctionName:z.string().nullish(),Revision:z.number().nullish(),FunctionResult:Ht.nullish(),FunctionResultTooLarge:z.boolean().nullish(),Logs:z.array(YA).nullish(),LogsTooLarge:z.boolean().nullish(),ExecutionTimeSeconds:z.number().nullish(),APIRequestsIssued:z.number().nullish(),Error:XA.nullish()}),vl={Execute:"Execute"};var Co=class extends _{constructor(e){super(e,"CloudCode");}execute(e){return this.send(vl.Execute,e,qf)}};var So=class extends _{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(nt.GetDefinitions,e,cd)}getUserState(e){return this.send(nt.GetUserState,e,pd)}depositToken(e){return this.send(nt.DepositToken,e,hd)}depositNFT(e){return this.send(nt.DepositNFT,e,dd)}requestTokenWithdrawal(e){return this.send(nt.RequestTokenWithdrawal,e,md)}requestNFTWithdrawal(e){return this.send(nt.RequestNFTWithdrawal,e,fd)}getTransactionHistory(e){return this.send(nt.GetTransactionHistory,e,gd)}retryWithdrawal(e){return this.send(nt.RetryWithdrawal,e,yd)}confirmWithdrawal(e){return this.send(nt.ConfirmWithdrawal,e,Rd)}donateToDeveloper(e){return this.send(nt.DonateToDeveloper,e,Na)}donateToUsersPool(e){return this.send(nt.DonateToUsersPool,e,Na)}getPlayAccess(e){return this.send(nt.GetPlayAccess,e,ld)}confirmPlayAccess(e){return this.send(nt.ConfirmPlayAccess,e,Yt)}};var xo=class extends _{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Le.GetDefinitions,e,xd)}getGroupedOffers(e){return this.send(Le.GetGroupedOffers,e,bd)}getOffersByItem(e){return this.send(Le.GetOffersByItem,e,Ka)}getOffer(e){return this.send(Le.GetOffer,e,Dd)}getBuyOrders(e){return this.send(Le.GetBuyOrders,e,Ka)}getMyState(e){return this.send(Le.GetMyState,e,cr)}getHistory(e){return this.send(Le.GetHistory,e,Pd)}createListing(e){return this.send(Le.CreateListing,e,Yn)}cancelListing(e){return this.send(Le.CancelListing,e,yt)}buy(e){return this.send(Le.Buy,e,yt)}marketBuy(e){return this.send(Le.MarketBuy,e,yt)}marketSell(e){return this.send(Le.MarketSell,e,yt)}createAuction(e){return this.send(Le.CreateAuction,e,Yn)}placeBid(e){return this.send(Le.PlaceBid,e,Id)}claimAuction(e){return this.send(Le.ClaimAuction,e,yt)}createBuyOrder(e){return this.send(Le.CreateBuyOrder,e,Yn)}cancelBuyOrder(e){return this.send(Le.CancelBuyOrder,e,yt)}fillBuyOrder(e){return this.send(Le.FillBuyOrder,e,yt)}createDirectTrade(e){return this.send(Le.CreateDirectTrade,e,Yn)}respondDirectTrade(e){return this.send(Le.RespondDirectTrade,e,yt)}cancelDirectTrade(e){return this.send(Le.CancelDirectTrade,e,yt)}claimBack(e){return this.send(Le.ClaimBack,e,yt)}};var bo=class extends _{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(it.CreateRoom,e,ii)}joinRoom(e){return this.send(it.JoinRoom,e,ii)}leaveRoom(e,t=false){return this.send(it.LeaveRoom,e,Il,{keepalive:t})}listRooms(e){return this.send(it.ListRooms,e,Mf)}getRoom(e){return this.send(it.GetRoom,e,ii)}closeRoom(e){return this.send(it.CloseRoom,e,Il)}poll(e){return this.send(it.Poll,e,Of)}sendSignal(e){return this.send(it.SendSignal,e,go,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(it.ClaimHost,e,ii)}kickMember(e){return this.send(it.KickMember,e,wf)}unbanMember(e){return this.send(it.UnbanMember,e,kf)}sendChat(e){return this.send(it.SendChat,e,go)}setMemberState(e){return this.send(it.SetMemberState,e,go)}};var eT={Free:"Free",Price:"Price",Holding:"Holding"},Al=z.enum(["Free","Price","Holding"]).catch("Free"),tT={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},nT=z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),iT={All:"All",Any:"Any"},sT=z.enum(["All","Any"]).catch("All"),rT={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},oT=z.enum(["Public","Unlisted","Friends"]).catch("Public"),aT={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},lT=z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),uT={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Lf=z.enum(["Purchase","Free","Holding"]).catch("Free"),cT={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},pT={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},hT=z.enum(["Creator","License","Free","Holding"]).catch("License"),dT=z.object({Type:i.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),Amount:z.number().nullish(),MinLevel:z.number().nullish()}).passthrough(),mT=z.object({Requirements:z.array(dT).nullish(),Match:sT.nullish(),Mode:nT.nullish()}).passthrough(),fT=z.object({OptionID:z.string().nullish(),Mode:Al.nullish(),Price:ce.nullish(),Holding:mT.nullish()}).passthrough(),gT=z.object({AllowedMimeTypes:z.array(z.string()).nullish(),MaxBytes:z.number().nullish(),MaxCount:z.number().nullish(),Required:z.boolean().nullish()}).passthrough(),yT=z.object({DisplayName:z.string().nullish(),Enabled:z.boolean().nullish(),Files:z.record(z.string(),gT).nullish(),ThumbnailRequired:z.boolean().nullish(),AllowedAccessModes:z.array(Al).nullish(),PricePolicy:ur.nullish(),PublishGate:ee.nullish(),PublishFeeOptions:he.nullish(),TagVocabulary:z.array(z.string()).nullish(),MaxPublishedPerPlayer:z.number().nullish(),DailyPublishCap:z.number().nullish()}).passthrough(),RT=z.object({Allowed:z.array(Kn).nullish(),MaxRequirements:z.number().nullish()}).passthrough(),CT=z.object({AutoHideReportThreshold:z.number().nullish(),RequireApproval:z.boolean().nullish(),BlockedTerms:z.array(z.string()).nullish()}).passthrough(),ST=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(),xT=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Schedule:Re.nullish(),Gate:ee.nullish(),Order:z.number().nullish()}).passthrough(),bT=z.object({Enabled:z.boolean().nullish(),Gate:ee.nullish(),Schedule:Re.nullish(),ContentTypes:z.record(z.string(),yT).nullish(),PricePolicy:ur.nullish(),Commission:Fa.nullish(),HoldingPolicy:RT.nullish(),Moderation:CT.nullish(),Limits:ST.nullish(),Featured:z.array(xT).nullish()}).passthrough(),DT=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(),fn=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),CreatorUserID:z.string().nullish(),IsOfficial:z.boolean().nullish(),CreatorPublicData:Be.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:oT.nullish(),Access:z.array(fT).nullish(),Status:lT.nullish(),ModerationNote:z.string().nullish(),Stats:DT.nullish(),Revision:z.number().nullish(),ParentContentID:z.string().nullish(),FileCount:z.number().nullish(),TotalBytes:z.number().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),PublishedAt:u.nullish(),IsMine:z.boolean().nullish(),Owned:z.boolean().nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish()}).passthrough(),IT=z.object({OptionID:z.string().nullish(),Mode:Al.nullish(),Available:z.boolean().nullish()}).passthrough(),Bf=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(),Gf=z.object({Definitions:bT.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish(),CanPublish:z.record(z.string(),z.boolean()).nullish(),Collections:z.array(Bf).nullish()}).passthrough(),Do=z.object({Items:z.array(fn).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Nf=z.object({Content:fn.nullish(),AccessState:z.array(IT).nullish(),CanDownload:z.boolean().nullish()}).passthrough(),_f=z.object({Collection:Bf.nullish(),Items:z.array(fn).nullish()}).passthrough(),Vf=z.object({CreatorUserID:z.string().nullish(),PublicData:Be.nullish(),PublishedCount:z.number().nullish(),FollowerCount:z.number().nullish(),IsFollowing:z.boolean().nullish(),Items:z.array(fn).nullish()}).passthrough(),Uf=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(),jf=z.object({ContentID:z.string().nullish(),Revision:z.number().nullish(),Uploads:z.array(Uf).nullish(),ThumbnailUpload:Uf.nullish(),ExpiresAt:u.nullish()}).passthrough(),Ff=z.object({CreditsConfirmation:ge.nullish(),Content:fn.nullish(),Resources:O.nullish()}).passthrough(),Tl=z.object({Content:fn.nullish()}).passthrough(),Wf=z.object({ContentID:z.string().nullish(),OptionID:z.string().nullish(),Source:Lf.nullish(),AlreadyOwned:z.boolean().nullish(),AccessActive:z.boolean().nullish(),Settlement:Ut.nullish(),Resources:O.nullish(),CommissionTaken:ce.nullish()}).passthrough(),PT=z.object({Role:z.string().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish()}).passthrough(),Kf=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),Revision:z.number().nullish(),AccessVia:hT.nullish(),Files:z.array(PT).nullish(),ThumbnailUrl:z.string().nullish(),ExpiresAt:u.nullish()}).passthrough(),vT=z.object({ContentID:z.string().nullish(),Source:Lf.nullish(),OptionID:z.string().nullish(),PricePaid:ce.nullish(),AcquiredAt:u.nullish(),Content:fn.nullish()}).passthrough(),Qf=z.object({Licenses:z.array(vT).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Xe={GetDefinitions:"GetDefinitions",Browse:"Browse",GetContent:"GetContent",GetCollection:"GetCollection",GetCreatorProfile:"GetCreatorProfile",BeginUpload:"BeginUpload",Publish:"Publish",UpdateContent:"UpdateContent",Unpublish:"Unpublish",GetMyContent:"GetMyContent",Acquire:"Acquire",GetDownload:"GetDownload",GetMyLicenses:"GetMyLicenses",GetMyFavorites:"GetMyFavorites"};var Io=class extends _{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(Xe.GetDefinitions,e,Gf)}browse(e){return this.send(Xe.Browse,e,Do)}getContent(e){return this.send(Xe.GetContent,e,Nf)}getCollection(e){return this.send(Xe.GetCollection,e,_f)}getCreatorProfile(e){return this.send(Xe.GetCreatorProfile,e,Vf)}beginUpload(e){return this.send(Xe.BeginUpload,e,jf)}publish(e){return this.send(Xe.Publish,e,Ae(Ff))}updateContent(e){return this.send(Xe.UpdateContent,e,Tl)}unpublish(e){return this.send(Xe.Unpublish,e,Tl)}getMyContent(e){return this.send(Xe.GetMyContent,e,Do)}acquire(e){return this.send(Xe.Acquire,e,Wf)}getDownload(e){return this.send(Xe.GetDownload,e,Kf)}getMyLicenses(e){return this.send(Xe.GetMyLicenses,e,Qf)}getMyFavorites(e){return this.send(Xe.GetMyFavorites,e,Do)}};var Po=class extends _{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,n,i){return this.send(e,t,n,{throttleKey:`${this.endpoint(e,t)}|${i}`})}sendPublic(e,t,n,i){let r=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(r,t,n,{throttleKey:`${r}|${i}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,kd,"defs")}get(e){return this.sendKeyed("Get",e,Ha,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Od,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,$a,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Ed,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,Ja,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,Ja,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,qd,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,Ld,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Ud,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,Bd,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,Md,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Gd,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,Ha,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,$a,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var vo=class{settings;emitter;host;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;credits;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;challenge;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;clan;avatar;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.host=e.host??N(),this.settings=El(e,this.host),this.emitter=new Ln,this.clientPlatform=e.clientPlatform??this.host.getClientPlatform(),this.acquisition=new sn(this.host),this.acquisition.capture(),this.playtime=new Bn(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{}),this.host.supports.storePurchases&&this.purchase.restorePending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new Ri({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e.fetch,debugLogging:this.settings.debugLogging,throttleMs:e.throttleMs,maxRequestsPerSecond:e.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new bi(this.emitter),this.cache=new Ii(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:n})=>{this.userService.noteStateVersions(t,n);}),this.authStore=new Pi(this.host.storage,this.settings.titleID),this.api={authentication:new br(this),user:new Dr(this),currency:new Ir(this),item:new Ar(this),store:new Tr(this),purchase:new Mr(this),lootbox:new qr(this),reward:new Ur(this),quest:new Vr(this),tutorial:new Lr(this),communityMarketing:new Br(this),chat:new Gr(this),push:new Nr(this),localization:new _r(this),timedEvent:new jr(this),leaderboard:new Fr(this),season:new Wr(this),premium:new Kr(this),character:new Qr(this),match:new Hr(this),challenge:new $r(this),craft:new Zr(this),ai:new Yr(this),collection:new eo(this),coopEvent:new to(this),dealOffer:new no(this),referral:new io(this),mailbox:new so(this),clan:new ro(this),avatar:new oo(this),advertising:new ao(this),social:new lo(this),timedBoost:new po(this),userCustomData:new ho(this),titleCustomData:new fo(this),title:new yo(this),gameLoop:new Ro(this),cloudCode:new Co(this),blockchain:new So(this),marketplace:new xo(this),multiplayer:new bo(this),workshop:new Io(this),dataCollections:new Po(this),analytics:new Cr(this),experiment:new Sr(this)},this.userService=new ki(this),this.cache.attachState(this.userService),this.auth=new Ai(this),this.currency=new Oi(this),this.item=new Ei(this),this.store=new Gi(this),this.credits=new Ni(this),this.purchase=new _i(this),this.checkout=new Vi(this),this.lootbox=new ji(this),this.reward=new Wi(this),this.quest=new ts(this),this.tutorial=new Qi(this),this.communityMarketing=new Hi(this),this.chat=new Zi(this),this.push=new Yi(this),this.localization=new es(this),this.timedEvent=new ss(this),this.leaderboard=new ps(this),this.season=new ms(this),this.premium=new fs(this),this.character=new Rs(this),this.match=new Cs(this),this.challenge=new Ss(this),this.craft=new xs(this),this.ai=new Ds(this),this.collection=new Is(this),this.coopEvent=new As(this),this.dealOffer=new ws(this),this.referral=new ks(this),this.mailbox=new qs(this),this.clan=new Gs(this),this.avatar=new Vs(this),this.ads=new Fs(this),this.social=new $s(this),this.timedBoost=new Js(this),this.userCustomData=new Zs(this),this.titleCustomData=new Ys(this),this.title=new Xs(this),this.gameLoop=new ir(this),this.cloudCode=new sr(this),this.blockchain=new or(this),this.marketplace=new pr(this),this.multiplayer=new hr(this),this.workshop=new dr(this),this.dataCollections=new fr(this),this.analytics=new yr(this),this.experiments=new Rr(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.host.getFullURL(),RelatedEntityID:a()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var Ao=class{ctx;constructor(e){this.ctx=new vo(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,n={}){let i=this.ctx.buildAuthedBaseRequest(),s=en(this.ctx.settings.titleID,e,t,i.UserID??"");return this.ctx.transport.post(s,{...i,...n},z.unknown(),{ticket:i.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get challenge(){return this.ctx.challenge}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get clan(){return this.ctx.clan}get avatar(){return this.ctx.avatar}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get host(){return this.ctx.host}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function TT(o){return new Ao(o)}var Hf="idos_sso",$f="state",zl="idos:sso:state",zT="https://idosgames.com/sso/",wT=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],kT=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function MT(){if(typeof window>"u")return false;let{origin:o}=window.location;return wT.includes(o)||kT.test(o)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function OT(){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(Hf);if(!t)return null;let n=e.get($f)??"",i=BT();return NT(e),GT(),i&&n!==i?null:{code:t,state:n}}function ET(o){if(typeof window>"u")return;let e=o.returnTo??qT(),t=UT();LT(t);let n=new URL(o.ssoUrl??zT);n.searchParams.set("title",o.titleID),n.searchParams.set("return_to",e),n.searchParams.set("state",t),window.location.assign(n.toString());}function qT(){let{origin:o,pathname:e,search:t}=window.location;return `${o}${e}${t}`}function UT(){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 LT(o){try{window.sessionStorage.setItem(zl,o);}catch{}}function BT(){try{return window.sessionStorage.getItem(zl)}catch{return null}}function GT(){try{window.sessionStorage.removeItem(zl);}catch{}}function NT(o){o.delete(Hf),o.delete($f);let e=o.toString(),{pathname:t,search:n}=window.location;window.history.replaceState(null,"",`${t}${n}${e?`#${e}`:""}`);}var _T={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 VT(o,e="Something went wrong. Please try again."){return o?_T[o]??o:e}function jT(o,e){return !!o?.Claims?.[e]?.ClaimedAt}function FT(o){let e=o?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function WT(o,e){return o?.Claims?.[e]?.PremiumTiers??[]}function Zf(o,e,t,n=1){if(!o)return e;let i=o.Base??e,s=Math.max(0,t-n),r;switch(o.Shape??"Flat"){case "PerStep":r=i+(o.PerStep??0)*s;break;case "PerStepRate":r=i*(1+(o.PerStepRate??0)*s);break;case "Geometric":r=i*Math.pow(1+(o.GrowthRate??0),s);break;case "Table":r=i*Jf(o,t,1);break;case "TableAbsolute":r=Jf(o,t,i);break;default:r=i;break}return Number.isNaN(r)?i:(o.MinResult!=null&&r<o.MinResult&&(r=o.MinResult),o.MaxResult!=null&&r>o.MaxResult&&(r=o.MaxResult),r)}function KT(o,e,t=1){return Zf(o,1,e,t)}function QT(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 Yf(o.Points).length>0;default:return o.MinResult!=null||o.MaxResult!=null}}function HT(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 Yf(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 Jf(o,e,t){let n=Yf(o.Points);if(n.length===0)return t;let i=null,s=null,r=null;for(let p of n)(r===null||p.AtStep>r.AtStep)&&(r=p),p.AtStep<=e&&(i===null||p.AtStep>=i.AtStep)&&(i=p),p.AtStep>e&&(s===null||p.AtStep<s.AtStep)&&(s=p);if(i===null)return t;if(s===null){let p=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-i.AtStep)/(s.AtStep-i.AtStep);return i.Value+p*(s.Value-i.Value)}case "Geometric":{if(i.Value<=0||s.Value<=0){let m=(e-i.AtStep)/(s.AtStep-i.AtStep);return i.Value+m*(s.Value-i.Value)}let p=(e-i.AtStep)/(s.AtStep-i.AtStep);return i.Value*Math.pow(s.Value/i.Value,p)}default:return i.Value}}function Xf(o,e){return e?.BonusMode??o?.SetSettings?.BonusMode??"Cumulative"}function eg(o,e,t){if(!o?.Bonuses||e<=0)return [];let n=o.Bonuses.filter(i=>!!i&&(i.Pieces??0)>0&&(i.Pieces??0)<=e).sort((i,s)=>(i.Pieces??0)-(s.Pieces??0));if(n.length===0)return [];if(t==="HighestOnly"){let i=n[n.length-1]?.Pieces??0;return n.filter(s=>(s.Pieces??0)===i)}return n}function $T(o,e){let t=e?.Sets,n=e?.Catalogs;if(!t||!o||!n||Object.keys(t).length===0)return [];let i=new Map;for(let[p,m]of Object.entries(o)){if(!p||p.startsWith("@")||!m?.ItemID)continue;let W=ZT(n,m.ItemID,m.CatalogID??null)?.Metadata?.CollectionID;!W||!(W in t)||i.set(W,(i.get(W)??0)+1);}let s=[...i.keys()].sort((p,m)=>p<m?-1:p>m?1:0),r=[];for(let p of s){let m=t[p];if(!m)continue;let R=i.get(p)??0,W=Xf(e,m);r.push({SetID:p,Definition:m,Pieces:R,Mode:W,ActiveTiers:eg(m,R,W)});}return r}function JT(o,e){if(!o||!e)return 0;let t=0;for(let n of Object.values(o))for(let i of Object.values(n?.Items??{}))i?.Metadata?.CollectionID===e&&t++;return t}function ZT(o,e,t){if(t){let i=o[t]?.Items?.[e];if(i)return i}let n=null;for(let i of Object.values(o)){let s=i?.Items?.[e];if(s){if(n)return null;n=s;}}return n}var YT={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},wl=z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),XT={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},ez=z.enum(["Top","Bottom","Left","Right"]).catch("Top"),tz=z.object({PlacementID:z.string().nullish(),Type:wl.nullish(),Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),CreditsRewarded:z.number().nullish(),AllowedProviderIDs:z.array(z.string()).nullish()}).passthrough(),nz=z.object({DefaultCreditsPerView:z.number().nullish(),MaxCreditsBalance:z.number().nullish(),DailyCreditEarnCap:z.number().nullish(),DailyViewCap:z.number().nullish(),MinSecondsBetweenViews:z.number().nullish()}).passthrough(),iz=z.object({CooldownSeconds:z.number().nullish(),MinSessionTimeBeforeFirstSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),sz=z.object({Enabled:z.boolean().nullish(),Position:ez.nullish(),RefreshIntervalSeconds:z.number().nullish()}).passthrough(),rz=z.object({Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish()}).passthrough(),oz=z.object({MaxImpressionsPerHour:z.number().nullish(),MaxImpressionsPerDay:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),az=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),DisableInterstitials:z.boolean().nullish(),DisableBanners:z.boolean().nullish(),DisableAppOpen:z.boolean().nullish()}).passthrough(),lz=z.object({RequirePersonalizedAdsConsent:z.boolean().nullish(),RequireTrackingConsent:z.boolean().nullish(),CurrentPolicyVersion:z.string().nullish(),RegulatedRegions:z.array(z.string()).nullish()}).passthrough(),uz=z.object({RequireServerSideVerification:z.boolean().nullish(),PendingRequestTtlSeconds:z.number().nullish(),MaxPendingRequestsPerUser:z.number().nullish()}).passthrough(),cz=z.object({AndroidUnitID:z.string().nullish(),IosUnitID:z.string().nullish(),WebUnitID:z.string().nullish(),Type:wl.nullish()}).passthrough(),pz={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},hz=z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),dz=z.object({ProviderID:z.string().nullish(),Kind:hz.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(),cz).nullish()}).passthrough();z.object({Enabled:z.boolean().nullish(),Placements:z.record(z.string(),tz).nullish(),Providers:z.record(z.string(),dz).nullish(),RewardedVideo:nz.nullish(),Interstitial:iz.nullish(),Banner:sz.nullish(),AppOpen:rz.nullish(),FrequencyCapping:oz.nullish(),PremiumAdReductions:z.array(az).nullish(),Consent:lz.nullish(),Verification:uz.nullish()}).passthrough();var mz=z.object({RewardedVideoCredit:z.number().nullish(),TotalEarned:z.number().nullish(),TotalSpent:z.number().nullish()}).passthrough(),fz=z.object({PlacementID:z.string().nullish(),LastShownAt:u.nullish(),LastCompletedAt:u.nullish(),TotalImpressions:z.number().nullish(),TotalCompletions:z.number().nullish(),ConsecutiveFailures:z.number().nullish()}).passthrough(),gz=z.object({Date:u.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(),yz=z.object({SessionID:z.string().nullish(),SessionStartAt:u.nullish(),Impressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish()}).passthrough(),Rz=z.object({PersonalizedAdsConsent:z.boolean().nullish(),TrackingConsent:z.boolean().nullish(),PolicyVersion:z.string().nullish(),Region:z.string().nullish(),ConsentGivenAt:u.nullish(),ConsentRevokedAt:u.nullish()}).passthrough(),Cz=z.object({RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),Type:wl.nullish(),IssuedAt:u.nullish(),ExpiresAt:u.nullish(),CreditsToAward:z.number().nullish()}).passthrough(),Sz=z.object({InvalidSsvCount:z.number().nullish(),OrphanCompletions:z.number().nullish(),FastCompletions:z.number().nullish(),LastFlaggedAt:u.nullish()}).passthrough();z.object({Credits:mz.nullish(),Placements:z.record(z.string(),fz).nullish(),Daily:gz.nullish(),Session:yz.nullish(),LastImpressionAt:u.nullish(),LastInterstitialAt:u.nullish(),LastRewardedAt:u.nullish(),LastAppOpenAt:u.nullish(),TotalImpressions:z.number().nullish(),TotalRewardedCompletions:z.number().nullish(),AdsDisabledUntil:u.nullish(),Consent:Rz.nullish(),PendingRequests:z.record(z.string(),Cz).nullish(),FraudFlags:Sz.nullish(),UpdatedAt:u.nullish()}).passthrough();
2
- export{je as AIAction,bC as AIErrorCode,on as AIGenerationStatus,$t as AIModality,Ns as AVATAR_MAX_USERS,Wx as AVATAR_SHOP_PAGE_SIZE,sn as AcquisitionCapture,pz as AdProviderKind,YT as AdType,js as AdvertisingAction,el as AnalyticsAction,QI as AnalyticsDropReason,Xa as AnalyticsEventNaming,Mt as AnalyticsLimits,zb as AttackOutcome,We as AuthenticationAction,Xt as AutomaticEvent,An as AvatarAction,Fx as AvatarErrors,XT as BannerPosition,nt as BlockchainAction,SD as BlockchainNetworkType,id as BlockchainOperationCategory,zD as BlockchainTransactionStatus,ID as BlockchainTransactionType,$S as BodyPart,zA as BoostWindowKind,Ls as CLAN_DEFAULT_KIND_ID,Mn as ChallengeAction,Gv as ChallengeMode,He as CharacterAction,et as ChatAction,cR as ChatAuthorType,lR as ChatBlockedTermAction,iR as ChatChannelType,oR as ChatDirectAudience,sR as ChatPartitioning,hR as ChatReportReason,Ue as ClanAction,yx as ClanCompetitionType,gx as ClanErrors,mx as ClanInviteType,hx as ClanJoinMode,fx as ClanPermission,Rx as ClanRelation,vl as CloudCodeAction,JA as CloudCodeErrorCode,HA as CloudCodeLogLevel,QA as CloudCodeRevisionSelection,Ye as CollectionAction,rI as CommissionSink,pD as CommunityChestMemberStatus,cD as CommunityChestStatus,Av as CommunityCreatorStatus,pn as CommunityMarketingAction,zv as CommunityMetricKind,Pv as CommunityParticipationMode,Tv as CommunityPayoutCurrencyKind,SS as ConversionRateMode,It as CoopEventAction,LC as CoopGroupStatus,BC as CoopMemberStatus,Jr as CraftAction,Yv as CraftInputSelectionMode,Jv as CraftOutputLevelMode,eA as CraftOutputLevelOverflow,$v as CraftType,Nn as CreditsConfirmationStatus,qy as CreditsError,Fn as CurrencyAction,CS as CurrencyStatus,Dg as CurveInterpolation,xg as CurveShape,Nt as CustomDataBucket,nb as CustomDataValueType,Xx as CustomDataWriter,Ol as DEFAULT_BASE_URL,PI as DataAccessMode,xI as DataCollectionKind,OI as DataCollectionSchemaMode,VI as DataCollectionsAction,zI as DataCounterKind,DI as DataFieldType,II as DataFieldVisibility,kI as DataOwnerDeletedPolicy,AI as DataRefKind,nS as DealComparisonOperator,HC as DealNodeRuntimeStatus,tS as DealNodeType,wt as DealOfferAction,QC as DealOfferActivationStatus,gr as EVENT_NAME_PATTERN,_A as EnvelopeType,il as ExperimentAction,sP as ExperimentGoalKind,Cb as FRIENDS_FROM_PLATFORM,yP as FodderSelectionMode,fP as FodderValuationMode,rb as FriendActionStatus,ob as FriendSource,Fe as GameLoopAction,Ao as IDosGamesClient,qP as IapProductType,$P as IapPurchaseStatus,Pr as ItemAction,TP as ItemSetBonusMode,PD as KycStatus,AD as KycTier,Je as LeaderboardAction,xr as LocalizationAction,uP as LocalizationMissingKeyMode,Er as LootboxAction,NS as MAILBOX_COUNTER_CAP,ut as MailboxAction,ES as MailboxCategory,GS as MailboxErrors,qS as MailboxLetterSource,LS as MailboxRewardModule,lr as MarketGoodsType,sI as MarketOfferStatus,iI as MarketOfferType,Le as MarketplaceAction,kt as MatchAction,JS as MatchStatus,it as MultiplayerAction,BA as MultiplayerChatMode,LA as MultiplayerTopology,tR as OFFER_NOT_IN_ROTATION,va as PLATFORM_AD_PROVIDER,MS as PeerPayoutSource,OS as PeerPayoutStatus,xb as PlatformFriendsMode,Sb as PlatformProfileMode,BD as PlayAccessMode,aP as PlayerExperimentStatus,Bn as PlaytimeTracker,un as PremiumAction,cn as PurchaseAction,vn as PushAction,tt as PushPermissionState,vR as PushTopic,IR as PushTransport,bt as QuestAction,Eg as QuestObjectiveSource,Ug as QuestPrerequisiteMode,kg as QuestStatus,Ab as RaidMode,tn as ReferralAction,Ot as RewardAction,pv as RewardWindowBoost,GA as RoomVisibility,SC as SKIN_ALREADY_OWNED,ra as SKIN_SLOT,Qt as SeasonAction,be as SocialAction,hb as SocialContentStatus,ub as SocialEntityType,db as SocialInboxVerb,cb as SocialReactionKind,pb as SocialReportReason,Tb as SpecialChoiceMode,Bt as StoreAction,By as StoreRotationMode,OP as StoreType,dn as TimedBoostAction,CA as TimedBoostStackingPolicy,ft as TimedEventAction,mn as TitleAction,ni as TitleCustomDataAction,MA as TitleDataBucket,kA as TitleDataScope,oA as TradeOfferStatus,wD as TransactionDirection,dt as TutorialAction,Zg as TutorialBoardAction,Hg as TutorialFlowStatus,fg as TutorialGateMode,Kg as TutorialRestartPolicy,Jg as TutorialScriptModule,Fg as TutorialStepCompletionMode,Ln as TypedEmitter,Rt as UserAction,Pt as UserCustomDataAction,qD as WalletGateBalanceSource,bD as WalletLinkType,eT as WorkshopAccessMode,pT as WorkshopAccessVia,Xe as WorkshopAction,aT as WorkshopContentStatus,iT as WorkshopHoldingMatch,tT as WorkshopHoldingMode,uT as WorkshopLicenseSource,cT as WorkshopSort,rT as WorkshopVisibility,eg as activeSetTiers,VT as authErrorText,ET as beginSsoRedirect,FT as claimedMilestoneIDs,JT as countSetMembers,TT as createIDosGamesClient,xn as cryptoShortfallFromError,KT as curveMultiplier,Sy as defineView,Qd as describeUserAgent,Xf as effectiveSetMode,Zf as evaluateCurve,WT as grantedPremiumTiers,jn as isAIGenerationTerminal,QT as isCurveConfigured,jT as isMilestoneClaimed,uC as isReservedSlot,MT as isSsoAvailable,rr as normalizeBlockchainCategory,DC as parseAIErrorCode,OT as readSsoCodeFromUrl,$T as resolveItemSets,HT as roundAmount,FI as where,Ey as zPaymentProof,qi as zPriceOption,he as zPriceOptions};
1
+ import {i,o,k,m,q,g,N,a,j,r,f,h,z as z$1}from'./chunk-TFBN7PEL.js';export{r as AuthType,c as BrowserFileStore,d as BrowserStorage,j as ClientPlatform,f as CurrencyType,n as EventTokenType,l as IapStoreValues,b as MemoryFileStore,s as MemoryHost,e as MemoryStorage,v as NATIVE_HOST_GLOBAL,u as NATIVE_HOST_PROTOCOL,x as NativeHost,G as PLATFORM_AD_MESSAGES,B as PLATFORM_BRIDGE_ACK,I as PLATFORM_CREDITS_CONFIRM_FINAL,H as PLATFORM_CREDITS_CONFIRM_MESSAGES,z as PLATFORM_ORIGINS,C as PLATFORM_PAGE_UNAVAILABLE,E as PLATFORM_SIGN_IN_MESSAGES,F as PLATFORM_TOPUP_MESSAGES,J as PLATFORM_TRADE_MESSAGES,h as ResourceEntryType,L as SITE_FRAME_HIDDEN_MESSAGE,p as ScheduleMode,M as WebHost,D as askPlatformPage,N as createDefaultHost,y as getTelegramWebApp,A as isPlatformParentOrigin,K as platformTradeUrl,w as readNativeHostGlobal,t as shareFallbackText}from'./chunk-TFBN7PEL.js';import {b,a as a$1,c}from'./chunk-CS7ACWDY.js';export{e as isFail,d as isOk}from'./chunk-CS7ACWDY.js';import {z}from'zod';import an from'decimal.js';var Gn=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.off(e,t);}}once(e,t){let n=this.on(e,i=>{n(),t(i);});return n}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e));}emit(e,t){let n=this.listeners.get(e);if(n)for(let i of [...n])i(t);}removeAllListeners(){this.listeners.clear();}};function Bl(o){return {get:e=>o.getString(e),set:(e,t)=>o.setString(e,t),remove:e=>o.remove(e)}}var Gl="https://api.idosgames.com";function Nl(o,e){return {titleID:o.titleID,titleTemplateID:o.titleTemplateID??"default",buildKey:o.buildKey??"",baseUrl:(o.baseUrl??Gl).replace(/\/+$/,""),devBuild:o.devBuild??false,debugLogging:o.debugLogging??false,configStorage:o.configStorage??Bl(e.storage),locale:o.locale??e.getLanguage(),appVersion:o.appVersion??""}}var Eo="idos_acq",_l=["gclid","fbclid","ttclid","msclkid","yclid"],fg=["ref","r"],gg=["ref_","ref-","ref=","r_","r-"];var on=class{constructor(e){this.host=e;}host;capture(){let e=this.readFromEnvironment();yg(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),n=t?{...t.signal}:{},i=Sg(this.host.getDeviceModel());return i&&(n.OsVersion=i),e&&(n.AppVersion=e),Object.keys(n).length>0?n:void 0}clear(){this.host.storage.remove(Eo);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let n=Fl(jl(t));if(n)return n}return ci(t)}readFromEnvironment(){let e={},t=jl(this.host.getFullURL());rn(e,"UtmSource",t.get("utm_source")),rn(e,"UtmMedium",t.get("utm_medium")),rn(e,"UtmCampaign",t.get("utm_campaign")),rn(e,"UtmTerm",t.get("utm_term")),rn(e,"UtmContent",t.get("utm_content")),rn(e,"ClaimToken",t.get("idos_click"));for(let R of _l){let W=t.get(R);if(W){e.ClickID=W;break}}let n=this.host.getStartParameter()??"",i=Cg(n);if(i){for(let R of Rg)rn(e,R,i.get(Wl[R])??null);for(let R of _l){let W=i.get(R);if(W){e.ClickID=W;break}}}let s=ci(i?i.get("ref")??i.get("r")??"":n),r=Fl(t),p=s||r;p&&(e.ReferralCode=p,e.ChannelHint=s?"telegram":"query");let m=this.host.getReferrer();return m&&(e.Referrer=m),e}read(){try{let e=this.host.storage.getString(Eo);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.host.storage.setString(Eo,JSON.stringify(e));}catch{}}};function yg(o){return !!(o.UtmSource||o.UtmMedium||o.UtmCampaign||o.ClickID||o.Referrer||o.ReferralCode||o.ClaimToken)}function rn(o,e,t){t&&(o[e]=t);}var Vl="a1_",Wl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},Rg=Object.keys(Wl);function Cg(o){let e=(o||"").trim();if(!e.startsWith(Vl))return null;let t=e.slice(Vl.length);if(!t)return null;try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),i=atob(n+"=".repeat((4-n.length%4)%4)),s=Uint8Array.from(i,m=>m.charCodeAt(0)),r=new TextDecoder().decode(s),p=new URLSearchParams(r);return [...p.keys()].length>0?p:null}catch{return null}}function jl(o){try{let e=o.indexOf("?");return new URLSearchParams(e>=0?o.slice(e):"")}catch{return new URLSearchParams}}function Fl(o){for(let e of fg){let t=o.get(e);if(t)return ci(t)}return null}function ci(o){let e=(o||"").trim();if(!e)return null;for(let t of gg)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Sg(o){let e=o||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let n=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(n)return n[1]}var Kl="idos_usage_pending",Ql="idos_usage_session",Hl="idos_usage_closed_session",$l="idos_usage_new_session",Jl="idos_usage_last_activity",Nn=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;stopVisibility=null;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=!this.ctx.host.isVisible(),this.timer=setInterval(()=>this.tick(),200*1e3),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=e=>{if(!e){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,n=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,n,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=n,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=n,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(Kl),this.currentSessionSeconds=this.readNumber(Ql),this.pendingClosedSessionSeconds=this.readNumber(Hl),this.isNewSessionPending=this.readNumber($l)!==0;let e=this.readNumber(Jl);this.currentSessionSeconds>0&&e>0&&(Date.now()-e)/1e3>=1800&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,Math.floor(this.currentSessionSeconds)),this.currentSessionSeconds=0);}persist(){this.writeNumber(Kl,this.pendingSeconds),this.writeNumber(Ql,this.currentSessionSeconds),this.writeNumber(Hl,this.pendingClosedSessionSeconds),this.writeNumber($l,this.isNewSessionPending?1:0),this.writeNumber(Jl,Date.now());}readNumber(e){let t=this.ctx.host.storage.getString(e),n=t?Number(t):0;return Number.isFinite(n)&&n>0?n:0}writeNumber(e,t){try{this.ctx.host.storage.setString(e,String(Math.floor(t)));}catch{}}};var H=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)}),ie=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}),u=z.string();var At=z.object({Type:i.nullish(),CurrencyID:z.string().nullish(),Amount:H.nullish(),AmountUsd:z.number().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ProductID:z.string().nullish()}),xg=z.object({Type:o.nullish(),EntityID:z.string()}),bg=z.object({Address:xg.nullish(),Amount:H.nullish(),Source:z.string().nullish()}),pe=z.object({Entries:z.array(At).nullish(),EventTokens:z.array(bg).nullish()}),Zl=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Resources:pe.nullish()}),$=z.object({Standard:pe.nullish(),PremiumBonuses:z.array(z.unknown()).nullish(),PremiumTiers:z.array(Zl).nullish()}),Ut=z.object({Standard:pe.nullish(),PremiumDiscounts:z.array(z.unknown()).nullish(),PremiumTiers:z.array(Zl).nullish()}),O=z.object({Grant:$.nullish(),Consume:Ut.nullish()}),Lt=z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),FromResult:O.nullish(),ToResult:O.nullish()});z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Transferred:pe.nullish()});var Dg=z.object({ExperimentID:z.string().nullish(),Variants:z.array(z.string()).nullish()}).passthrough(),Ig={Completed:"Completed",Started:"Started",StepReached:"StepReached"},Pg=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(),te=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:Dg.nullish(),Tutorial:Pg.nullish(),Platforms:z.array(k).nullish()}).passthrough();var Pe=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 vg=z.object({OffsetSecondsFromParentStart:z.number().nullish(),DurationSeconds:z.number().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Ag=z.object({StartUtc:z.string().nullish(),EndUtc:z.string().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Tg=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 wg=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 dt=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:Pe.nullish()}).passthrough(),Ce=z.object({Mode:z.string().nullish(),IsActive:z.boolean().nullish(),Scheduled:Ag.nullish(),Chain:Tg.nullish(),Cyclic:wg.nullish(),ActivationTriggers:z.array(dt).nullish(),Relative:vg.nullish()}).passthrough();var zg={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},kg=z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Mg={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Og=z.enum(["Step","Linear","Geometric"]).catch("Step"),Eg=z.object({AtStep:z.number().nullish(),Value:z.number().nullish()}).passthrough(),Je=z.object({Base:z.number().nullish(),Shape:kg.nullish(),PerStep:z.number().nullish(),PerStepRate:z.number().nullish(),GrowthRate:z.number().nullish(),Points:z.array(Eg).nullish(),Interpolation:Og.nullish(),TailGrowthRate:z.number().nullish(),MinResult:z.number().nullish(),MaxResult:z.number().nullish()}).passthrough();var qg=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Rewards:$.nullish()}).passthrough(),Ug=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Multiplier:z.number().nullish()}).passthrough(),qo=z.object({Bundles:z.array(qg).nullish(),Multipliers:z.array(Ug).nullish()}).passthrough();var Lg=z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),pi=z.object({Source:Lg.nullish(),SourceKey:z.string().nullish(),Curve:Je.nullish(),Anchor:z.number().nullish(),IncludeRewards:pe.nullish(),ExcludeRewards:pe.nullish()}).passthrough(),Yl=z.object({ClaimedAt:z.string().nullish(),PremiumTiers:z.array(z.string()).nullish(),Unlocked:z.boolean().nullish()}).passthrough(),je=z.object({MilestoneID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredProgress:z.number().nullish(),Rewards:$.nullish(),BonusRewards:$.nullish(),SeasonTierRewards:qo.nullish(),SortOrder:z.number().nullish(),IsFeatured:z.boolean().nullish()}).passthrough(),Sn=z.object({Milestones:z.record(z.string(),je).nullish()}).passthrough();var J=z.object({PresetID:z.string().nullish(),Remove:z.array(z.string()).nullish()}).passthrough();var Bg=z.object({TargetCurrencyID:z.string().nullish(),Rate:z.number().nullish(),MaxConvertAmount:z.number().nullish()}).passthrough(),Tt=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:Bg.nullish()}).passthrough();var Gg=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),xn=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:u,ExpiresAt:u.nullish(),EquippedSlot:Gg.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Q=z.object({ChangedInstances:z.record(z.string(),xn).nullish(),RemovedInstanceIDs:z.array(z.string()).nullish()});var Me=o=>z.object({Id:z.string(),Success:z.boolean(),Error:z.string().nullish(),Data:o.nullish()}),wt=o=>z.object({ServerTimeUtc:u,Items:z.array(Me(o)),Resources:O.nullish(),Inventory:Q.nullish()});var Ng={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Xl=z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),_g=z.object({}).passthrough().transform(o=>o),Vg=z.object({CycleID:z.string(),InstanceKey:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),CycleStartUtc:u.nullish(),CycleEndUtc:u.nullish(),PointsTotalEarned:H.nullish(),PointsCurrent:H.nullish(),ClaimedPointMilestoneIDs:z.array(z.string()).nullish(),NextMilestone:je.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),Uo=z.object({QuestID:z.string(),CycleID:z.string().nullish(),ObjectiveID:z.string().nullish(),NewValue:H.nullish(),ObjectiveCompleted:z.boolean().nullish(),Status:Xl}),eu=z.object({State:_g.nullish(),PointsTracks:z.record(z.string(),Vg).nullish()}),Lo=z.object({ServerTimeUtc:u,QuestID:z.string(),CycleID:z.string().nullish(),NewStatus:Xl.nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),Bo=z.object({ServerTimeUtc:u,CycleID:z.string(),MilestoneID:z.string(),PointsTotalEarned:H.nullish(),Resources:O.nullish(),Inventory:Q.nullish(),NextMilestone:je.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),tu=z.object({ServerTimeUtc:u,CycleID:z.string(),GroupCompletionID:z.string(),GroupID:z.string().nullish(),CompletedGroupQuests:z.number().nullish(),RequiredGroupQuests:z.number().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),nu=z.object({MetricID:z.string(),Updates:z.array(Uo).nullish()}),iu=z.array(Me(Lo)),su=z.array(Me(Bo)),jg={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Fg=z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Wg={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Kg=z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),ru=z.object({ObjectiveID:z.string().nullish(),Source:Fg.nullish(),MaxProgressPerCall:z.number().nullish(),MetricID:z.string().nullish(),Triggers:z.array(dt).nullish(),TargetValue:z.number().nullish(),AggregationMethod:z.string().nullish()}).passthrough(),Go=z.object({Milestones:J.nullish(),Linking:J.nullish(),Availability:J.nullish(),Reward:J.nullish(),Objectives:J.nullish()}).passthrough(),Qg=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(),ou=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:Kg.nullish()}).passthrough(),au=z.object({Schedule:Ce.nullish(),AccrueProgressWhenLocked:z.boolean().nullish(),Gate:te.nullish(),Limits:Pe.nullish()}).passthrough(),lu=z.object({Grant:$.nullish(),PointsReward:z.number().nullish()}).passthrough(),Hg=z.object({QuestID:z.string().nullish(),Identity:Qg.nullish(),Linking:ou.nullish(),Availability:au.nullish(),Objectives:z.record(z.string(),ru).nullish(),Reward:lu.nullish(),Presets:Go.nullish()}).passthrough(),$g=z.object({CompletionID:z.string().nullish(),GroupID:z.string().nullish(),RequiredCompletedQuests:z.number().nullish(),Gate:te.nullish(),Reward:$.nullish(),PointsReward:z.number().nullish()}).passthrough(),Jg=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:te.nullish(),Milestones:z.record(z.string(),je).nullish(),Presets:Go.nullish(),PointsToken:Tt.nullish()}).passthrough(),Zg=z.object({Milestones:z.record(z.string(),Sn).nullish(),Linking:z.record(z.string(),ou).nullish(),Availability:z.record(z.string(),au).nullish(),Reward:z.record(z.string(),lu).nullish(),Objectives:z.record(z.string(),z.record(z.string(),ru)).nullish()}).passthrough(),Yg=z.object({CycleID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:Ce.nullish(),Milestones:z.record(z.string(),je).nullish(),Gate:te.nullish(),PointsToken:Tt.nullish(),GroupCompletions:z.record(z.string(),$g).nullish(),Phases:z.record(z.string(),Jg).nullish(),Presets:Go.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),di=z.object({Cycles:z.record(z.string(),Yg).nullish(),Quests:z.record(z.string(),Hg).nullish(),Presets:Zg.nullish()}).passthrough(),Dt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var Xg={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},ey=z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),ty={Never:"Never",OnRequest:"OnRequest",Always:"Always"},ny=z.enum(["Never","OnRequest","Always"]).catch("Never"),iy={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},sy=z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),ry={GameLoop:"GameLoop"},oy={Raid:"Raid",Attack:"Attack"},ay=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(),ly=z.object({Mode:ey.nullish(),Triggers:z.array(dt).nullish(),TargetValue:z.number().nullish(),RequireAllTriggers:z.boolean().nullish()}).passthrough(),uy=z.object({Grant:$.nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),cy=z.object({TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),RandomActionType:z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),py=z.object({Module:z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:cy.nullish(),MaxUses:z.number().nullish()}).passthrough(),hy=z.object({Skippable:z.boolean().nullish(),TimeoutSeconds:z.number().nullish()}).passthrough(),No=z.object({StepID:z.string().nullish(),Order:z.number().nullish(),Identity:ay.nullish(),Completion:ly.nullish(),Effects:uy.nullish(),Script:py.nullish(),Policy:hy.nullish()}).passthrough(),dy=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(),uu=z.object({Schedule:Ce.nullish(),Gate:te.nullish(),RequiredFlowIDs:z.array(z.string()).nullish(),AutoStart:z.boolean().nullish(),StartTrigger:dt.nullish()}).passthrough(),cu=z.object({Skippable:z.boolean().nullish(),SkippableFromOrder:z.number().nullish(),RestartPolicy:ny.nullish(),ExpireAfterSeconds:z.number().nullish(),IsBlocking:z.boolean().nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),pu=z.object({Grant:$.nullish(),AutoClaim:z.boolean().nullish()}).passthrough(),my=z.object({Availability:J.nullish(),Policy:J.nullish(),Reward:J.nullish(),Steps:J.nullish()}).passthrough(),fy=z.object({FlowID:z.string().nullish(),Identity:dy.nullish(),Availability:uu.nullish(),Policy:cu.nullish(),Steps:z.record(z.string(),No).nullish(),Reward:pu.nullish(),Presets:my.nullish()}).passthrough(),gy=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(),yy=z.object({IsEnabled:z.boolean().nullish(),MaxActiveFlows:z.number().nullish(),Blocking:gy.nullish()}).passthrough(),Ry=z.object({Availability:z.record(z.string(),uu).nullish(),Policy:z.record(z.string(),cu).nullish(),Reward:z.record(z.string(),pu).nullish(),Steps:z.record(z.string(),z.record(z.string(),No)).nullish()}).passthrough(),hu=z.object({Flows:z.record(z.string(),fy).nullish(),Settings:yy.nullish(),Presets:Ry.nullish()}).passthrough(),Cy=z.object({}).passthrough().transform(o=>o),du=z.object({FlowID:z.string(),Status:sy,CurrentStepID:z.string().nullish(),CurrentStep:No.nullish(),TotalSteps:z.number(),CompletedSteps:z.number(),CanSkip:z.boolean(),RewardClaimed:z.boolean(),RewardPending:z.boolean(),VariantID:z.string().nullish()}).passthrough(),mi=z.object({State:Cy.nullish(),Flows:z.array(du).nullish(),UnlockedFeatures:z.array(z.string()).nullish()}).passthrough(),Wt=z.object({Flow:du.nullish()}).passthrough(),mu=z.object({FlowID:z.string().nullish(),Granted:O.nullish()}).passthrough(),fu=z.array(Me(Wt)),gu=z.object({FlowID:z.string(),StepID:z.string(),Progress:z.number(),Target:z.number(),Completed:z.boolean()}).passthrough(),mt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function fi(o){return Array.isArray(o)?o.filter(e=>e!==null).map(fi):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).filter(([,e])=>e!==null).map(([e,t])=>[e,fi(t)])):o}var gi=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),n=this.last.get(e);return n!==void 0&&t-n<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var 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 yu(o){return o===429||o>=500&&o<=599}function Ri(o,e=Math.random){let t=Math.min(500*Math.pow(2,o-1),4e3),n=t*.2*(e()*2-1);return Math.max(50,t+n)}function Kt(o){return new Promise(e=>setTimeout(e,o))}var Ru=15e3;async function Cu(o){try{let t=JSON.parse(await o.text()),n=Number(t?.RetryAfterMs);if(Number.isFinite(n)&&n>0)return n}catch{}let e=Number(o.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Su(o,e=Math.random){return o+10+Math.min(250,o*.2)*e()}function xu(o,e=Math.random){let t=o<=1?1500:o===2?4e3:6e3;return t+t*.1*e()}var _o=15,bu=1e3,Ci=class{constructor(e=_o,t=()=>Date.now(),n=Kt){this.perSecond=e;this.now=t;this.wait=n;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=bu;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(bu-(e-this.starts[0])+5);}}};var Sy=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function Dn(o){if(!o)return null;let e=Sy.exec(o);if(!e)return null;let[,t,n,i]=e;if(!t||n===void 0||i===void 0)return null;let s=new an(n),r=new an(i),p=r.minus(an.max(s,0));return p.lte(0)?null:{currencyID:t,required:r.toNumber(),available:s.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var xy=12e3,by=new Set(["RelatedEntityID"]);function Dy(o,e){if(e===null||typeof e!="object"||Array.isArray(e))return o;let t={};for(let[n,i]of Object.entries(e))by.has(n)||(t[n]=i);try{return `${o}|${JSON.stringify(t)}`}catch{return o}}var Iy=z.object({Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().optional(),QuestProgress:z.array(Uo).nullish(),TutorialProgress:z.array(gu).nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish()}).passthrough(),Si=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 gi(e.throttleMs),this.pacer=new Ci(e.maxRequestsPerSecond??_o),this.clientPlatform=e.clientPlatform??j.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,n,i={}){let s=i.throttleKey??Dy(e,t);if(!this.throttler.tryAcquire(s))return b("throttled","Throttled");if(!this.inflight.add(s))return b("throttled","Duplicate request skipped");this.raiseBusy();try{let r=`${this.baseUrl}/${e}`,p=JSON.stringify(t),m=i.ticket??null,R=i.silent??!1,W=i.timeoutMs??xy,fe=i.autoRetry??!0,Oe=!1,Ie=!1,Ve=0;for(;;){let qt;i.keepalive||await this.pacer.take();try{qt=await this.doFetch(r,p,m,W,i.keepalive??!1);}catch{if(fe&&Ve<3){Ve++,await Kt(Ri(Ve));continue}return this.connectionFailure("Internet Connection Error",R)}let ot=qt.status;if(ot>=200&&ot<300){let ce=!Ie&&this.cryptoTopUpHandler!==null,ke=await this.parseSuccess(qt,n,R,e,ce);if(!ke.ok&&ce){let ge=Dn(ke.error);if(ge){if(Ie=!0,await this.runTopUp(ge))continue;R||this.emitter.emit("error:global",ke.error);}}return ke}if(ot===401){if(!Oe&&this.sessionRefreshHandler){Oe=!0;let ce=null;try{ce=await this.sessionRefreshHandler();}catch{ce=null;}if(ce){m=ce;continue}}return this.emitter.emit("auth:unauthorized",void 0),b("unauthorized","Unauthorized")}if(yu(ot)){let ce=ot===429?await Cu(qt):null;if(ce!==null&&ce>Ru)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ce/1e3)} s`,R);if(fe&&Ve<3){Ve++,await Kt(ce!==null?Su(ce):ot===429?xu(Ve):Ri(Ve));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${ot})`,R)}let Un="";try{Un=await qt.text();}catch{}if(ot===409&&/operation in progress/i.test(Un)&&fe&&Ve<3){Ve++,await Kt(Ri(Ve));continue}return this.handleWebError(Un,ot,R)}}finally{this.inflight.remove(s),this.lowerBusy();}}async doFetch(e,t,n,i,s=false){let r=new AbortController,p=setTimeout(()=>{r.abort();},i);try{let m={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return n&&(m.Authorization=`Bearer ${n}`),await this.fetchImpl(e,{method:"POST",body:t,headers:m,signal:r.signal,...s?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,n,i,s=false){let r;try{r=await e.text();}catch{return this.globalError("Failed to read response body",n)}let p;try{p=JSON.parse(r);}catch{return this.globalError("JSON Parse Error",n)}let m=Iy.safeParse(p);if(!m.success)return this.globalError("Malformed response envelope",n);if(!m.data.Success){let Ie=m.data.Error??"Server returned Success=false",Ve=s&&Dn(Ie);return !n&&!Ve&&this.emitter.emit("error:global",Ie),b("server",Ie)}let R=m.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:m.data.StateEpoch??null,versions:R});let W=m.data.QuestProgress;W&&W.length>0&&this.emitter.emit("quest:systemProgress",W);let fe=m.data.TutorialProgress;fe&&fe.length>0&&this.emitter.emit("tutorial:systemProgress",fe);let Oe=t.safeParse(m.data.Data);if(!Oe.success){let Ie=t.safeParse(fi(m.data.Data));Ie.success&&(Oe=Ie);}if(!Oe.success){let Ie=`Validation error (${i}): ${Oe.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",Ie),n||this.emitter.emit("error:global",Ie),b("validation",Ie)}return a$1(Oe.data)}handleWebError(e,t,n){let i=`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");i=typeof r=="string"&&r.length>0?`HTTP ${t}: ${r}`:`HTTP ${t}: ${e}`;}catch{i=`HTTP ${t}: ${e}`;}return n||this.emitter.emit("error:global",i),b("server",i)}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 In(o){return (typeof o=="string"?o:o.toISOString()).slice(0,10)}function _n(o){return `${In(o)}T00:00:00.000Z`}function Du(o){let e=new Date(o);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Iu(o,e){return new Date(o.getTime()+e*6e4).toISOString()}function Fo(o,e,t,n){let i={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return i;o.InventoryV2??={};let s=o.InventoryV2,r=n.toISOString(),p=new Map,m=new Map,R=new Map,W=new Map,fe=new Map,Oe=new Map,Ie=new Map,Ve=new Map,qt=e.Grant?.PremiumTiers??[],ot=qt.length;for(let ce=0;;ce++){let ke,ge;if(ce===0)ke=e.Grant?.Standard?.Entries,ge=false;else if(ce-1<ot)ke=qt[ce-1]?.Resources?.Entries,ge=false;else if(ce===1+ot)ke=e.Consume?.Standard?.Entries,ge=true;else break;if(ke)for(let me of ke){if(me.Type==null)continue;let Re=Math.max(0,me.Amount??0);if(!(Re<=0))switch(me.Type){case "VirtualCurrency":{if(!me.CurrencyID)continue;let Se=ge?m:p;Se.set(me.CurrencyID,(Se.get(me.CurrencyID)??0)+Re);break}case "CryptoCurrency":{if(!me.CurrencyID)continue;let Se=ge?W:R;Se.set(me.CurrencyID,(Se.get(me.CurrencyID)??new an(0)).plus(Re));break}case "Item":{if(!me.ItemID)continue;let Se=vy(t,me.CatalogID,me.ItemID),Ae=(Se?Se.IsStackable??true:true)?ge?Oe:fe:ge?Ve:Ie;Ae.set(me.ItemID,(Ae.get(me.ItemID)??0)+Re);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(i.vcChanged=p.size>0||m.size>0,i.vcChanged){s.VirtualCurrencies??={};for(let ce of new Set([...p.keys(),...m.keys()])){let ke=p.get(ce)??0,ge=m.get(ce)??0,me=ke-ge,Re=s.VirtualCurrencies[ce];Re?(Re.Amount+=me,Re.UpdatedAt=r,Re.Daily&&In(Re.Daily.PeriodStartUtc)===In(n)?(Re.Daily.Earned+=ke,Re.Daily.Spent+=ge):Re.Daily={PeriodStartUtc:_n(n),Earned:ke,Spent:ge}):s.VirtualCurrencies[ce]={Amount:me,CreatedAt:r,UpdatedAt:r,Daily:{PeriodStartUtc:_n(n),Earned:ke,Spent:ge}};}}if(i.ccChanged=R.size>0||W.size>0,i.ccChanged){s.CryptoCurrencies??={};for(let ce of new Set([...R.keys(),...W.keys()])){let ke=R.get(ce)??new an(0),ge=W.get(ce)??new an(0),me=ke.minus(ge),Re=s.CryptoCurrencies[ce];Re?(Re.Amount=new an(Re.Amount).plus(me).toString(),Re.UpdatedAt=r):s.CryptoCurrencies[ce]={Amount:me.toString(),Frozen:"0",CreatedAt:r,UpdatedAt:r};}}if(i.itemsChanged=fe.size>0||Oe.size>0||Ie.size>0||Ve.size>0,i.itemsChanged){s.Items??={},s.UnstackableItems??={};let ce=s.UnstackableItems,ke=new Set([...fe.keys(),...Oe.keys(),...Ie.keys(),...Ve.keys()]);for(let ge of ke){let me=(fe.get(ge)??0)-(Oe.get(ge)??0),Re=(Ie.get(ge)??0)-(Ve.get(ge)??0),Se=me+Re,ht=s.Items[ge];ht?(me!==0&&(ht.StackableAmount+=me),Re!==0&&(ht.UnstackableAmount+=Re),Se!==0&&(ht.TotalAmount+=Se)):s.Items[ge]={StackableAmount:Math.max(0,me),UnstackableAmount:Math.max(0,Re),TotalAmount:Math.max(0,Se)};}for(let[ge,me]of Ve){if(me<=0)continue;let Re=Object.values(ce).filter(Se=>Se.ItemID===ge&&Se.EquippedSlot==null&&(Se.ExpiresAt==null||new Date(Se.ExpiresAt)>n)).sort(Py).slice(0,me).map(Se=>Se.ItemInstanceID);for(let Se of Re)delete ce[Se];}for(let[ge,me]of Ie){let Re=Ay(t,ge);for(let Se=0;Se<me;Se++){let ht=a();ce[ht]={ItemInstanceID:ht,ItemID:ge,CatalogID:Re,RemainingUses:1,AcquiredAt:r};}}}o.EventToken??={};let Un=o.EventToken;for(let ce=0;;ce++){let ke,ge;if(ce===0)ke=e.Grant?.Standard?.EventTokens,ge=false;else if(ce-1<ot)ke=qt[ce-1]?.Resources?.EventTokens,ge=false;else if(ce===1+ot)ke=e.Consume?.Standard?.EventTokens,ge=true;else break;if(!(!ke||ke.length===0))for(let me of ke){let Re=me.Address;if(!Re||Re.Type==null)continue;let Se=me.Amount??0;if(Se<=0)continue;let ht=Ty(Un,Re.Type);if(!ht)continue;let Ae=ht[Re.EntityID];Ae||(Ae={},ht[Re.EntityID]=Ae),Ae.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Ae.Daily??={Date:_n(n),TotalEarned:0},Ae.Meta??={};let Ln=me.Source&&me.Source.length>0?me.Source:"CustomAction";ge?(Ae.Balance.Current-=Se,Ae.Balance.TotalSpent+=Se):(Ae.Balance.Current+=Se,Ae.Balance.TotalEarned+=Se,In(Ae.Daily.Date)!==In(n)&&(Ae.Daily={Date:_n(n),TotalEarned:0}),Ae.Daily.TotalEarned+=Se,Ae.Daily.EarnedBySource??={},Ae.Daily.EarnedBySource[Ln]=(Ae.Daily.EarnedBySource[Ln]??0)+Se,Ae.Daily.TriggersBySource??={},Ae.Daily.TriggersBySource[Ln]=(Ae.Daily.TriggersBySource[Ln]??0)+1,Ae.Daily.LastTriggerBySource??={},Ae.Daily.LastTriggerBySource[Ln]=r,Ae.Meta.JoinedAtUtc||(Ae.Meta.JoinedAtUtc=r),Ae.Meta.LastEarnedAtUtc=r),i.tokensChanged=true;}}return i}function Py(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 vy(o,e,t){let n=o?.Catalogs;if(n){if(e){let i=n[e]?.Items?.[t];if(i)return i}for(let i of Object.values(n)){let s=i.Items?.[t];if(s)return s}}}function Ay(o,e){let t=o?.Catalogs;if(t){for(let[n,i]of Object.entries(t))if(i.Items&&e in i.Items)return n}}function Ty(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??={};case "Challenge":return o.Challenge??={};case "ChallengePoints":return o.ChallengePoints??={};default:return null}}function Pu(o,e,t){let n={drop:[],restore:{}};if(!t)return n;let i=t.ChangedInstances??{},s=new Set(t.RemovedInstanceIDs??[]),r=new Set;for(let m of Object.values(i))m?.ItemID&&r.add(m.ItemID);for(let m of s){let R=o[m]?.ItemID;R&&r.add(R);}if(r.size===0)return n;let p=m=>s.has(m)||m in i;if(e){for(let[m,R]of Object.entries(e))m in o||p(m)||R&&r.has(R.ItemID)&&n.drop.push(m);for(let[m,R]of Object.entries(o))m in e||p(m)||R&&r.has(R.ItemID)&&(n.restore[m]=R);}return n}function Wo(o,e){return o===e||o.startsWith(`${e}:`)}var bi=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 n of Object.values(t))n&&(typeof n.Amount=="number"&&(n.Amount=String(n.Amount)),typeof n.Frozen=="number"&&(n.Frozen=String(n.Frozen)));}applyUserState(e){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 n of t)this.currentState[n]=e[n];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,n=new Date){if(!this.currentState)return;let i=Fo(this.currentState,e,t,n);this.emitResourceChanges(i,false);}applyResourcesWithDelta(e,t,n,i=new Date){if(!this.currentState)return;let s=this.currentState,r={...s.InventoryV2?.UnstackableItems??{}},p=Fo(s,e,n,i),m=Pu(r,s.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),W=t?.RemovedInstanceIDs??[],fe=m.drop.length>0||Object.keys(m.restore).length>0||R.length>0||W.length>0;if(fe){s.InventoryV2??={},s.InventoryV2.UnstackableItems??={};let Oe=s.InventoryV2.UnstackableItems;for(let Ie of m.drop)delete Oe[Ie];for(let[Ie,Ve]of Object.entries(m.restore))Oe[Ie]=Ve;for(let[Ie,Ve]of R)Oe[Ie]=Ve;for(let Ie of W)delete Oe[Ie];}this.emitResourceChanges(p,fe);}emitResourceChanges(e,t){let n=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),n&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(n||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,n,i){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let s=this.currentState.InventoryV2.CryptoCurrencies,r=t instanceof an?t:new an(t),p=i===void 0?new an(0):i instanceof an?i:new an(i),m=n??new Date().toISOString(),R=s[e];R?(R.Amount=new an(R.Amount).plus(r).toString(),p.isZero()||(R.Frozen=new an(R.Frozen??0).plus(p).toString()),R.UpdatedAt=m):s[e]={Amount:r.toString(),Frozen:p.toString(),CreatedAt:m,UpdatedAt:m},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,n){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let i=this.currentState.Store.Purchases,s=i[e];s||(s={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},i[e]=s),s.TotalPurchases+=t,s.LastPurchasedAt=n,n>=s.DailyResetUtc?(s.DailyPurchases=t,s.DailyResetUtc=Du(n)):s.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,n){if(!e||n<=0)return;this.currentState??={};let i=this.currentState.Lootbox??={};if(i.Pity??={},t){let s=new Date().toISOString();for(let r of t)r.RuleID&&(i.Pity[`${e}:${r.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:s});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchRewardWindowState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Windows??={},this.currentState.Reward.Windows[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,n){if(!e)return;this.currentState??={},this.currentState.Quest??={};let i=this.currentState.Quest;if(t){i.Cycles??={};let s=i.Cycles[t];if(!s)return;s.Quests??={};let r=s.Quests[e]??={QuestID:e,Status:n};r.Status=n,n==="Claimed"&&(r.ClaimedAtUtc??=new Date().toISOString());}else {i.PermanentQuests??={};let s=i.PermanentQuests[e]??={QuestID:e,Status:n};s.Status=n,n==="Claimed"&&(s.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let n=this.getQuestPointsProgress(e);n&&(n.Milestone??={},this.markMilestoneClaimed(n.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let n of Object.values(e)){if(!n.CycleID)continue;let i=n.InstanceKey?`${n.CycleID}:${n.InstanceKey}`:n.CycleID,s=t[i]??={};s.Balance??={Current:0,TotalEarned:0,TotalSpent:0},s.Balance.Current=n.PointsCurrent??0,s.Balance.TotalEarned=n.PointsTotalEarned??0,s.Milestone??={};for(let r of n.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(s.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 n=this.currentState.Quest.Cycles[e];n&&(n.ClaimedGroupCompletionIDs??=[],n.ClaimedGroupCompletionIDs.includes(t)||n.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let n=t.Flows[e.FlowID]??={FlowID:e.FlowID};n.Status=e.Status,n.CurrentStepID=e.CurrentStepID??null,n.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(n.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let n of e){if(!n.FlowID||!n.StepID)continue;let i=t.Flows[n.FlowID]??={FlowID:n.FlowID,Status:"InProgress"};i.Steps??={};let s=i.Steps[n.StepID]??={StepID:n.StepID};s.Progress=n.Progress,n.Completed&&(s.CompletedAtUtc??=new Date().toISOString(),i.CurrentStepID===n.StepID&&(i.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let n of e){if(!n.QuestID)continue;let i;if(!n.CycleID)t.PermanentQuests??={},i=t.PermanentQuests[n.QuestID]??={QuestID:n.QuestID,Status:n.Status};else {t.Cycles??={};let s=t.Cycles[n.CycleID];if(!s)continue;s.Quests??={},i=s.Quests[n.QuestID]??={QuestID:n.QuestID,Status:n.Status};}if(i.Status=n.Status,n.ObjectiveID){i.Objectives??={};let s=i.Objectives[n.ObjectiveID]??={ObjectiveID:n.ObjectiveID,CurrentValue:0,Completed:false};s.CurrentValue=n.NewValue??0,n.ObjectiveCompleted&&(s.Completed=true,s.CompletedAtUtc??=new Date().toISOString());}n.Status==="Completed"&&(i.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[n,i]of Object.entries(t))if(Wo(n,e)&&i)return i;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,n,i){if(!(!t||!n)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[s,r]of Object.entries(this.currentState.EventToken.TimedEvent))r&&((i?s!==i:!Wo(s,t))||this.markMilestoneClaimed(r.Milestone??(r.Milestone={}),n));this.patchActiveEventMilestoneClaimed(e,t,n,i),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,n,i){let s=this.activeEventsCache?.ActiveEvents;if(s)for(let r of s)r.Type!==e||r.TimedEventID!==t||i&&r.TokenEntityID&&r.TokenEntityID!==i||(r.Progress??={},this.markMilestoneClaimed(r.Progress.Milestone??(r.Progress.Milestone={}),n));}markMilestoneClaimed(e,t){e.Claims??={};let n=e.Claims[t]??={};n.ClaimedAt??=new Date().toISOString(),n.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let n=this.ensureLeaderboardProgress(e);n.CurrentScore=t.CurrentScore??0,n.LastKnownRank=t.LastKnownRank??0,n.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,n.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,n.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,n,i){if(!e)return;let s=this.ensureLeaderboardProgress(e);(s.ScoreCycleVersion??0)<i&&(s.ScoreEarnedThisCycle=0,s.ClaimedMilestoneIDs=[],s.BracketID=null),s.CurrentScore=t,s.ScoreEarnedThisCycle=(s.ScoreEarnedThisCycle??0)+n,s.ScoreCycleVersion=i,s.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let n=this.ensureLeaderboardProgress(e);n.ClaimedMilestoneIDs??=[],n.ClaimedMilestoneIDs.includes(t)||n.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,n=t[e];return n||(n={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=n),n}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let n=this.ensureSeasonState(e);n.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let n=this.ensureSeasonState(e);n.ClaimedTierRewards??=[],n.ClaimedTierRewards.includes(t)||n.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,n=t[e];return n||(n={SeasonChainID:e},t[e]=n),n}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let n=this.currentState?.Character?.Characters;if(!n)return;let i=false;for(let s of Object.values(n))for(let r of Object.values(s.Equipment??{}))r?.ItemInstanceID===e&&(r.Level=t,i=true);i&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySelectedCharacter(e){this.currentState??={},this.currentState.Character??={};let t=e??null;(this.currentState.Character.SelectedCharacterID??null)!==t&&(this.currentState.Character.SelectedCharacterID=t,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let n=this.currentState.Character.Characters,i=n[e];i||(i={CharacterID:e},n[e]=i),t(i),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,n){if(!e||!t)return;let i=this.currentState?.Character?.Characters?.[e];i&&(i.Equipment??={},n===null?delete i.Equipment[t]:i.Equipment[t]=n,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,n=false;for(let[i,s]of Object.entries(e.ChangedInstances??{}))t[i]=s,n=true;for(let i of e.RemovedInstanceIDs??[])i in t&&(delete t[i],n=true);n&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,n){this.currentState??={};let i=this.currentState.CoopEvent??={MyObjectIndex:-1};i.ActiveGroupID=e,i.ActiveCoopEventID=t,i.MyObjectIndex=n,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(n=>n!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(n=>n!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(n=>n!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),n=false;typeof e.FriendsCount=="number"&&(n||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(n||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(n||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),n&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let n=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let i of Object.keys(n)){let s=n[i];s&&s.BoostID===e.BoostID&&i!==e.InstanceID&&delete n[i];}n[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,n,i,s){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let r=this.currentState.CustomData,p={Value:n,UpdatedAt:new Date().toISOString(),Version:i,LastWriter:"Client",ExpiresAt:s??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 n=this.currentState.CustomData;if(e==="Private")n.Private&&delete n.Private[t];else if(e==="Public")n.Public&&delete n.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let n=this.ensureBoard();n.BuildingStates??=[];let i=n.BuildingStates.find(s=>s.SlotIndex===e);i||(i={SlotIndex:e},n.BuildingStates.push(i)),t(i),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let i=this.ensureBoard().Pending;i&&(e&&(i.RaidLayout=e),t>=0&&(i.OpenedIndices??=[],i.OpenedIndices.includes(t)||i.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let n=this.ensureBoard().Pending;!n||n.Type.toUpperCase()!=="SPECIAL"||(n.Special??={},e(n.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let i of Object.values(e.CryptoBalances??{}))i?.CurrencyID&&this.patchCryptoCurrencyDelta(i.CurrencyID,i.AmountDelta,i.UpdatedAt,i.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),n=e.PendingAdded;if(t.size>0||n){let i=this.currentState.Blockchain??={},s=i.PendingWithdrawals??[];t.size>0&&(s=s.filter(r=>!r.TitleTransactionID||!t.has(r.TitleTransactionID))),n&&!s.some(r=>r.TitleTransactionID===n.TitleTransactionID)&&(s=[...s,n]),i.PendingWithdrawals=s;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var Di=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,n]of Object.entries(e))this.sections.has(t)||this.sections.set(t,n);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let n=this.config?.[e];return n??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var Ii=class{user;config;constructor(e){this.user=new bi(e),this.config=new Di;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function wy(o){return o}var zy=0,ky=1500,My=3,vi=class{constructor(e,t,n=null,i="",s="auto"){this.emitter=e;this.config=t;this.storage=n;this.titleId=i;this.loginMode=s;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return a$1(void 0);let n=Date.now(),i=[],s=[];for(let m of new Set(e)){let R=this.rules.get(m);if(R&&(t?.force||R.needsServer(n))){i.push(this.runRule(m,R));continue}(t?.force||!this.state.isStateFresh(m,t?.maxAgeMs))&&s.push(m);}let p=(await Promise.all([...i,s.length>0?this.queueSlice(s):Promise.resolve(a$1(void 0))])).find(m=>!m.ok);return p&&!p.ok?p:a$1(void 0)}runRule(e,t){let n=this.ruleInflight.get(e);if(n)return n;let i=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,i),i}queueSlice(e){for(let n of e)this.pending.add(n);let t=new Promise(n=>this.waiters.push(n));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},zy),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let n;this.batchRunning=new Promise(i=>n=i);try{let i=this.state?await this.state.readStateSlice(e):a$1(void 0),s=i.ok?a$1(void 0):i;for(let r of t)r(s);}finally{this.batchRunning=null,n();}}async read(e,t,n){this.register(e);let i=Pi(e,n?.args);if(this.noteUsed(e,n?.args,n?.loginParams),!n?.forceRefresh){let R=this.fresh(i,n?.maxAgeMs);if(R)return a$1(R.data);let W=this.loginFailures.get(i);if(W)return this.loginFailures.delete(i),W;let fe=this.inflight.get(i);if(fe)return fe}let s=this.generation.get(i)??0,r=Date.now(),m=t().then(R=>{if(!R.ok)return R;let W=Date.now();if((this.generation.get(i)??0)===s)return this.entries.set(i,{data:R.data,storedAt:W,expiresAt:Ko(e,R.data,W)}),R;let fe=this.entries.get(i);if(fe&&fe.storedAt>=r)return R;let Oe=Ko(e,R.data,W);return this.entries.set(i,{data:R.data,storedAt:W,expiresAt:Math.min(Oe??1/0,W+ky)}),R}).finally(()=>{this.inflight.get(i)===m&&this.inflight.delete(i);});return this.inflight.set(i,m),m}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...n})=>n))}acceptLoginViews(e){for(let t of e??[]){let n=this.loginBindings.get(t.Name);if(!n)continue;let i=t.Key?t.Key:void 0,s=Pi(n.view,i);if(!t.Success){this.loginFailures.set(s,b("server",t.Error??"View failed."));continue}let r=n.schema.safeParse(t.Data);r.success&&(this.loginFailures.delete(s),n.apply(r.data,i),this.put(n.view,r.data,i));}}noteUsed(e,t,n){if(!e.login||this.loginMode!=="auto")return;let i=e.login;this.loadUsed().then(()=>{let s=vu({Name:i,Key:t});this.used.get(s)?.n!==this.session&&(this.used.set(s,{Name:i,Key:t??"",...n,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>My||this.used.set(vu(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),n=t?JSON.parse(t):null;return !n||typeof n.s!="number"||!Array.isArray(n.v)?e:{session:n.s,views:n.v.filter(i=>i&&typeof i.Name=="string"&&typeof i.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(Pi(e,t))?.data}put(e,t,n){this.register(e);let i=Pi(e,n);this.bump(i);let s=Date.now();this.entries.set(i,{data:t,storedAt:s,expiresAt:Ko(e,t,s)});}invalidate(e,t){let n=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${n}|${t}`);return}for(let i of [...this.entries.keys(),...this.inflight.keys()])(i===n||i.startsWith(`${n}|`))&&this.drop(i);this.drop(n);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,n])=>({key:t,ageMs:e-n.storedAt,expiresInMs:n.expiresAt===null?null:n.expiresAt-e}))}fresh(e,t){let n=this.entries.get(e);if(!n)return;let i=Date.now();if(!(n.expiresAt!==null&&i>=n.expiresAt)&&!(t!==void 0&&i-n.storedAt>t))return n}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let n of this.views.values())n.dependsOn?.some(i=>t.has(i))&&this.invalidate(n);}};function Pi(o,e){return e===void 0?o.key:`${o.key}|${e}`}function vu(o){return o.Key?`${o.Name}|${o.Key}`:o.Name}function Ko(o,e,t){let n=o.expiresAt?.(e)??null,i=o.ttlMs!==void 0?t+o.ttlMs:null;return n!==null&&i!==null?Math.min(n,i):n??i}var Ai=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 Oy(e)?e:r.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 Oy(o){return o!==null&&Object.values(r).includes(o)}var Ey=8,qy=100,Uy=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,Ti=["GameLoop"];function Ly(o){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(o)}var wi=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=r.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,n){let i=this.authContext;if(!i)return c;let s=this.baseRequest();s.UserID=i.userID,s.ClientSessionTicket=i.clientSessionTicket,s.WalletAddress=e,s.NetworkID=t,n&&(s.WalletSignature=n);let r=await this.ctx.api.authentication.linkWallet(s);return r.ok&&r.data.PlayAccess&&this.setPlayAccess(r.data.PlayAccess),r}async unlinkWallet(e){let t=this.authContext;if(!t)return c;let n=this.baseRequest();n.UserID=t.userID,n.ClientSessionTicket=t.clientSessionTicket,n.NetworkID=e;let i=await this.ctx.api.authentication.unlinkWallet(n);return i.ok&&i.data.PlayAccess&&this.setPlayAccess(i.data.PlayAccess),i}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.host.getDeviceID(),e.Device=this.ctx.host.getDeviceModel(),e.Platform=this.ctx.host.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(r.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.host.getTelegramInitDataRaw();if(!e)return b("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let n=await this.ctx.api.authentication.loginWithTelegram(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(r.Telegram)):n}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.Password=t;let i=await this.ctx.api.authentication.loginWithEmail(n);if(!i.ok)return i;this.applyAuthContext(i.data);let s=await this.fetchAndApplyClientState(r.Email);return s.ok&&this.keepEmailCredentials(e,t),s}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.Password=t,n.DeviceID=this.ctx.host.getDeviceID(),n.Device=this.ctx.host.getDeviceModel(),n.Platform=this.ctx.host.getPlatform();let i=await this.ctx.api.authentication.registerWithEmail(n);return i.ok?(this.pendingRegistration={email:e,password:t},a$1({codeTtlMinutes:i.data.CodeTtlMinutes??0,resendCooldownSeconds:i.data.ResendCooldownSeconds??0})):i}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.VerificationCode=t;let i=await this.ctx.api.authentication.confirmEmailRegistration(n);if(!i.ok)return i;this.applyAuthContext(i.data);let s=await this.fetchAndApplyClientState(r.Email);return s.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,s}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let n=await this.ctx.api.authentication.resendVerificationCode(t);return n.ok?a$1(void 0):n}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let n=await this.ctx.api.authentication.loginWithGoogle(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(r.Google)):n}async loginWithApple(e,t){if(!e?.trim())return b("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.AppleIDToken=e,t?.nonce&&(n.AuthNonce=t.nonce),t?.name?.trim()&&(n.Username=t.name.trim());let i=await this.ctx.api.authentication.loginWithApple(n);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(r.Apple)):i}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.WalletAddress=e,n.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(n)}async loginWithWallet(e,t,n){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.WalletAddress=e,i.NetworkID=t,i.WalletSignature=n,i.Platform=this.ctx.host.getPlatform(),i.Device=this.ctx.host.getDeviceModel(),i.DeviceID=this.ctx.host.getDeviceID();let s=await this.ctx.api.authentication.loginWithWallet(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(r.Wallet)):s}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.host.getDeviceID(),t.Device=this.ctx.host.getDeviceModel(),t.Platform=this.ctx.host.getPlatform();let n=await this.ctx.api.authentication.loginWithSsoCode(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(r.iDosGames)):n}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 n=await this.ctx.userService.prepareLoginClientState(Ti,Ti);t.ClientState=n.request;let i=await this.ctx.api.authentication.resolvePlatformGameSession(t);if(!i.ok)return i;this.applyAuthContext(i.data),this.platformGameSession=true;let s=i.data.ClientState;return this.fetchAndApplyClientState(r.iDosGames,s?()=>n.finish(s):void 0)}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,n){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.Email=e,i.ResetToken=t,i.Password=n,this.ctx.api.authentication.resetPassword(i)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==r.None?e:r.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let n=this.baseRequest();n.RefreshToken=t,e?.appOpened&&(n.AppOpened=true);let i=await this.ctx.api.authentication.refreshSession(n);return i.ok?(this.applyRefresh(i.data),"ok"):(Ly(i.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,n){switch(e){case r.Email:return this.loginWithEmail(t,n);case r.Device:case r.None:return this.loginWithDeviceID();case r.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 this.ctx.host.signIn(this.ctx.settings.titleID);if(!t.ticket)return null;let n=this.baseRequest();n.PlatformGameTicket=t.ticket;let i=await this.ctx.api.authentication.resolvePlatformGameSession(n);return i.ok?(this.applyAuthContext(i.data),this.platformGameSession=!0,i.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==r.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===r.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&&Uy.test(e)}static isValidPasswordLength(e){return e.length>=Ey&&e.length<=qy}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=r.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e,t){let n=t?await t():await this.ctx.userService.getClientStateExcept(Ti,Ti);return n.ok&&(this.sessionAuthType=e,this.rememberSession?(this.ctx.authStore.saveAuthType(e),this.ctx.authStore.saveRefreshToken(this.sessionRefreshToken)):this.ctx.authStore.clear(),this.ctx.emitter.emit("auth:loggedIn",void 0)),n}};var By="idos:cfg",Pn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Au(t)}`:e&&e.length>0?`f:${Au(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.v!="string"||!n.c?null:n}catch{return null}}async write(e,t,n){try{let i={v:t,c:n};await this.storage.set(this.keyOf(e),JSON.stringify(i));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${By}:${this.titleId}:${e}`}};function Au(o){return [...o].map(e=>e.toLowerCase()).sort().join(",")}var Tu="idos:loc",vn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.v!="number"||!n.t||typeof n.t!="object"?null:n}catch{return null}}async write(e,t,n){try{let i={v:t,t:n};await this.storage.set(this.keyOf(e),JSON.stringify(i)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let n={};for(let[i,s]of Object.entries(t))typeof s=="number"&&s>0&&(n[i]=s);return n}catch{return {}}}async noteVersion(e,t){let n=await this.readVersions();n[e]!==t&&(n[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(n)));}keyOf(e){return `${Tu}:${this.titleId}:${e}`}versionsKey(){return `${Tu}:${this.titleId}:versions`}};var Gy="idos:sec",zi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let n=JSON.parse(t);return !n||typeof n!="object"||n.v!==e||!n.s||typeof n.s!="object"?{}:n.s}catch{return {}}}async write(e,t){try{let n={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(n));}catch{}}keyOf(){return `${Gy}:${this.titleId}`}};var Ny="idos:state",ki=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.e!="string"||!n.v||!n.s?null:n}catch{return null}}async write(e,t,n,i){if(!(!e||!t))try{let s={e:t,v:n,s:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}keyOf(e){return `${Ny}:${this.titleId}:${e}`}};function _y(o,e){if(!o)return;let t=new Set((e??[]).map(i=>i.trim().toLowerCase()));if(t.size===0)return o;let n={};for(let[i,s]of Object.entries(o))t.has(i.toLowerCase())||(n[i]=s);return n}function Qo(o,e,t,n){let i={...o??{}};if(!e||!t||!n)return i;for(let[s,r]of Object.entries(t))n[s]===r&&s in e&&(i[s]=e[s]);return i}function Vy(o){return {...o??{}}}function Ho(o){return typeof o.StateEpoch=="string"&&o.StateEpoch.length>0?o.StateEpoch:null}var Mi=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,n=Date.now()){if(this.versions[e]===void 0)return false;let i=this.confirmedAt[e];return i===void 0?false:t===void 0||n-i<=t}forget(e){let t=[];for(let n of e)this.versions[n]!==void 0&&(delete this.versions[n],delete this.confirmedAt[n],t.push(n));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=_y(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let r=Object.keys(this.versions);this.reset(e),this.notify(r);}return []}let n=Date.now(),i=[],s=[];for(let[r,p]of Object.entries(t)){let m=this.versions[r];m!==p&&(m!==void 0&&p===m+1?(this.versions[r]=p,this.confirmedAt[r]=n):(delete this.versions[r],delete this.confirmedAt[r],m!==void 0&&p>m+1&&s.push(r)),i.push(r),this.dirty=true);}return this.notify(i),s}afterFullRead(e,t){let n=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=Vy(t);let i=Date.now();this.confirmedAt={};for(let r of Object.keys(this.versions))this.confirmedAt[r]=i;this.dirty=true;let s=new Set;for(let r of new Set([...Object.keys(n),...Object.keys(this.versions)]))n[r]!==this.versions[r]&&s.add(r);this.notify([...s]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let n=Date.now(),i=[];for(let[s,r]of Object.entries(t??{}))this.versions[s]!==r&&i.push(s),this.versions[s]=r,this.confirmedAt[s]=n;this.dirty=true,this.notify(i);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var wu=b("server","Title configuration is unavailable (CDN and API both failed)."),Oi=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:a()}:null}get configCache(){return this.cache??=new Pn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new vn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new zi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new Mi(new ki(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){if(!this.ctx.auth.context?.userID||!this.stateStore.currentEpoch)return;let i=this.stateStore.noteMutation(e,t);i.length>0&&(this.ctx.cache.ensureState(i),this.ctx.emitter.emit("user:changedElsewhere",{containers:i}));}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return c;let t=Pn.scopeOf(e.TitleFields,null),n=await this.configCache.read(t);n&&(e.KnownTitleConfigVersion=n.v),await this.prepareLocalization(e);let i=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let s=await this.ctx.api.user.getClientState(e);if(!s.ok)return s;let r=await this.resolveTitleConfig(s.data,t,n,{Fields:e.TitleFields});return r==null?wu:(this.finishStateHandshake(s.data,i),await this.restoreSections(s.data.TitleConfigVersion,r),await this.applyClientState(s.data,r,void 0,void 0),this.ctx.cache.acceptLoginViews(s.data.Views),await this.applyLocalization(s.data.Localization),await this.flushState(i),s)}async prepareStateHandshake(e,t){let n=this.ctx.auth.context?.userID;if(!n)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(n),await this.stateStore.flush(n,this.ctx.data.user.state);let i=this.stateStore.versionsFor(t);if(i){e.KnownStateVersions=i;let s=this.stateStore.currentEpoch;s&&(e.KnownStateEpoch=s);}return {userId:n,cached:this.stateStore.cachedState,sent:i}}finishStateHandshake(e,t){let n=Qo(e.User,t.cached,t.sent,e.StateVersions);e.User=n;let i=Ho(e);!i||!t.userId||this.stateStore.afterFullRead(i,e.StateVersions);}async resolveTitleConfig(e,t,n,i){let s=e.TitleConfigVersion;if(n&&s&&n.v===s)return n.c;if(e.TitleConfigUrl){let p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return s&&await this.configCache.write(t,s,p),p}let r=await this.fetchConfigFromApi(i);return r!=null?(s&&await this.configCache.write(t,s,r),r):n?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let n=await t.json();return n&&typeof n=="object"?n:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let n={...t,...e},i=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(n):await this.ctx.api.title.getTitlePublicConfiguration(n);return i.ok?i.data:null}async getClientStateExcept(e,t){let n=this.baseRequest();if(!n)return c;let i=await this.prepareClientStateExcept(n,e,t,true),s=await this.ctx.api.user.getClientStateExcept(n);return s.ok?this.finishClientStateExcept(i,s.data):s}async prepareLoginClientState(e,t){let n={BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:a()},i=await this.prepareClientStateExcept(n,e,t,false);return {request:n,finish:async s=>{let r=this.ctx.auth.context?.userID??null;return r&&await this.stateStore.load(r),i.handshake={userId:r,cached:null,sent:void 0},this.finishClientStateExcept(i,s)}}}async prepareClientStateExcept(e,t,n,i){e.ExcludeFields=t,e.ExcludeTitleFields=n;let s=Pn.scopeOf(null,n??[]),r=await this.configCache.read(s);r&&(e.KnownTitleConfigVersion=r.v),await this.prepareLocalization(e);let p=i?await this.prepareStateHandshake(e,t??null):{userId:null,cached:null,sent:void 0};return await this.prepareLoginViews(e),{scope:s,cached:r,handshake:p,excludeFields:t,excludeTitleFields:n}}async finishClientStateExcept(e,t){let n=await this.resolveTitleConfig(t,e.scope,e.cached,{ExcludeFields:e.excludeTitleFields??[]});return n==null?wu:(this.finishStateHandshake(t,e.handshake),await this.restoreSections(t.TitleConfigVersion,n),await this.applyClientState(t,n,e.excludeFields,e.excludeTitleFields),this.ctx.cache.acceptLoginViews(t.Views),await this.applyLocalization(t.Localization),await this.flushState(e.handshake),a$1(t))}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let n=t,i={};for(let[s,r]of Object.entries(await this.sectionCache.read(e)))n[s]==null&&(i[s]=r);this.ctx.data.config.restoreSections(i),this.ctx.data.config.setSectionSink((s,r)=>{n[s]!=null||r==null||(i[s]=r,this.sectionCache.write(e,i));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let n=await this.localizationCache.readVersions();Object.keys(n).length>0&&(e.KnownLocalizationVersions=n);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),n=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:n});}async resolveLocalizationTable(e){let t=e.Locale??null,n=e.Version??0;if(!t)return null;let i=await this.localizationCache.read(t);if(n<=0)return i?.t??null;if(i&&i.v===n)return i.t;if(e.Url){let r=await this.fetchLocalizationFromCdn(e.Url);if(r!=null)return await this.localizationCache.write(t,n,r),r}let s=await this.fetchLocalizationFromApi(t,i?.v??0);return s??i?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let n=await t.json();return n&&typeof n=="object"?n:null}catch{return null}}async fetchLocalizationFromApi(e,t){let n=this.baseRequest();if(!n)return null;let i=await this.ctx.api.localization.getLocalizationTable({...n,Locale:e,KnownVersion:t});if(!i.ok)return null;let s=i.data;if(s.NotModified)return null;let r=s.Entries??{},p=s.Version??0,m=s.Locale??e;return p>0&&await this.localizationCache.write(m,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}async getUserState(e){let t=this.baseRequest();if(!t)return c;e&&e.length>0&&(t.Fields=e);let n=await this.prepareStateHandshake(t,null),i=await this.ctx.api.user.getUserState(t);if(!i.ok)return i;let s=Qo(i.data.User,n.cached,n.sent,i.data.StateVersions);i.data.User=s;let r=n.sent??{},p=Object.entries(i.data.StateVersions??{}).filter(([R,W])=>r[R]!==W||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(s,p);let m=Ho(i.data);return m&&(this.stateStore.afterSliceRead(m,i.data.StateVersions),await this.flushState(n)),i}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return 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,n){let i=this.baseRequest();if(!i)return c;i.UsageTime=e,i.IsNewSession=t,i.SessionDurationSeconds=n;let s=await this.ctx.api.user.addUsageTime(i);return s.ok&&this.ctx.emitter.emit("user:usageTimeAdded",s.data),s}async deleteUserAccount(){let e=this.baseRequest();if(!e)return 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 n=await this.ctx.api.user.changeUsername(t);return n.ok&&this.ctx.emitter.emit("user:usernameChanged",n.data),n}async applyClientState(e,t,n,i){let s=n?.includes("GameLoop")===true,r=i?.includes("GameLoop")===true,p=s?this.ctx.data.user.state?.GameLoop:void 0,m=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;s&&R&&R.GameLoop==null&&(R.GameLoop=p);let W=this.ctx.data.config.titlePublicConfiguration;r&&W&&W.GameLoop==null&&(W.GameLoop=m),this.ctx.emitter.emit("user:clientStateReceived",e);}};var qi=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return b("client","SpendID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${a()}`},i=await this.ctx.api.currency.spend(n);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",i.data)),i}async convert(e,t,n,i,s,r){if(!t)return b("client","SourceID is required.");if(!i)return b("client","TargetID is required.");if(s<=0)return b("client","Amount must be positive.");if(e===n&&t===i)return b("client","Source and target must differ.");if(e===f.Crypto||n===f.Crypto)return b("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return c;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:n,TargetID:i,SourceAmount:String(Math.trunc(s)),TransactionID:r&&r.length>0?r:`convert_${e}_${t}_to_${n}_${i}_${a()}`},m=await this.ctx.api.currency.convert(p);if(m.ok){let R=m.data,W={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(W,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return m}async cryptoConvert(e,t,n,i,s,r){let p=s instanceof an?s:new an(s);if(!t)return b("client","SourceID is required.");if(!i)return b("client","TargetID is required.");if(p.lte(0))return b("client","SourceAmount must be a positive decimal.");if(e===n&&t===i)return b("client","Source and target must differ.");if(e===f.Virtual&&n===f.Virtual)return b("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===f.Virtual&&!p.isInteger())return b("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return c;let m={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:n,TargetID:i,SourceAmount:p.toString(),TransactionID:r&&r.length>0?r:`crypto_convert_${e}_${t}_to_${n}_${i}_${a()}`},R=await this.ctx.api.currency.cryptoConvert(m);if(R.ok){let W=R.data,fe=[],Oe=[];if(W.SourceType===f.Virtual&&fe.push({Type:"VirtualCurrency",CurrencyID:W.SourceID,Amount:Math.trunc(Number(W.SourceSpent))}),W.TargetType===f.Virtual&&Oe.push({Type:"VirtualCurrency",CurrencyID:W.TargetID,Amount:Math.trunc(Number(W.TargetCredited))}),fe.length>0||Oe.length>0){let Ie={Consume:fe.length>0?{Standard:{Entries:fe}}:null,Grant:Oe.length>0?{Standard:{Entries:Oe}}:null};this.ctx.data.user.applyResourceOperation(Ie,this.ctx.data.config.itemDefinitions);}W.SourceType===f.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(W.SourceID,new an(W.SourceSpent).negated(),W.ServerTimeUtc),W.TargetType===f.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(W.TargetID,new an(W.TargetCredited),W.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",W);}return R}};var Ui=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,n,i){let s=e.trim();if(!s)return b("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:n,CreditsConfirmationID:i,RelatedEntityID:`upgrade_item_${s}_${a()}`};t&&t.length>0&&(r.FodderInstanceIDs=[...t]);let p=await this.ctx.api.item.upgradeLevel(r);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(p.data.ItemInstanceID??s,p.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",p.data)),p}async upgradeLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},n=await this.ctx.api.item.upgradeLevelsBatch(t);if(n.ok){for(let i of n.data)i.Success&&i.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(i.Data.ItemInstanceID,i.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",n.data);}return n}};var Li=z.object({OptionID:z.string().nullish(),Name:z.string().nullish(),Cost:Ut.nullish(),AllowedPlatforms:z.array(k).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),de=z.record(z.string(),Li),jy=z.object({Store:m,Receipt:z.string(),Signature:z.string().nullish()}).passthrough();var Vn={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},ye=z.object({ConfirmationID:z.string(),Url:z.string(),Status:z.string(),PriceCredits:z.number(),ExpiresAt:u}).passthrough(),zu=z.object({Linked:z.boolean(),Credits:z.number(),TopUpUrl:z.string().nullish()}).passthrough(),Fy={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"},$o=z.object({ServerTimeUtc:u,OfferID:z.string(),Count:z.number(),Resources:O.nullish(),Inventory:Q.nullish(),CreditsConfirmation:ye.nullish()}),ku=z.array(Me($o)),Wy=z.object({OfferID:z.string(),TotalPurchases:z.number(),DailyPurchases:z.number(),DailyResetUtc:u,LastPurchasedAt:u}),Ky=z.object({SlotKey:z.string(),InstanceKey:z.string(),OfferID:z.string().nullish(),Purchases:z.number(),LastPurchasedAt:u}),Mu=z.object({Purchases:z.record(z.string(),Wy).nullish(),Rotations:z.record(z.string(),Ky).nullish()}).passthrough().transform(o=>o),Bt=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(),Bi=z.object({Schedule:Ce.nullish(),Gate:te.nullish()}).passthrough(),Qy={Fixed:"Fixed",Title:"Title",Player:"Player"},Hy=z.object({OfferID:z.string().nullish(),Weight:z.number().nullish(),Gate:te.nullish()}).passthrough(),Ou=z.object({Mode:z.string().nullish(),OfferID:z.string().nullish(),Pool:z.array(Hy).nullish(),Salt:z.string().nullish(),PerInstanceCap:z.number().nullish()}).passthrough(),$y=z.object({Identity:J.nullish(),Availability:J.nullish(),Rotation:J.nullish()}).passthrough(),Jy=z.object({SlotID:z.string().nullish(),Identity:Bt.nullish(),Availability:Bi.nullish(),Rotation:Ou.nullish(),Presets:$y.nullish()}).passthrough(),Zy=z.object({Identity:J.nullish(),Availability:J.nullish()}).passthrough(),Yy=z.object({SectionID:z.string().nullish(),Identity:Bt.nullish(),Availability:Bi.nullish(),Slots:z.record(z.string(),Jy).nullish(),UniqueOffersInSection:z.boolean().nullish(),Presets:Zy.nullish()}).passthrough(),Eu=z.object({Sections:z.record(z.string(),Yy).nullish()}).passthrough(),Xy=z.object({Identity:J.nullish(),Availability:J.nullish(),Layout:J.nullish()}).passthrough(),eR=z.object({StoreID:z.string().nullish(),Identity:Bt.nullish(),Availability:Bi.nullish(),Layout:Eu.nullish(),Presets:Xy.nullish()}).passthrough(),qu=z.object({Options:de.nullish(),CompareAt:z.record(z.string(),Ut).nullish()}).passthrough(),Uu=z.object({Grant:$.nullish()}).passthrough(),Lu=z.object({Schedule:Ce.nullish(),Gate:te.nullish(),Limits:Pe.nullish()}).passthrough(),tR=z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish(),Availability:J.nullish()}).passthrough(),nR=z.object({OfferID:z.string().nullish(),Identity:Bt.nullish(),Pricing:qu.nullish(),Reward:Uu.nullish(),Availability:Lu.nullish(),Presets:tR.nullish()}).passthrough(),iR=z.object({Identity:z.record(z.string(),Bt).nullish(),Availability:z.record(z.string(),Bi).nullish(),Layout:z.record(z.string(),Eu).nullish(),Rotation:z.record(z.string(),Ou).nullish(),Pricing:z.record(z.string(),qu).nullish(),Reward:z.record(z.string(),Uu).nullish(),OfferAvailability:z.record(z.string(),Lu).nullish()}).passthrough(),Gi=z.object({Stores:z.record(z.string(),eR).nullish(),StoreOffers:z.record(z.string(),nR).nullish(),Presets:iR.nullish()}).passthrough(),sR=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:u.nullish()}).passthrough(),rR=z.object({OptionID:z.string(),Name:z.string().nullish(),Cost:Ut.nullish(),CompareAtCost:Ut.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(),oR=z.object({OfferID:z.string(),Identity:Bt.nullish(),PriceOptions:z.array(rR).nullish(),Rewards:$.nullish(),State:sR.nullish()}).passthrough(),aR=z.object({SlotID:z.string(),Identity:Bt.nullish(),SortOrder:z.number(),RotationMode:z.string().nullish(),RotationInstanceKey:z.string().nullish(),RefreshesAtUtc:u.nullish(),RemainingThisRotation:z.number().nullish(),Offer:oR.nullish()}).passthrough(),lR=z.object({SectionID:z.string(),Identity:Bt.nullish(),SortOrder:z.number(),Slots:z.array(aR).nullish()}).passthrough(),uR=z.object({StoreID:z.string(),Identity:Bt.nullish(),SortOrder:z.number(),ScheduleInstanceKey:z.string().nullish(),ExpiresAtUtc:u.nullish(),Sections:z.array(lR).nullish()}).passthrough(),Ni=z.object({ServerTimeUtc:u,Stores:z.array(uR).nullish(),AdCreditBalance:z.number()}).passthrough(),Gt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},cR="OFFER_NOT_IN_ROTATION";var Bu="Store",Gu={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 n of t.Sections??[])for(let i of n.Slots??[]){let s=Date.parse(i.RefreshesAtUtc??"");!Number.isNaN(s)&&(e===null||s<e)&&(e=s);}return e}},_i=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Gu,{schema:Ni,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,n){if(!e)return b("client","OfferID is required.");if(t<1)return b("client","Count must be at least 1.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,StoreID:n?.slot?.storeID,SectionID:n?.slot?.sectionID,SlotID:n?.slot?.slotID,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${i.userID}_${a()}`},r=await this.ctx.api.store.purchase(s);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,n={}){return await this.ctx.credits.pay(i=>this.purchase(e,t,{selectedOptionID:n.selectedOptionID,slot:n.slot,creditsConfirmationID:i}),{onConfirmation:n.onConfirmation,signal:n.signal,pollMs:n.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):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},n=await this.ctx.api.store.purchaseBatch(t);if(n.ok){let i=false;for(let s of n.data)!s.Success||!s.Data||!s.Data.OfferID||(this.ctx.data.user.patchStorePurchase(s.Data.OfferID,s.Data.Count,s.Data.ServerTimeUtc),!i&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true));this.ctx.emitter.emit("store:offersPurchasedBatch",n.data);}return n}async getDefinitions(e){let t=this.ctx.cache.configSection(Bu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.store.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Bu,i.data),this.ctx.emitter.emit("store:definitionsLoaded",i.data)),i}getStorefront(e){return this.ctx.cache.read(Gu,()=>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 n of t.Sections??[])for(let i of n.Slots??[]){let s=i.RefreshesAtUtc;s&&(e===null||Date.parse(s)<Date.parse(e))&&(e=s);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return 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 Vi=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let n=await e(void 0);if(!n.ok||!n.data.CreditsConfirmation)return n;let i=n.data.CreditsConfirmation,s=()=>e(i.ConfirmationID);if(this.ctx.host.supports.creditsConfirm){let m=await this.ctx.host.confirmCredits({titleID:this.ctx.settings.titleID,confirmationID:i.ConfirmationID});if(m.ok)return await s();if(m.error==="DECLINED")return b("server","CREDITS_CONFIRMATION_DECLINED");if(m.error==="NOT_ENOUGH_CREDITS")return b("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(i);let r=Math.max(1e3,t.pollMs??2500),p=Date.parse(i.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return b("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>p)return b("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(W=>setTimeout(W,r));let m=await this.ctx.store.getCreditsConfirmation(i.ConfirmationID);if(!m.ok)continue;let R=m.data.Status;if(R!==Vn.Pending)return R===Vn.Declined?b("server","CREDITS_CONFIRMATION_DECLINED"):R===Vn.Expired?b("server","CREDITS_CONFIRMATION_EXPIRED"):await s()}}};var ji=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$1(t.data.Purchase??{}):t}async validatePurchase(e,t,n){if(!t)return b("client","Receipt is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:n?.signature,ProductID:n?.productID,TransactionID:n?.transactionID},s=await this.ctx.api.purchase.validatePurchase(i);return s.ok&&this.applyValidation(s.data),s}async buyWithTelegramStars(e,t){if(!e)return b("client","productID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),ProductID:e},i=await this.ctx.api.purchase.createTelegramInvoice(n);return i.ok&&t?.open!==false&&this.ctx.host.openInvoice(i.data.InvoiceLink),i}async buy(e){if(!e)return b("client","productID is required.");if(!this.ctx.host.supports.storePurchases)return b("client","UNAVAILABLE");if(!this.ctx.auth.context)return c;let t=await this.getDefinitions();if(!t.ok)return t;let n=t.data.Purchase?.Products?.[e],i=this.hostStore(),s=n?.StoreProductIDs?.[i];if(!n||n.Enabled===false||!s)return b("client","NOT_SOLD");let r=this.ctx.buildAuthedBaseRequest(),p=await this.ctx.host.buyProduct({storeProductID:s,type:n.Type??"Consumable",accountID:r.UserID??void 0});return !p.ok||!p.receipt?b("client",p.error??"FAILED"):this.deliver(p.receipt,n)}async restorePending(){if(!this.ctx.host.supports.storePurchases||!this.ctx.auth.context)return 0;let e=await this.ctx.host.pendingPurchases();if(e.length===0)return 0;let t=await this.getDefinitions(),n=t.ok?Object.values(t.data.Purchase?.Products??{}):[],i=0;for(let s of e){let r=n.find(p=>s.storeProductID&&p.StoreProductIDs?.[s.store]===s.storeProductID);(await this.deliver(s,r)).ok&&i++;}return i}async deliver(e,t){let n=await this.validatePurchase(e.store,e.receipt,{signature:e.signature});return n.ok&&await this.ctx.host.finishPurchase(e,(t?.Type??"Consumable")==="Consumable"),n}hostStore(){return this.ctx.host.getClientPlatform()===j.Ios?"AppleAppStore":"GooglePlay"}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},n=await this.ctx.api.purchase.validatePurchasesBatch(t);if(n.ok)for(let i of n.data.Items)i.Success&&i.Data&&this.applyValidation(i.Data);return n}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Nu=3,pR=700,Fi=class{constructor(e){this.ctx=e;e.host.supports.cryptoTopUp&&this.setTopUpHandler(this.hostTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return Dn(e)}hostTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let n=await this.ctx.host.topUp({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return n.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:n.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=Nu;t++){let n=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(n.ok)return;if(n.reason!=="throttled"||t===Nu)break;await Kt(pR);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,n])=>({...n,OptionID:n.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,n)=>(t.OptionID??"").localeCompare(n.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let n of t)if(n?.Type===h.Purchase&&n.ProductID)return n.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let n of t){if(n?.Type!==h.CryptoCurrency||!n.CurrencyID)continue;let i=Number(n.Amount??0);if(!(i>0))continue;let s=this.cryptoBalance(n.CurrencyID);return s>=i?null:{currencyID:n.CurrencyID,required:i,available:s,missing:i-s}}return null}cryptoBalance(e){let n=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(n?.Amount??0)}};var _u="Lootbox",Wi=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(_u,e);if(t){let s={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),a$1(s)}let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.lootbox.getDefinitions(n);if(i.ok){let s=i.data.LootboxDefinitions;s&&(this.ctx.data.config.patchSection(_u,s),this.ctx.emitter.emit("lootbox:definitionsLoaded",s));}return i}async open(e,t,n,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;let r={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:n,Payment:i,CreditsConfirmationID:s,RelatedEntityID:`lootbox_${e}_${n??"default"}_${a()}`},p=await this.ctx.api.lootbox.open(r);if(p.ok&&!p.data.CreditsConfirmation){let m=p.data;m.TriggeredPity&&m.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,m.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(m.Resources,m.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",m);}return p}};var Jo="Reward";function Ki(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Qi=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(Jo)?.Comebacks??{}).some(n=>n?.TrackPresenceOnRead===true),refresh:async()=>{let n=await this.getUserRewardsState();return n.ok&&(t=true),n}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(Jo,e);if(t){let s={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),a$1(s)}let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.reward.getRewardDefinitions(n);if(i.ok){let s=i.data.RewardDefinitions;s&&(this.ctx.data.config.patchSection(Jo,s),this.ctx.emitter.emit("reward:definitionsLoaded",s));}return i}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 n=t.data;this.multiplierEnabled=n.Enabled,this.multiplier=n.Enabled?n.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",n);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return c;let n={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${a()}`},i=await this.ctx.api.reward.claimDailyReward(n);if(i.ok){let s=i.data;this.ctx.data.user.patchDailyCalendarState(s.CalendarID,s.DailyState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",s);}return i}async collectIdleAccrual(e){if(!Ki(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}_${a()}`},n=await this.ctx.api.reward.collectIdleAccrual(t);if(n.ok){let i=n.data;this.ctx.data.user.patchIdleAccrualState(i.AccrualID,i.IdleState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",i);}return n}async claimComebackReward(e){if(!Ki(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}_${a()}`},n=await this.ctx.api.reward.claimComebackReward(t);if(n.ok){let i=n.data;this.ctx.data.user.patchComebackState(i.ComebackID,i.ComebackState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",i);}return n}async claimReward(e){if(!Ki(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}_${a()}`},n=await this.ctx.api.reward.claimReward(t);if(n.ok){let i=n.data;this.ctx.data.user.patchClaimRewardState(i.ClaimID,i.ClaimState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",i);}return n}async claimRewardWindow(e,t,n={}){if(!Ki(e))return b("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return b("client","Amount must be a positive number.");let i=n.boost??"None";if(i==="Ad"&&!n.adRequestID)return b("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:i,...n.adRequestID?{AdRequestID:n.adRequestID}:{},RelatedEntityID:n.roundID??`reward_window_${e}_${a()}`},r=await this.ctx.api.reward.claimRewardWindow(s);if(r.ok){let p=r.data;this.ctx.data.user.patchRewardWindowState(p.WindowID,p.WindowState),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:windowClaimed",p);}return r}};var Hi="Tutorial",Vu={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"]},$i=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Vu,{schema:mi,apply:n=>this.applyUserTutorialState(n)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(Hi)?.Flows??{}).length>0,refresh:async()=>{let n=await this.getUserTutorialState();return n.ok&&(t=true),n}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(Hi,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.tutorial.getTutorialDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Hi,i.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",i.data)),i}getUserTutorialState(e=true,t){return this.ctx.cache.read(Vu,()=>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 n=await this.ctx.api.tutorial.getUserTutorialState(t);return n.ok&&this.applyUserTutorialState(n.data),n}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.reportStepShown(n))}async completeStep(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.completeStep(n),{relatedEntityID:`tutorial_step_${e}_${t}_${a()}`})}async completeStepsBatch(e,t){let n=e?.trim();if(!n)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 i={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepIDs:t,RelatedEntityID:`tutorial_batch_${n}_${a()}`},s=await this.ctx.api.tutorial.completeStepsBatch(i);return s.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",s.data)),s}async skipStep(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.skipStep(n))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${a()}`},i=await this.ctx.api.tutorial.claimFlowReward(n);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",i.data)),i}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,n){let i=e?.trim();if(!i)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i},r=await t(s);return r.ok&&(this.applyFlowView(r.data),this.ctx.emitter.emit(n.event,r.data)),r}async stepCall(e,t,n,i){let s=e?.trim(),r=t?.trim();if(!s)return b("client","FlowID is required.");if(!r)return b("client","StepID is required.");if(!this.ctx.auth.context)return c;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:s,StepID:r};i?.relatedEntityID&&(p.RelatedEntityID=i.relatedEntityID);let m=this.ctx.data.user.state?.Tutorial?.Flows?.[s]?.RewardClaimed===true,R=await n(p);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(s,r,m,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,n,i){return !n&&i.Flow?.RewardClaimed===true?true:i.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Hi)?.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 Ji=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 n=await this.ctx.api.communityMarketing.getEarnings(t);return n.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",n.data),n}async claim(e){if(!e)return b("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.CampaignID=e;let n=await this.ctx.api.communityMarketing.claim(t);return n.ok&&this.ctx.emitter.emit("communityMarketing:claimed",n.data),n}async withdrawCryptoReward(e,t,n){if(!e)return b("client","campaignID is required.");if(!t)return b("client","walletAddress is required.");let i=this.ctx.authedRequest();if(!i)return c;i.CampaignID=e,i.WalletAddress=t,n&&(i.Amount=n);let s=await this.ctx.api.communityMarketing.withdrawCryptoReward(i);return s.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",s.data),s}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Ge=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 hR={Global:"Global",Announcement:"Announcement",Group:"Group"},Fu=z.enum(["Global","Announcement","Group"]).catch("Global"),dR={None:"None",Language:"Language",Region:"Region"},mR=z.enum(["None","Language","Region"]).catch("None"),fR={Anyone:"Anyone",Friends:"Friends"},gR=z.enum(["Anyone","Friends"]).catch("Anyone"),yR={Reject:"Reject",Mask:"Mask"},RR=z.enum(["Reject","Mask"]).catch("Reject"),CR={Player:"Player",Publisher:"Publisher",System:"System"},SR=z.enum(["Player","Publisher","System"]).catch("Player"),xR={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var bR=z.object({DisplayNameKey:z.string().nullish(),SortOrder:z.number().nullish(),IconPath:z.string().nullish(),JoinedByDefault:z.boolean().nullish()}).passthrough(),Wu=z.object({Gate:te.nullish(),Schedule:Ce.nullish()}).passthrough(),Ku=z.object({Gate:te.nullish(),Limits:Pe.nullish(),MaxLength:z.number().nullish()}).passthrough(),Qu=z.object({HotTailSize:z.number().nullish(),HistoryHours:z.number().nullish()}).passthrough(),DR=z.object({Availability:J.nullish(),Write:J.nullish(),Retention:J.nullish()}).passthrough(),IR=z.object({ChannelID:z.string().nullish(),Identity:bR.nullish(),Type:Fu.nullish(),GroupSource:z.string().nullish(),Partitioning:mR.nullish(),Capacity:z.number().nullish(),Availability:Wu.nullish(),Write:Ku.nullish(),Retention:Qu.nullish(),Presets:DR.nullish()}).passthrough(),PR=z.object({IsEnabled:z.boolean().nullish(),Gate:te.nullish(),WhoCanMessage:gR.nullish(),Limits:Pe.nullish(),MaxLength:z.number().nullish(),HistoryHours:z.number().nullish(),MaxConversations:z.number().nullish()}).passthrough(),vR=z.object({BlockedTerms:z.array(z.string()).nullish(),BlockedTermAction:RR.nullish(),MaxIgnoreListSize:z.number().nullish(),ReportsEnabled:z.boolean().nullish(),ReportLimits:Pe.nullish()}).passthrough(),AR=z.object({MinIntervalSeconds:z.number().nullish(),MaxMessagesPerPoll:z.number().nullish(),MaxHistoryPageSize:z.number().nullish()}).passthrough(),TR=z.object({Availability:z.record(z.string(),Wu).nullish(),Write:z.record(z.string(),Ku).nullish(),Retention:z.record(z.string(),Qu).nullish()}).passthrough(),Hu=z.object({IsEnabled:z.boolean().nullish(),Channels:z.record(z.string(),IR).nullish(),Direct:PR.nullish(),Moderation:vR.nullish(),Polling:AR.nullish(),Presets:TR.nullish()}).passthrough(),wR=z.object({LastReadAt:z.string().nullish(),LastReadMessageID:z.string().nullish(),Left:z.boolean().nullish()}).passthrough(),ju=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(),wR).nullish(),Limits:z.record(z.string(),ju).nullish(),ReportLimits:ju.nullish()}).passthrough();var Zo=z.object({RoomID:z.string().nullish(),SentAt:z.string().nullish(),MessageID:z.string().nullish()}).passthrough(),Zi=z.object({RoomID:z.string().nullish(),ChannelID:z.string().nullish(),MessageID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderProfile:Ge.nullish(),AuthorType:SR.nullish(),Text:z.string().nullish(),SentAt:z.string().nullish(),SystemKey:z.string().nullish(),SystemParams:z.record(z.string(),z.string()).nullish()}).passthrough(),zR=z.object({ChannelID:z.string().nullish(),RoomID:z.string().nullish(),DisplayNameKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),Type:Fu.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(),Yi=z.object({Channels:z.array(zR).nullish(),PollIntervalSeconds:z.number().nullish(),MutedUntil:z.string().nullish(),MuteReason:z.string().nullish()}).passthrough(),kR=z.object({RoomID:z.string().nullish(),Messages:z.array(Zi).nullish(),NextCursor:Zo.nullish(),UnreadCount:z.number().nullish(),ServedFromDatabase:z.boolean().nullish()}).passthrough(),$u=z.object({Rooms:z.array(kR).nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),Ju=z.object({RoomID:z.string().nullish(),Messages:z.array(Zi).nullish(),NextBefore:Zo.nullish()}).passthrough(),Zu=z.object({Message:Zi.nullish(),Moderated:z.boolean().nullish()}).passthrough(),Yu=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Ge.nullish(),MaxLength:z.number().nullish()}).passthrough(),MR=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Ge.nullish(),LastMessage:Zi.nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),Xu=z.object({Conversations:z.array(MR).nullish()}).passthrough(),An=z.object({Ignored:z.array(z.string()).nullish(),Cursor:Zo.nullish(),Joined:z.boolean().nullish()}).passthrough(),ec=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish()}).passthrough(),tt={GetChatDefinitions:"GetChatDefinitions",GetChannels:"GetChannels",Poll:"Poll",GetHistory:"GetHistory",GetConversations:"GetConversations",SendMessage:"SendMessage",OpenDirectChannel:"OpenDirectChannel",MarkRead:"MarkRead",JoinChannel:"JoinChannel",LeaveChannel:"LeaveChannel",ReportMessage:"ReportMessage",IgnoreUser:"IgnoreUser",UnignoreUser:"UnignoreUser"};var tc="Chat",nc={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Xi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(nc,{schema:Yi,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(tc,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.chat.getChatDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(tc,i.data),this.ctx.emitter.emit("chat:definitionsLoaded",i.data)),i}getChannels(e,t){return this.ctx.cache.read(nc,()=>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 n=await this.ctx.api.chat.getChannels(t);return n.ok&&this.ctx.emitter.emit("chat:channelsLoaded",n.data),n}async poll(e){let t=this.ctx.authedRequest();if(!t)return c;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let n=await this.ctx.api.chat.poll(t);if(!n.ok)return n;for(let i of n.data.Rooms??[])i.NextCursor&&i.RoomID&&this.cursors.set(i.RoomID,i.NextCursor),i.Messages&&i.Messages.length>0&&this.ctx.emitter.emit("chat:messages",i);return n}async getHistory(e,t,n){let i=this.ctx.authedRequest();return i?(i.RoomID=e,t&&(i.Before=t),n&&(i.Limit=n),this.ctx.api.chat.getHistory(i)):c}async sendMessage(e,t,n){let i=this.ctx.authedRequest();if(!i)return c;i.ChannelID=e,i.Text=t,n&&(i.Locale=n);let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async sendDirect(e,t){let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.Text=t;let i=await this.ctx.api.chat.sendMessage(n);return i.ok&&this.ctx.emitter.emit("chat:sent",i.data),i}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):c}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):c}async markRead(e,t){let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let i=await this.ctx.api.chat.markRead(n);return i.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),i}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):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,n,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,s.MessageID=t,s.Reason=n,i&&(s.Comment=i),this.ctx.api.chat.reportMessage(s)):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 OR={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},ER=z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),qR={Player:"player",Title:"title",Creator:"creator"},Tn={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},ic=z.object({Configured:z.boolean().nullish(),PublicKey:z.string().nullish()}).passthrough(),UR=z.object({TitleID:z.string().nullish(),Topic:z.string().nullish()}).passthrough(),Yo=z.object({EndpointHash:z.string().nullish(),Transport:ER.nullish(),Locale:z.string().nullish(),Topics:z.array(UR).nullish()}).passthrough(),sc=z.object({Configured:z.boolean().nullish(),Subscriptions:z.array(Yo).nullish()}).passthrough(),nt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var LR="IDOS_PLATFORM_PUSH_REQUEST",BR="IDOS_PLATFORM_PUSH_RESPONSE",GR=12e4;function rc(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(n=>{let i=false,s=m=>{i||(i=true,window.removeEventListener("message",r),clearTimeout(p),n(m));},r=m=>{let R=m?.data;!R||R.type!==BR||R.requestId!==t||z$1.includes(m.origin)&&s(R.ok===true);},p=setTimeout(()=>s(false),GR);window.addEventListener("message",r);for(let m of z$1)try{e.postMessage({type:LR,requestId:t,titleID:o},m);}catch{}})}var NR="idos:push:deviceToken:",es=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let n=await this.ctx.api.push.getPushConfig(t),i=n.ok?n.data:{Configured:false,PublicKey:null};return this.cachedConfig=i,n.ok&&this.ctx.emitter.emit("push:configLoaded",i),i}async getState(){let e=await this.getConfig();if(this.ctx.host.supports.pushNotifications){if(!e.Configured)return nt.Unsupported;let s=await this.ctx.host.requestPushToken({prompt:false});return s.error==="BLOCKED"?nt.Blocked:s.token?this.ctx.host.storage.getString(this.deviceTokenKey())===s.token?nt.Subscribed:nt.Idle:s.error==="NOT_GRANTED"?nt.Idle:nt.Unsupported}if(!e.Configured||!e.PublicKey)return nt.Unsupported;if(this.isEmbedded())return nt.Embedded;if(!this.isSupported())return nt.Unsupported;let t=Notification.permission;return t==="denied"?nt.Blocked:t!=="granted"?nt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?nt.Subscribed:nt.Idle}async subscribe(e={}){let t=await this.getConfig();if(this.ctx.host.supports.pushNotifications)return this.subscribeDevice(t,e);if(!t.Configured||!t.PublicKey)return b("client","Push notifications are not available for this title.");if(this.isEmbedded())return await rc(this.ctx.settings.titleID)?a$1({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 n=await Notification.requestPermission();if(n!=="granted")return b("client",n==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let i=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let r=await i.pushManager.getSubscription()??await i.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:_R(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return c;let m=r.toJSON();p.PushEndpoint=m.endpoint,p.PushP256dh=m.keys?.p256dh,p.PushAuth=m.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(p);return R.ok?(this.ctx.emitter.emit("push:subscribed",R.data),a$1({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return c;if(this.ctx.host.supports.pushNotifications){let n=this.ctx.host.storage.getString(this.deviceTokenKey());if(!n)return b("client","This device has no push subscription to remove.");e.PushDeviceToken=n;let i=await this.ctx.api.push.unsubscribePush(e);return i.ok&&(this.ctx.host.storage.remove(this.deviceTokenKey()),this.ctx.emitter.emit("push:unsubscribed",void 0)),i}if(this.isSupported()){let i=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();i&&(e.PushEndpoint=i.endpoint,await i.unsubscribe());}if(!e.PushEndpoint)return 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 n=await this.ctx.api.push.unsubscribePush(t);return n.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),n}async subscribeDevice(e,t){if(!e.Configured)return b("client","Push notifications are not available for this title.");let n=await this.ctx.host.requestPushToken({prompt:true});if(!n.token)return b("client",n.error==="BLOCKED"?"The player blocked notifications for this app.":"The device gave no push token.");let i=this.ctx.authedRequest();if(!i)return c;i.PushTransport=n.transport??"Fcm",i.PushDeviceToken=n.token,i.PushLocale=t.locale??(this.ctx.host.getLanguage()||void 0),i.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let s=await this.ctx.api.push.subscribePush(i);return s.ok?(this.ctx.host.storage.setString(this.deviceTokenKey(),n.token),this.ctx.emitter.emit("push:subscribed",s.data),a$1({Where:"game",Subscription:s.data})):s}deviceTokenKey(){return NR+this.ctx.settings.titleID}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function _R(o){let e=o.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(o.length/4)*4,"="),t=atob(e),n=new ArrayBuffer(t.length),i=new Uint8Array(n);for(let s=0;s<t.length;s++)i[s]=t.charCodeAt(s);return n}var ts=Object.freeze({}),ns=class{constructor(e){this.ctx=e;}ctx;table={...ts};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new vn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,n])=>({Locale:n?.Locale??t,DisplayName:n?.DisplayName??null,Order:n?.Order??0})).sort((t,n)=>(t.Order??0)-(n.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let n=this.resolveKey(e,t),i=this.lookup(n)??this.lookup(e);return i===void 0?this.onMissing(e):t?VR(i,t):i}applyState(e,t){if(!e){this.reset();return}let n=e.Locale??null;this.table=t.table??{...ts},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return c;let n=await this.loadTableFromApi(e);if(!n.ok)return n;let{locale:i,table:s,fallbackLocale:r}=n.data,p=null;if(r){let m=await this.loadTableFromApi(r);m.ok&&(p=m.data.table);}return this.table=s,this.fallbackTable=p,this.currentFallbackLocale=r,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:r,entryCount:Object.keys(s).length}),{ok:true,data:i}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):c}reset(){this.table={...ts},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:a()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return c;t.Locale=e;let n=await this.cache.read(oc(e));n&&(t.KnownVersion=n.v);let i=await this.ctx.api.localization.getLocalizationTable(t);if(!i.ok)return i;let s=i.data,r=s.Locale??oc(e),p=s.Version??0;if(s.NotModified){let R=n??await this.cache.read(r);return {ok:true,data:{locale:r,table:R?.t??{...ts},fallbackLocale:s.FallbackLocale??null}}}let m=s.Entries??{};return p>0&&await this.cache.write(r,p,m),{ok:true,data:{locale:r,table:m,fallbackLocale:s.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let n=t?.count;if(typeof n!="number")return e;let i=this.pluralCategory(n),s=`${e}.${i}`;if(this.lookup(s)!==void 0)return s;let 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 VR(o,e){return o.replace(/\{(\w+)\}/g,(t,n)=>{let i=e[n];return i===void 0?t:String(i)})}function oc(o){return o.trim().replace(/_/g,"-").toLowerCase()}var Xo="Quest",jR={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:o=>{let e=Date.now(),t=null,n=[...Object.values(o.PointsTracks??{}).map(i=>i?.CycleEndUtc),...Object.values(o.State?.Cycles??{}).map(i=>i?.CycleEndUtc)];for(let i of n){let s=Date.parse(i??"");!Number.isNaN(s)&&s>e&&(t===null||s<t)&&(t=s);}return t}},is=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:n=>{let i=e.cache.configSection(Xo)?.Cycles;if(!i)return false;let s=e.data.user.state?.Quest?.Cycles??{};for(let r of Object.keys(i)){let p=Date.parse(s[r]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=n&&t<p)return true}return false},refresh:async()=>{let n=await this.getUserQuestState(true,{forceRefresh:true});return n.ok&&(t=Date.now()),n}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(Xo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.quest.getQuestDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Xo,i.data),this.ctx.emitter.emit("quest:definitionsLoaded",i.data)),i}getUserQuestState(e=true,t){return this.ctx.cache.read(jR,()=>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 n=await this.ctx.api.quest.getUserQuestState(t);if(n.ok){let i=n.data.State??{};this.ctx.data.user.applyQuest(i),this.ctx.data.user.patchQuestPointsTracks(n.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",i);}return n}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return 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 n=e.trim();if(!n)return b("client","QuestID is required.");if(!this.ctx.auth.context)return c;let i=t&&t.trim().length>0?t.trim():void 0,s={...this.ctx.buildAuthedBaseRequest(),QuestID:n,CycleID:i,RelatedEntityID:`quest_claim_${i??""}_${n}_${a()}`},r=await this.ctx.api.quest.claimQuestReward(s);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;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},n=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(n.ok){let i=false;for(let s of n.data)!s.Success||!s.Data||(this.ctx.data.user.patchQuestStatus(s.Data.QuestID,s.Data.CycleID,"Claimed"),!i&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",n.data);}return n}async claimMilestoneReward(e,t){let n=e.trim(),i=t.trim();if(!n||!i)return b("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CycleID:n,MilestoneID:i,RelatedEntityID:`milestone_claim_${n}_${i}_${a()}`},r=await this.ctx.api.quest.claimMilestoneReward(s);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;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(n.ok){let i=false;for(let s of n.data)!s.Success||!s.Data||(this.ctx.data.user.patchMilestoneClaimed(s.Data.CycleID,s.Data.MilestoneID),!i&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",n.data);}return n}async claimGroupCompletionReward(e,t){let n=e.trim(),i=t.trim();if(!n||!i)return b("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CycleID:n,GroupCompletionID:i,RelatedEntityID:`group_completion_${n}_${i}_${a()}`},r=await this.ctx.api.quest.claimGroupCompletionReward(s);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 n=e.trim();if(!n)return b("client","MetricID is required.");if(t<0)return b("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),MetricID:n,ProgressValue:t},s=await this.ctx.api.quest.addQuestProgress(i);return s.ok&&(this.ctx.data.user.patchQuestProgressUpdates(s.data.Updates),this.ctx.emitter.emit("quest:progressAdded",s.data)),s}};var ac=z.object({}).passthrough().transform(o=>o);var FR=z.object({Order:z.number().nullish(),Type:z.string().nullish(),DurationSec:z.number().nullish(),BonusMultiplier:z.number().nullish()}).passthrough(),WR=z.object({Schedule:z.array(FR).nullish(),RepeatCycle:z.boolean().nullish(),MaxCycles:z.number().nullish()}).passthrough(),KR=z.object({IsActive:z.boolean().nullish(),CurrentPhaseEndUtc:u.nullish(),NextBonusStartUtc:u.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentPhaseIndex:z.number().nullish(),ActiveBonusMultiplier:z.number().nullish()}).passthrough(),QR=z.object({Milestones:J.nullish()}).passthrough(),ea=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Category:z.string().nullish(),Token:Tt.nullish(),TokenSources:z.array(dt).nullish(),ClaimMode:z.string().nullish(),Milestones:z.record(z.string(),je).nullish(),Presets:QR.nullish(),BonusWindow:WR.nullish()}).passthrough(),HR=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Content:ea.nullish(),ClaimGraceHours:z.number().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),$R=z.object({TimedEventID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:Ce.nullish(),Content:ea.nullish(),Events:z.array(HR).nullish(),Gate:te.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),JR=z.object({MaxConcurrentEvents:z.number().nullish()}).passthrough(),ZR=z.object({Milestones:z.record(z.string(),Sn).nullish()}).passthrough(),ss=z.object({Definitions:z.record(z.string(),$R).nullish(),Settings:JR.nullish(),Presets:ZR.nullish()}).passthrough(),YR=z.object({Type:q,TimedEventID:z.string(),CurrentChainedEventID:z.string().nullish(),Content:ea.nullish(),Progress:ac.nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),NextMilestone:je.nullish(),BonusWindow:KR.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentEventOrder:z.number().nullish(),TotalEventsInChain:z.number().nullish(),TokenEntityID:z.string().nullish()}).passthrough(),rs=z.object({ActiveEvents:z.array(YR).nullish()}).passthrough(),lc=z.object({Tokens:z.record(z.string(),ac).nullish()}),ta=z.object({Type:q.nullish(),LteID:z.string().nullish(),Resources:O.nullish()}),na=z.object({Type:q.nullish(),LteID:z.string().nullish(),MilestoneID:z.string().nullish(),TokenEntityID:z.string().nullish(),Rewards:O.nullish(),Inventory:Q.nullish()}),XR=z.object({Type:q.nullish(),LteID:z.string().nullish(),Resources:O.nullish()}),ia=z.array(Me(na)),uc=z.array(Me(ta)),cc=z.array(Me(XR)),gt={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var pc="TimedEvent",hc={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 n=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},os=class{constructor(e){this.ctx=e;e.cache.bindLoginView(hc,{schema:rs,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(hc,()=>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(pc,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.timedEvent.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(pc,i.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",i.data)),i}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,n,i,s,r,p=1){if(!t)return b("client","LteID is required.");if(!n)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c;let m={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:n,Outcome:i,AmountOverride:s,SourceParams:r,RollMultiplier:p},R=await this.ctx.api.timedEvent.grantTokens(m);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,n){if(!t)return b("client","LteID is required.");if(n<=0)return b("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:n},s=await this.ctx.api.timedEvent.spendTokens(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",s.data)),s}async claimMilestone(e,t,n){if(!t||!n)return b("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:n},s=await this.ctx.api.timedEvent.claimMilestone(i);if(s.ok){let r=s.data;this.ctx.data.user.applyResourcesWithDelta(r.Rewards,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,n,r.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",r);}return s}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},n=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return n.ok&&(this.applyMilestoneClaimBatch(n.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",n.data)),n}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return c;e&&e.length>0&&(t.Events=e);let n=await this.ctx.api.timedEvent.claimAllMilestones(t);return n.ok&&(this.applyMilestoneClaimBatch(n.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",n.data)),n}async spendTokensBatch(e){if(!e||e.length===0)return b("client","spends is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},n=await this.ctx.api.timedEvent.spendTokensBatch(t);if(n.ok){let i=false;for(let s of n.data)!i&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(s.Data.Resources,this.ctx.data.config.itemDefinitions),i=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",n.data);}return n}async grantTokensBatch(e){if(!e||e.length===0)return b("client","grants is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},n=await this.ctx.api.timedEvent.grantTokensBatch(t);if(n.ok){let i=false;for(let s of n.data)!i&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(s.Data.Resources,this.ctx.data.config.itemDefinitions),i=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",n.data);}return n}applyMilestoneClaimBatch(e){let t=false;for(let n of e){if(!n.Success||!n.Data)continue;let i=n.Data;i.Type&&i.LteID&&i.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(i.Type,i.LteID,i.MilestoneID,i.TokenEntityID),!t&&i.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(i.Rewards,i.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var eC=z.object({UserID:z.string(),Score:H.nullish(),Rank:z.number().nullish(),LastScoreUpdateUtc:u.nullish(),IpHash:z.string().nullish(),PublicProfile:Ge.nullish(),SeasonTierAtCycleEnd:z.number().nullish()}).passthrough(),jn=z.object({LeaderboardID:z.string(),CycleVersion:z.number().nullish(),TotalParticipants:H.nullish(),CycleEndUtc:u.nullish(),TopUsers:z.array(eC).nullish(),BracketID:z.string().nullish()}),tC=z.object({CycleKey:z.string().nullish(),CycleEndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),MilestoneTokensEarned:H.nullish(),ClaimableMilestoneIDs:z.array(z.string()).nullish(),CycleIndex:z.number().nullish(),ChainedEventID:z.string().nullish()}).passthrough(),as=z.object({LeaderboardID:z.string(),CurrentScore:H.nullish(),LastKnownRank:z.number().nullish(),HasUnclaimedReward:z.boolean().nullish(),UnclaimedRewardRank:z.number().nullish(),ScoreEarnedThisCycle:H.nullish(),MilestoneTokensEarned:H.nullish(),TokenEntityID:z.string().nullish(),NextMilestone:je.nullish(),HasUnclaimedMilestone:z.boolean().nullish(),GrantedPremiumTiers:z.record(z.string(),z.array(z.string())).nullish(),ClaimableGraceCycles:z.array(tC).nullish()}),ls=z.object({LeaderboardID:z.string(),NewScore:H,CycleVersion:z.number()}),us=z.object({ServerTimeUtc:u,LeaderboardID:z.string(),Rank:z.number().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),cs=z.object({ServerTimeUtc:u,LeaderboardID:z.string(),MilestoneID:z.string(),Resources:O.nullish(),Inventory:Q.nullish()}),dc=z.array(Me(jn)),ps=z.array(Me(as)),mc=z.array(Me(us)),fc=z.array(Me(cs)),gc=z.array(Me(ls)),nC=z.object({LeaderboardID:z.string(),CycleReward:Me(us).nullish(),Milestones:z.array(Me(cs)).nullish()}),yc=z.array(nC),iC=z.object({LeaderboardID:z.string(),Leaderboard:Me(jn).nullish(),Progress:Me(as).nullish()}),Rc=z.array(iC),sC=z.string(),Cc=z.object({Rank:z.string().nullish(),Rewards:$.nullish(),SeasonTierRewards:qo.nullish()}).passthrough(),rC=z.object({RankRewards:z.array(Cc).nullish()}).passthrough(),oC=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),aC=z.object({Milestones:J.nullish(),RankRewards:J.nullish()}).passthrough(),lC=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:sC.nullish(),Schedule:Ce.nullish(),ChainEvents:z.array(oC).nullish(),Gate:te.nullish(),TopUsersLimit:z.number().nullish(),MinScoreToEnterTop:z.number().nullish(),BracketSize:z.number().nullish(),LinkedSeasonChainID:z.string().nullish(),RankRewards:z.array(Cc).nullish(),Milestones:z.record(z.string(),je).nullish(),Presets:aC.nullish(),MilestoneClaimMode:z.string().nullish(),MilestoneClaimGraceHours:z.number().nullish(),ScoreSources:z.array(dt).nullish()}).passthrough(),uC=z.object({Milestones:z.record(z.string(),Sn).nullish(),RankRewards:z.record(z.string(),rC).nullish()}).passthrough(),hs=z.object({Definitions:z.record(z.string(),lC).nullish(),Presets:uC.nullish()}).passthrough(),Ze={GetDefinitions:"GetDefinitions",GetLeaderboard:"GetLeaderboard",GetMyProgress:"GetMyProgress",SubmitScore:"SubmitScore",SubmitScoreFromSource:"SubmitScoreFromSource",ClaimCycleReward:"ClaimCycleReward",ClaimMilestone:"ClaimMilestone",GetFriendsLeaderboard:"GetFriendsLeaderboard",GetLeaderboardsBatch:"GetLeaderboardsBatch",GetProgressBatch:"GetProgressBatch",ClaimCycleRewardsBatch:"ClaimCycleRewardsBatch",ClaimMilestonesBatch:"ClaimMilestonesBatch",SubmitScoresBatch:"SubmitScoresBatch",ClaimAllRewardsBatch:"ClaimAllRewardsBatch",GetOverviewBatch:"GetOverviewBatch"};var Sc="Leaderboard",xc={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"]},ds=class{constructor(e){this.ctx=e;e.cache.bindLoginView(xc,{schema:ps,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Sc,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.leaderboard.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Sc,i.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",i.data)),i}async getLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getLeaderboard(t);return n.ok&&this.ctx.emitter.emit("leaderboard:loaded",n.data),n}async getMyProgress(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getMyProgress(t);return n.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),n.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",n.data)),n}async submitScore(e,t){if(!e)return b("client","LeaderboardID is required.");if(t<=0)return b("client","Score must be positive.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},i=await this.ctx.api.leaderboard.submitScore(n);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),s.NewScore,t,s.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",s);}return i}async submitScoreFromSource(e,t,n,i,s=1){if(!e)return b("client","LeaderboardID is required.");if(!t)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:n,Params:i,RollMultiplier:s},p=await this.ctx.api.leaderboard.submitScoreFromSource(r);if(p.ok){let m=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),m.NewScore,m.NewScore,m.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",m);}return p}async claimCycleReward(e){if(!e)return b("client","LeaderboardID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},n=await this.ctx.api.leaderboard.claimCycleReward(t);if(n.ok){let i=n.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",i);}return n}async claimMilestone(e,t,n){if(!e||!t)return b("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...n?{CycleKey:n}:{}},s=await this.ctx.api.leaderboard.claimMilestone(i);if(s.ok){let r=s.data;n||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 s}async getFriendsLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return n.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",n.data),n}async getLeaderboardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return n.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",n.data),n}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(b("client","leaderboardIDs is required.")):this.ctx.cache.read(xc,()=>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 n=await this.ctx.api.leaderboard.getProgressBatch(t);return n.ok&&this.applyProgressBatch(n.data),n}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},n=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(n.ok){for(let i of n.data)!i.Success||!i.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(i.Data.LeaderboardID)),i.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",n.data);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(n.ok){for(let i of n.data)!i.Success||!i.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(i.Data.LeaderboardID),i.Data.MilestoneID),i.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",n.data);}return n}async submitScoresBatch(e){if(!e||e.length===0)return b("client","scores is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},n=await this.ctx.api.leaderboard.submitScoresBatch(t);if(n.ok){for(let i of n.data)!i.Success||!i.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(i.Data.LeaderboardID),i.Data.NewScore,i.Data.NewScore,i.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",n.data);}return n}async claimAllRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},n=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(n.ok){for(let i of n.data){let s=this.cycleDocID(i.LeaderboardID);i.CycleReward?.Success&&i.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(s),i.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.CycleReward.Data.Resources,i.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let r of i.Milestones??[])!r.Success||!r.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(s,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",n.data);}return n}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 n=await this.ctx.api.leaderboard.getOverviewBatch(t);if(n.ok){for(let i of n.data)i.Progress?.Success&&i.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(i.LeaderboardID),i.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",n.data);}return n}};var sa=z.object({}).passthrough().transform(o=>o),ms=z.object({SeasonChainID:z.string(),CycleIndex:z.number().nullish(),Season:z.lazy(()=>Pc).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:H.nullish(),UserState:sa.nullish(),NextTier:z.lazy(()=>Ic).nullish()}).passthrough(),bc=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),AmountGranted:H.nullish(),NewStatusTokens:H.nullish(),OldTier:z.number().nullish(),NewTier:z.number(),TierUp:z.boolean().nullish()}),ra=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),TierNumber:z.number(),Resources:O.nullish(),Inventory:Q.nullish()}),Dc=wt(ra);var Ic=z.object({Tier:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredTokens:H.nullish(),TierReachedReward:$.nullish()}).passthrough(),Pc=z.object({SeasonID:z.string().nullish(),Order:z.number().nullish(),DurationSec:H.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(Ic).nullish(),LinkedCollectionID:z.string().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough();var cC=z.object({SeasonChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:Ce.nullish(),Seasons:z.array(Pc).nullish(),GrantTokensAccessMode:z.string().nullish(),Gate:te.nullish()}).passthrough(),fs=z.object({Chains:z.record(z.string(),cC).nullish()}).passthrough(),Ht={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var vc="Season",Ac={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}},gs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ac,{schema:ms,apply:(t,n)=>this.applyActiveSeason(n??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(vc,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.season.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(vc,i.data),this.ctx.emitter.emit("season:definitionsLoaded",i.data)),i}getActiveSeason(e,t){return e?this.ctx.cache.read(Ac,()=>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 n=await this.ctx.api.season.getActiveSeason(t);return n.ok&&this.applyActiveSeason(e,n.data),n}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return b("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.SeasonChainID=e;let n=await this.ctx.api.season.getUserState(t);return n.ok&&(this.ctx.data.user.patchSeasonState(e,n.data),this.ctx.emitter.emit("season:userStateLoaded",n.data)),n}async grantStatusTokens(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","Amount must be positive.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${a()}`},i=await this.ctx.api.season.grantStatusTokens(n);return i.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,i.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",i.data)),i}async claimTierReward(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","TierNumber must be positive.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${a()}`},i=await this.ctx.api.season.claimTierReward(n);if(i.ok){let s=i.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",s);}return i}async claimTierRewardsBatch(e,t){if(!e)return b("client","SeasonChainID is required.");let n=(t??[]).filter(r=>r>0);if(n.length===0)return b("client","TierNumbers is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:n,RelatedEntityID:`season_tier_batch_${e}_${a()}`},s=await this.ctx.api.season.claimTierRewardsBatch(i);if(s.ok){let r=s.data;for(let p of r.Items??[]){let m=p.Data?.TierNumber;p.Success&&typeof m=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,m);}this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",r);}return s}};var Tc="Premium",ys=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Tc,e);if(t){let s={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",s),a$1(s)}let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.premium.getDefinitions(n);return i.ok&&i.data.Premium&&(this.ctx.data.config.patchSection(Tc,i.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",i.data)),i}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 n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},i=await this.ctx.api.premium.activateTrial(n);return i.ok&&(i.data.Premium&&this.ctx.data.user.applyPremium(i.data.Premium),this.ctx.emitter.emit("premium:trialActivated",i.data)),i}async purchaseItemOrCurrency(e,t,n="Default",i=1,s){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:n,Count:i,CreditsConfirmationID:s,RelatedEntityID:`premium_purchase_${e}_${t}`},p=await this.ctx.api.premium.purchaseItemOrCurrency(r);if(p.ok&&!p.data.CreditsConfirmation){let m=p.data;m.Premium&&this.ctx.data.user.applyPremium(m.Premium),this.ctx.data.user.applyResourceOperation(m.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",m);}return p}async purchaseRealMoney(e,t,n,i,s,r,p,m){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!i||!s)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:n,ProductID:i,ReceiptData:s,PurchaseToken:r,PackageName:p,AppStoreEnvironment:m,RelatedEntityID:`premium_iap_${e}_${t}`},W=await this.ctx.api.premium.purchaseRealMoney(R);if(W.ok){let fe=W.data;fe.Premium&&this.ctx.data.user.applyPremium(fe.Premium),this.ctx.data.user.applyResourceOperation(fe.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",fe);}return W}};var Rs=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ItemInstanceID:z.string().nullish(),Level:z.number().nullish(),EquippedAt:u.nullish()}),Fn=z.object({CharacterID:z.string(),Level:z.number().nullish(),Experience:H.nullish(),Power:z.number().nullish(),StatLevels:z.record(z.string(),z.number()).nullish(),Equipment:z.record(z.string(),Rs).nullish(),UpdatedAt:u.nullish()}).passthrough(),wc=z.object({Characters:z.record(z.string(),Fn).nullish(),SelectedCharacterID:z.string().nullish()}),oa=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:z.string(),StatID:z.string(),StatLevel:z.number(),Power:z.number().nullish(),Resources:O.nullish()}),aa=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:z.string(),NewLevel:z.number(),Power:z.number().nullish(),Resources:O.nullish()}),zc=z.object({ServerTimeUtc:u,CharacterID:z.string(),Equipment:z.record(z.string(),Rs).nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),kc=z.object({ServerTimeUtc:u,CharacterID:z.string(),ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),pC=z.object({ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish()}),Mc=z.object({ServerTimeUtc:u,Characters:z.record(z.string(),pC).nullish(),Inventory:Q.nullish()}),la=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:z.string(),Power:z.number().nullish(),Resources:O.nullish()}),Oc=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,CharacterID:z.string(),SkinID:z.string(),Resources:O.nullish(),Inventory:Q.nullish(),Equipped:z.boolean().nullish(),EquipError:z.string().nullish(),Equipment:Rs.nullish(),Power:z.number().nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish()}),Ec=z.object({ServerTimeUtc:u,CharacterID:z.string(),SkinID:z.string(),Equipped:Rs.nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),qc=z.object({ServerTimeUtc:u,CharacterID:z.string(),Cleared:z.boolean().nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),hC=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:u.nullish(),GateOpen:z.boolean().nullish(),Purchasable:z.boolean().nullish(),PriceOptions:de.nullish()}),dC=z.object({CharacterID:z.string(),CharacterOpen:z.boolean().nullish(),DefaultSkinID:z.string().nullish(),WornSkinID:z.string().nullish(),Skins:z.array(hC).nullish()}),Uc=z.object({ServerTimeUtc:u,Characters:z.record(z.string(),dC).nullish()}),Lc=z.object({ServerTimeUtc:u,SelectedCharacterID:z.string().nullish()}),Bc=wt(la),Gc=wt(aa),Nc=wt(oa),ua=z.object({RequiredStatID:z.string(),RequiredLevel:z.number()}).passthrough(),_c=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:de.nullish(),CostCurve:Je.nullish(),BaseStatValue:z.number().nullish(),ValueCurve:Je.nullish(),RankCurve:Je.nullish(),Requirements:z.array(ua).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),mC=z.object({SlotID:z.string(),MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(ua).nullish(),AllowedRarityIDs:z.array(z.string()).nullish(),AllowedItemTags:z.array(z.string()).nullish(),MinItemLevel:z.number().nullish(),MaxItemLevel:z.number().nullish()}).passthrough(),Vc=z.object({Slots:z.record(z.string(),mC).nullish()}).passthrough(),jc=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(),fC=z.object({ClassID:z.string().nullish(),RarityID:z.string().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),gC=z.object({UnlockedByDefault:z.boolean().nullish(),PriceOptions:de.nullish()}).passthrough(),yC=z.object({Stats:J.nullish(),Levels:J.nullish(),Equipment:J.nullish()}).passthrough(),Fc=z.object({MaxRank:z.number().nullish(),FirstPaidRank:z.number().nullish(),PriceOptions:de.nullish(),CostCurve:Je.nullish()}).passthrough(),ca="@skin";function RC(o){return !!o&&o.startsWith("@")}var CC=z.object({CatalogID:z.string().nullish(),ItemID:z.string()}).passthrough(),SC=z.object({PriceOptions:de.nullish(),Schedule:Ce.nullish(),Gate:te.nullish()}).passthrough(),xC=z.object({MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(ua).nullish()}).passthrough(),bC=z.object({SkinID:z.string().nullish(),Identity:jc.nullish(),Item:CC.nullish(),Sale:SC.nullish(),Requirements:xC.nullish()}).passthrough(),DC=z.object({DefaultSkinID:z.string().nullish(),Definitions:z.record(z.string(),bC).nullish()}).passthrough(),IC=z.object({CharacterID:z.string(),Identity:jc.nullish(),Classification:fC.nullish(),Unlock:gC.nullish(),Presets:yC.nullish(),Equipment:Vc.nullish(),Stats:z.record(z.string(),_c).nullish(),RankLadder:Fc.nullish(),RankStatCurve:Je.nullish(),StatMaxLevelCurve:Je.nullish(),Skins:DC.nullish()}).passthrough(),PC=z.object({Stats:z.record(z.string(),_c).nullish()}).passthrough(),vC=z.object({RankLadder:Fc.nullish()}).passthrough(),AC=z.object({Equipment:Vc.nullish()}).passthrough(),TC=z.object({Stats:z.record(z.string(),PC).nullish(),Levels:z.record(z.string(),vC).nullish(),Equipment:z.record(z.string(),AC).nullish()}).passthrough(),Cs=z.object({Definitions:z.record(z.string(),IC).nullish(),Presets:TC.nullish()}).passthrough(),$e={GetCharacterDefinitions:"GetCharacterDefinitions",GetUserCharacters:"GetUserCharacters",UnlockCharacter:"UnlockCharacter",UpgradeStatLevel:"UpgradeStatLevel",UpgradeCharacterLevel:"UpgradeCharacterLevel",EquipItems:"EquipItems",UnequipItems:"UnequipItems",UnequipAllCharacters:"UnequipAllCharacters",UnlockCharactersBatch:"UnlockCharactersBatch",UpgradeCharacterLevelsBatch:"UpgradeCharacterLevelsBatch",UpgradeStatLevelsBatch:"UpgradeStatLevelsBatch",UnlockSkin:"UnlockSkin",EquipSkin:"EquipSkin",UnequipSkin:"UnequipSkin",GetCharacterSkins:"GetCharacterSkins",SelectCharacter:"SelectCharacter"},wC="SKIN_ALREADY_OWNED";var pa="Character",Ss=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(pa)?.Definitions,n=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([i,s])=>s?.Unlock?.UnlockedByDefault===true&&!n[s.CharacterID??i])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(pa,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.character.getCharacterDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(pa,i.data),this.ctx.emitter.emit("character:definitionsLoaded",i.data)),i}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let n=t.data.Characters??{};this.ctx.data.user.applyCharacter(n),this.ctx.data.user.applySelectedCharacter(t.data.SelectedCharacterID),this.ctx.emitter.emit("character:userCharactersLoaded",n);}return t}async unlockCharacter(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${a()}`},i=await this.ctx.api.character.unlockCharacter(n);if(i.ok&&!i.data.CreditsConfirmation){let s=i.data;this.ctx.data.user.patchCharacter(s.CharacterID,r=>{r.Level??=1,r.StatLevels??={},r.Equipment??={},s.Power!=null&&(r.Power=s.Power),r.UpdatedAt=s.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(s.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",s);}return i}async upgradeStatLevel(e,t,n){if(!e||!t)return b("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${a()}`,SelectedOptionID:n?.selectedOptionID,CreditsConfirmationID:n?.creditsConfirmationID,...n?.levels!=null?{Levels:n.levels}:{},...n?.targetLevel!=null?{TargetLevel:n.targetLevel}:{}},s=await this.ctx.api.character.upgradeStatLevel(i);if(s.ok&&!s.data.CreditsConfirmation){let r=s.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 s}async upgradeCharacterLevel(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${a()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},i=await this.ctx.api.character.upgradeCharacterLevel(n);if(i.ok&&!i.data.CreditsConfirmation){let s=i.data;this.ctx.data.user.patchCharacter(s.CharacterID,r=>{r.Level=s.NewLevel,s.Power!=null&&(r.Power=s.Power),r.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(r.StatLevels??={},r.Equipment??={});}),this.ctx.data.user.applyResourceOperation(s.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",s);}return i}async equipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},i=await this.ctx.api.character.equipItems(n);return i.ok&&(this.applyEquipChangesLocally(e,i.data),this.ctx.emitter.emit("character:itemsEquipped",i.data)),i}async unequipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},i=await this.ctx.api.character.unequipItems(n);if(i.ok){let s=i.data;this.applyUnequipChangesLocally(e,s),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:s.ClearedSlotIDs??[],power:s.Power??null});}return i}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return 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,n){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,AutoEquip:n?.autoEquip??false,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${a()}`},s=await this.ctx.api.character.unlockSkin(i);if(s.ok&&!s.data.CreditsConfirmation){let r=s.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 s}async equipSkin(e,t,n){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:n},s=await this.ctx.api.character.equipSkin(i);if(s.ok){let r=s.data;this.applyInventoryDelta(r.Inventory),this.applySkinLocally(r.CharacterID,r.Equipped??null,r.Power,r.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",r);}return s}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},n=await this.ctx.api.character.unequipSkin(t);if(n.ok){let i=n.data;i.Cleared&&(this.applyInventoryDelta(i.Inventory),this.applySkinLocally(i.CharacterID,null,i.Power,i.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",i);}return n}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):c}async selectCharacter(e){let t=this.ctx.authedRequest();if(!t)return c;let n=e?.trim();if(!n)return b("client","CharacterID is required.");t.CharacterID=n;let i=await this.ctx.api.character.selectCharacter(t);return i.ok&&(this.ctx.data.user.applySelectedCharacter(i.data.SelectedCharacterID),this.ctx.emitter.emit("character:selected",i.data)),i}applySkinLocally(e,t,n,i){let s=this.ctx.data.user;s.patchCharacterEquipment(e,ca,t??null),s.patchCharacter(e,r=>{n!=null&&(r.Power=n),r.UpdatedAt=i;});}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},n=await this.ctx.api.character.unlockCharactersBatch(t);return n.ok&&(this.applyBatchResults(n.data,i=>{this.ctx.data.user.patchCharacter(i.CharacterID,s=>{s.Level??=1,s.StatLevels??={},s.Equipment??={},i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=i.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",n.data)),n}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},n=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return n.ok&&(this.applyBatchResults(n.data,i=>{this.ctx.data.user.patchCharacter(i.CharacterID,s=>{s.Level=i.NewLevel,i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=i.ServerTimeUtc,i.NewLevel===1&&(s.StatLevels??={},s.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",n.data)),n}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},n=await this.ctx.api.character.upgradeStatLevelsBatch(t);return n.ok&&(this.applyBatchResults(n.data,i=>{this.ctx.data.user.patchCharacter(i.CharacterID,s=>{s.StatLevels??={},s.StatLevels[i.StatID]=i.StatLevel,i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=i.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",n.data)),n}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let n of e.Items??[])!n.Success||!n.Data||t(n.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[i,s]of Object.entries(t.Equipment??{}))n.patchCharacterEquipment(e,i,s);n.patchCharacter(e,i=>{t.Power!=null&&(i.Power=t.Power),i.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let n=t.ClearedSlotIDs??[];if(n.length===0&&t.Power==null)return;let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let s of n)i.patchCharacterEquipment(e,s,null);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[n,i]of Object.entries(e.Characters??{})){for(let s of i.ClearedSlotIDs??[])t.patchCharacterEquipment(n,s,null);t.patchCharacter(n,s=>{i.Power!=null&&(s.Power=i.Power),s.UpdatedAt=e.ServerTimeUtc;});}}};var Wc="Match",xs=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,n,i,s,r){let p=this.ctx.auth.context;if(!p)return c;let m={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:n,BattleStrategy:i,TargetUserID:s,SelectedOptionID:r,RelatedEntityID:`pvp_create_${p.userID}_${a()}`},R=await this.ctx.api.match.createMatch(m);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 n={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},i=await this.ctx.api.match.updateMatch(n);return i.ok&&this.ctx.emitter.emit("match:updated",i.data),i}async cancelMatch(e){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},n=await this.ctx.api.match.cancelMatch(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",n.data)),n}async instantBattle(e,t,n,i){let s=this.ctx.auth.context;if(!s)return c;let r={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:n,BattleStrategy:i,RelatedEntityID:`pvp_battle_${e}_${a()}`},p=await this.ctx.api.match.instantBattle(r);if(p.ok){let m=p.data,R=this.ctx.data.config.itemDefinitions;if(m.Resources)this.ctx.data.user.applyResourceOperation(m.Resources,R);else if(m.ResourcesDual){let W=m.ResourcesDual;W.FromUserID===s.userID&&W.FromResult?this.ctx.data.user.applyResourceOperation(W.FromResult,R):W.ToUserID===s.userID&&W.ToResult&&this.ctx.data.user.applyResourceOperation(W.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",m);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},n=await this.ctx.api.match.saveStrategy(t);return n.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),n}async getMyMatches(e=0,t=20,n){let i=this.ctx.authedRequest();if(!i)return c;i.Page=e,i.PageSize=t,i.Statuses=n;let s=await this.ctx.api.match.getMyMatches(i);return s.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",s.data),s}async getAvailableMatches(e=0,t=20,n=false){let i=this.ctx.authedRequest();if(!i)return c;i.Page=e,i.PageSize=t,i.OnlyPublic=n;let s=await this.ctx.api.match.getAvailableMatches(i);return s.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",s.data),s}async getDefinitions(e){let t=this.ctx.cache.configSection(Wc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.match.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Wc,i.data),this.ctx.emitter.emit("match:definitionsLoaded",i.data)),i}};var zC="Challenge",bs=class{constructor(e){this.ctx=e;}ctx;lastState=null;get definitions(){return this.ctx.cache.configSection(zC)??null}get state(){return this.lastState}chainDefinition(e){return this.definitions?.Chains?.[e]??null}phaseDefinition(e,t){return t?this.chainDefinition(e)?.Challenges?.find(n=>n?.ChallengeID===t)??null:null}chainView(e){return this.lastState?.Chains?.find(t=>t.ChainID===e)??null}newAttemptID(){return a().replace(/-/g,"")}async getState(e){let t=this.ctx.authedRequest();if(!t)return c;e&&(t.ChainID=e);let n=await this.ctx.api.challenge.getState(t);return n.ok&&this.applyState(n.data,e),n}async refreshOpponents(e){if(!e)return b("client","ChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.ChainID=e;let n=await this.ctx.api.challenge.refreshOpponents(t);return n.ok&&this.applyState(n.data,e),n}async attempt(e,t,n,i,s){if(!e)return b("client","ChainID is required.");if(!n)return b("client","AttemptID is required.");let r=this.ctx.authedRequest();if(!r)return c;r.ChainID=e,r.AttemptID=n,"tierID"in t?r.TierID=t.tierID:r.RevengeID=t.revengeID,i&&(r.CharacterID=i),s&&(r.BattleStrategy=s);let p=await this.ctx.api.challenge.attempt(r);if(p.ok){let m=p.data;m.IsReplay||this.ctx.data.user.applyResourcesWithDelta(m.Rewards,m.Inventory,this.ctx.data.config.itemDefinitions),this.patchAfterAttempt(e,m,"revengeID"in t?t.revengeID:void 0),this.ctx.emitter.emit("challenge:attemptCompleted",m);}return p}async claimMilestone(e,t,n){if(!e||!t)return b("client","ChainID and MilestoneID are required.");let i=this.ctx.authedRequest();if(!i)return c;i.ChainID=e,i.MilestoneID=t,n&&(i.InstanceKey=n);let s=await this.ctx.api.challenge.claimMilestone(i);if(s.ok){let r=s.data;this.ctx.data.user.applyResourcesWithDelta(r.Rewards,r.Inventory,this.ctx.data.config.itemDefinitions),this.markClaimed(e,r.InstanceKey??n,t),this.ctx.emitter.emit("challenge:milestoneClaimed",r);}return s}async claimReachedMilestones(e){if(!this.ctx.auth.context)return c;let t=[],n=(this.lastState?.Chains??[]).filter(i=>!e||i.ChainID===e);for(let i of n){if(!i.ChainID)continue;let s=[i.Active,...i.Ended??[]].filter(r=>!!r&&!!r.CanClaim);for(let r of s)for(let p of this.reachedUnclaimed(i.ChainID,r)){let m=await this.claimMilestone(i.ChainID,p,r.InstanceKey??void 0);m.ok&&t.push(m.data);}}return a$1(t)}reachedUnclaimed(e,t){let n=this.phaseDefinition(e,t.ChallengeID),i=t.PointsEarned??0,s=new Set(t.ClaimedMilestoneIDs??[]);return Object.entries(n?.Milestones??{}).filter(([r,p])=>!s.has(r)&&(p?.RequiredProgress??1/0)<=i).sort((r,p)=>(r[1]?.RequiredProgress??0)-(p[1]?.RequiredProgress??0)).map(([r])=>r)}applyState(e,t){if((e.Rewards||e.Inventory)&&this.ctx.data.user.applyResourcesWithDelta(e.Rewards,e.Inventory,this.ctx.data.config.itemDefinitions),t&&this.lastState){let n=(this.lastState.Chains??[]).filter(i=>i.ChainID!==t);this.lastState={...e,Chains:[...n,...e.Chains??[]]};}else this.lastState=e;this.ctx.emitter.emit("challenge:stateLoaded",e);}patchAfterAttempt(e,t,n){let i=this.chainView(e);if(!i)return;t.Tickets!=null&&(i.Tickets=t.Tickets);let s=i.Active;if(!s||s.InstanceKey!==t.InstanceKey)return;t.PointsEarned!=null&&(s.PointsEarned=t.PointsEarned),t.IsReplay||(s.AttemptsToday=(s.AttemptsToday??0)+1);let r=t.Attempt;if(!(!r?.Win||!s.Arena))if(r.IsRevenge)s.Arena.Revenges=(s.Arena.Revenges??[]).filter(p=>p.RevengeID!==n);else for(let p of s.Arena.Opponents??[])p.TierID===r.TierID&&p.OpponentID===r.OpponentID&&(p.Defeated=true);}markClaimed(e,t,n){let i=this.chainView(e);if(i)for(let s of [i.Active,...i.Ended??[]])s&&(t&&s.InstanceKey!==t||!t&&s!==i.Active||(s.ClaimedMilestoneIDs=[...new Set([...s.ClaimedMilestoneIDs??[],n])]));}};var Kc="Craft",Ds=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Kc,e);if(t){let s={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),a$1(s)}let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.craft.getDefinitions(n);return i.ok&&i.data.CraftDefinitions&&(this.ctx.data.config.patchSection(Kc,i.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",i.data.CraftDefinitions)),i}async craft(e,t,n=1,i,s,r){if(!e)return b("client","CraftID is required.");let p=this.ctx.auth.context;if(!p)return c;let m={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:n,SelectedOptionID:i,InputInstanceIDs:s,CreditsConfirmationID:r,RelatedEntityID:`craft_${e}_${p.userID}_${a()}`},R=await this.ctx.api.craft.craft(m);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 $t=z.lazy(()=>z.union([z.string(),z.number(),z.boolean(),z.null(),z.array($t),z.record(z.string(),$t)]));var Jt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Qc=z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),ln={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Wn(o){return o!==ln.Pending&&o!==ln.Running}var kC={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 MC(o){return o?/\b(AI_[A-Z_]+)\s*:/.exec(o)?.[1]??null:null}var OC=z.object({Url:z.string().nullish(),ContentType:z.string().nullish(),Variant:z.string().nullish()}),EC=z.object({Code:z.string().nullish(),Message:z.string().nullish()}),Is=z.object({CreditsConfirmation:ye.nullish(),GenerationID:z.string(),FeatureKey:z.string().nullish(),Modality:Qc.nullish(),Status:z.string(),Progress:z.number().nullish(),OutputText:z.string().nullish(),OutputJson:z.record(z.string(),$t).nullish(),Assets:z.array(OC).nullish(),Error:EC.nullish(),Charge:O.nullish(),PlayerRefunded:z.boolean().nullish(),Reused:z.boolean().nullish(),Reward:O.nullish(),Context:z.record(z.string(),$t).nullish(),PaymentSettled:z.boolean().nullish(),CreditsPrice:z.number().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish()}),Hc=z.object({Data:z.array(Is).nullish(),Skip:z.number().nullish(),Limit:z.number().nullish()}),qC=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(),It=z.record(z.string(),z.string()),UC=z.object({Key:z.string().nullish(),Role:z.string().nullish(),Required:z.boolean().nullish(),Label:It.nullish()}).passthrough(),LC=z.object({Name:z.string().nullish(),Type:z.string().nullish(),Required:z.boolean().nullish(),MaxLength:z.number().nullish(),Default:z.string().nullish(),Multiline:z.boolean().nullish(),Label:It.nullish(),Placeholder:It.nullish(),Choices:z.array(z.object({Value:z.string().nullish(),Label:It.nullish()}).passthrough()).nullish()}).passthrough(),$c=z.object({Key:z.string(),Kind:z.string().nullish(),Name:It.nullish(),Hint:It.nullish(),Unit:It.nullish(),Choices:z.array(z.object({Value:z.string(),Name:It.nullish(),Group:z.string().nullish()}).passthrough()).nullish(),Groups:z.array(z.object({Key:z.string(),Name:It.nullish()}).passthrough()).nullish(),Default:z.string().nullish(),Min:z.number().nullish(),Max:z.number().nullish(),Step:z.number().nullish()}).passthrough(),Jc=z.object({PriceOptions:de.nullish()}).passthrough(),BC=z.object({Id:z.string().nullish(),Kind:z.string().nullish(),Action:z.string().nullish(),IsTrend:z.boolean().nullish(),Category:z.string().nullish(),Order:z.number().nullish(),Name:It.nullish(),Description:It.nullish(),Preview:z.object({Url:z.string().nullish(),PosterUrl:z.string().nullish(),Type:z.string().nullish()}).passthrough().nullish(),Inputs:z.array(UC).nullish(),Variables:z.array(LC).nullish(),Settings:z.array($c).nullish()}).passthrough(),GC=z.object({Modality:Qc.nullish(),Async:z.boolean().nullish(),Limits:Pe.nullish(),PriceOptions:de.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:$.nullish(),PromptVariables:z.array(qC).nullish(),AllowFreePrompt:z.boolean().nullish(),PlatformTemplateId:z.string().nullish(),PlatformTemplate:BC.nullish(),Settings:z.array($c).nullish(),FreePerDay:z.number().nullish(),FreeLeftToday:z.number().nullish()}).passthrough(),Zc=z.object({Enabled:z.boolean().nullish(),Features:z.record(z.string(),GC).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",GenerateFromTemplate:"GenerateFromTemplate",EstimateTemplatePrice:"EstimateTemplatePrice"};var Yc="AI",NC=/^[A-Za-z0-9_-]{1,128}$/,_C=2e3,VC=5e3,jC=30*6e4;function FC(o,e){return new Promise(t=>{if(e?.aborted){t();return}let n=()=>{clearTimeout(i),e?.removeEventListener("abort",n),t();},i=setTimeout(n,o);e?.addEventListener("abort",n,{once:true});})}var Ps=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(Yc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.ai.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Yc,i.data),this.ctx.emitter.emit("ai:definitionsLoaded",i.data)),i}generateText(e,t,n){return this.generate(e,{Text:t},n,i=>this.ctx.api.ai.generateText(i))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,n){return this.generate(e,{Image:t},n,i=>this.ctx.api.ai.generateImage(i))}editImage(e,t,n){return this.generate(e,{ImageEdit:t},n,i=>this.ctx.api.ai.editImage(i))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,n){return this.generate(e,{Video:t},n,i=>this.ctx.api.ai.generateVideo(i))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,n){return this.generate(e,{Audio:t},n,i=>this.ctx.api.ai.generateAudio(i))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,n){return this.generate(e,{Music:t},n,i=>this.ctx.api.ai.generateMusic(i))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,n){return this.generate(e,{TemplateInputs:t},n,i=>this.ctx.api.ai.generateFromTemplate(i))}async estimateTemplatePrice(e,t,n){return e?this.ctx.auth.context?this.ctx.api.ai.estimateTemplatePrice({...this.ctx.buildAuthedBaseRequest(),FeatureKey:e,Params:t,Variables:n}):c:b("client","FeatureKey is required.")}generateThreeD(e,t,n){return this.generate(e,{ThreeD:t},n,i=>this.ctx.api.ai.generateThreeD(i))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):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 Wn(e)}async waitForGeneration(e,t={}){let n;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;n=p.data;}else {if(!e?.GenerationID)return b("client","GenerationID is required.");n=e;}let i=Date.now()+(t.timeoutMs??jC),s=Math.max(1,t.intervalMs??_C),r=Math.max(s,t.maxIntervalMs??VC);for(;!Wn(n.Status);){if(t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");if(Date.now()+s>i)return b("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await FC(s,t.signal),t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(n);if(s=Math.min(r,Math.round(s*1.5)),!p.ok){if(p.reason==="connection")continue;return p}n=p.data,Wn(n.Status)||t.onUpdate?.(n);}return a$1(n)}pollFor(e){switch(e.Modality){case Jt.Text:return this.getText(e.GenerationID);case Jt.Image:return this.getImage(e.GenerationID);case Jt.Audio:return this.getAudio(e.GenerationID);case Jt.Music:return this.getMusic(e.GenerationID);case Jt.Video:return this.getVideo(e.GenerationID);case Jt.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,n,i){if(!e)return b("client","FeatureKey is required.");let s=n?.relatedEntityID;if(s!==void 0&&!NC.test(s))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 r={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,Variables:n?.variables,Params:n?.params,Context:n?.context,RelatedEntityID:s??a()},p=await i(r);return p.ok&&!p.data.CreditsConfirmation&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return b("client","GenerationID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.GenerationID=e;let i=await t(n);return i.ok&&(await this.reconcileCharge(i.data,false),this.emitView(i.data)),i}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===ln.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===ln.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===ln.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var ha="Collection",vs=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let n=e.cache.configSection(ha),i=Object.keys(n?.Collections??{});if(i.length===0||t)return false;let s=e.cache.configSection("Season");return Object.values(s?.Chains??{}).some(p=>(p?.Seasons??[]).some(m=>!!m?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==i[0]},refresh:async()=>{let n=await this.getUserState();return n.ok&&(t=true),n}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ha,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.collection.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(ha,i.data),this.ctx.emitter.emit("collection:definitionsLoaded",i.data)),i}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,n=1,i){let s=this.ctx.auth.context;if(!s)return c;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:n,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${s.userID}_${a()}`},p=await this.ctx.api.collection.openPack(r);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,n=1){let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:n,RelatedEntityID:`open_chest_${e}_${t}_${i.userID}_${a()}`},r=await this.ctx.api.collection.openCollectionChest(s);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",r.data)),r}async useCollectibleJoker(e,t){let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${n.userID}_${a()}`},s=await this.ctx.api.collection.useCollectibleJoker(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",s.data)),s}async claimSetReward(e,t){let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${n.userID}_${a()}`},s=await this.ctx.api.collection.claimSetReward(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",s.data)),s}async claimSetRewardsBatch(e){if(!e||e.length===0)return b("client","sets is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},n=await this.ctx.api.collection.claimSetRewardsBatch(t);if(n.ok){let i=false;for(let s of n.data)!i&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),i=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",n.data);}return n}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return c;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${a()}`},i=await this.ctx.api.collection.claimGrandPrize(n);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",i.data)),i}async sendTradeOffer(e,t,n,i,s,r=false){let p=this.ctx.auth.context;if(!p)return c;let m={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:n,ReceiverUserID:i,RequestedCollectibleID:s,RequestedCollectibleIsSpecial:r,RelatedEntityID:`trade_send_${p.userID}_${i}_${a()}`},R=await this.ctx.api.collection.sendTradeOffer(m);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}_${a()}`},n=await this.ctx.api.collection.cancelTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",n.data)),n}async acceptTradeOffer(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${a()}`},n=await this.ctx.api.collection.acceptTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",n.data)),n}async declineTradeOffer(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${a()}`},n=await this.ctx.api.collection.declineTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",n.data)),n}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return c;t.CollectionID=e;let n=await this.ctx.api.collection.getMyTradeOffers(t);return n.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",n.data),n}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return c;t.CollectionID=e;let n=await this.ctx.api.collection.getIncomingTradeOffers(t);return n.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",n.data),n}};var WC=z.object({}).passthrough().transform(o=>o),KC={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},QC={Active:"Active",Left:"Left",Replaced:"Replaced"},HC=z.object({ObjectIndex:z.number().nullish(),ObjectCompletionRewardClaimed:z.boolean().nullish()}).passthrough(),$C=z.object({UserID:z.string().nullish(),PublicData:Ge.nullish(),BuildObjectsProgress:HC.nullish(),IsBot:z.boolean().nullish(),SpinsCount:z.number().nullish(),TokensSpent:z.number().nullish(),MemberStatus:z.string().nullish(),GrandPrizeClaimed:z.boolean().nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),JC=z.object({Index:z.number().nullish(),OwnerUserID:z.string().nullish(),CurrentProgress:z.number().nullish(),MaxProgress:z.number().nullish(),IsCompleted:z.boolean().nullish()}).passthrough(),ZC=z.object({Objects:z.array(JC).nullish()}).passthrough(),Xc=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($C).nullish(),BuildObjectsState:ZC.nullish(),Status:z.string().nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:z.number().nullish()}).passthrough(),ep=z.object({CoopChainID:z.string(),CycleIndex:z.number().nullish(),EventOrder:z.number().nullish(),EventDef:z.lazy(()=>tp).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:z.number().nullish()}).passthrough(),YC=z.string(),da=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(),XC=z.object({Index:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxProgress:z.number().nullish(),CompletionReward:$.nullish()}).passthrough(),eS=z.object({Objects:z.array(XC).nullish(),PriceOptions:de.nullish(),SpinnerTable:z.array(da).nullish(),MaxSpinsPerCall:z.number().nullish()}).passthrough(),tp=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:YC.nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),BuildObjects:eS.nullish(),GrandPrize:$.nullish()}).passthrough(),tS=z.object({CoopChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:Ce.nullish(),Events:z.array(tp).nullish(),Gate:te.nullish()}).passthrough(),As=z.object({ServerTimeUtc:u.nullish(),UserState:WC.nullish(),ActiveGroup:Xc.nullish()}),ma=z.object({ServerTimeUtc:u.nullish(),Group:Xc.nullish(),SecondsRemaining:H.nullish()}),np=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),GroupID:z.string().nullish(),Resources:O.nullish(),ObjectIndex:z.number().nullish(),Sector:da.nullish(),RequestedSpins:z.number().nullish(),SpinsUsed:z.number().nullish(),Sectors:z.array(da).nullish(),ProgressDelta:z.number().nullish(),NewProgress:H.nullish(),MaxProgress:H.nullish(),ObjectCompleted:z.boolean().nullish(),AllObjectsCompleted:z.boolean().nullish()}),fa=z.object({ServerTimeUtc:u.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),ip=z.object({ServerTimeUtc:u.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),Ts=z.object({Chains:z.record(z.string(),tS).nullish()}).passthrough(),Pt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var sp="CoopEvent",rp={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(rp,{schema:As,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(sp,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.coopEvent.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(sp,i.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",i.data)),i}async getActiveEvent(e){if(!e)return b("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.CoopChainID=e;let n=await this.ctx.api.coopEvent.getActiveEvent(t);return n.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",n.data),n}getUserState(e){return this.ctx.cache.read(rp,()=>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 n=await this.ctx.api.coopEvent.getGroupState(t);return n.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",n.data),n}async joinOrCreateGroup(e){if(!e)return b("client","CoopChainID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},n=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(n.ok){let i=n.data.Group;i&&this.ctx.data.user.patchCoopEventActiveGroup(i.GroupID??null,i.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",n.data);}return n}async spin(e,t,n=1,i,s){if(!e||!t)return b("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:n,SelectedOptionID:i,CreditsConfirmationID:s,RelatedEntityID:a()},p=await this.ctx.api.coopEvent.spin(r);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(p.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",p.data)),p}async claimObjectReward(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.claimObjectReward(t);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",n.data)),n}async claimGrandPrize(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.claimGrandPrize(t);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",n.data)),n}async leaveGroup(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.leaveGroup(t);return n.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",n.data)),n}};var nS={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},iS={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},sS=z.object({NodeID:z.string().nullish(),Status:z.string().nullish(),ExecutionCount:z.number().nullish(),UnlockedAtUtc:u.nullish(),CompletedAtUtc:u.nullish(),LastExecutedAtUtc:u.nullish(),NextAvailableAtUtc:u.nullish(),LastExecutionRefID:z.string().nullish()}).passthrough(),rS=z.object({TrackID:z.string().nullish(),CurrentValue:z.number().nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),op=z.object({OfferID:z.string().nullish(),InstanceKey:z.string().nullish(),SourceOfferVersion:z.number().nullish(),Status:z.string().nullish(),ActivatedAtUtc:u.nullish(),ExhaustedAtUtc:u.nullish(),ExpiredAtUtc:u.nullish(),DismissedAtUtc:u.nullish(),ShowCount:z.number().nullish(),LastShownAtUtc:u.nullish(),Nodes:z.record(z.string(),sS).nullish(),Tracks:z.record(z.string(),rS).nullish(),SelectedChoiceNodeID:z.string().nullish()}).passthrough(),oS=z.object({SlotID:z.string().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),ActiveOfferID:z.string().nullish(),ActiveOfferStartedAtUtc:u.nullish(),ActiveOfferExpiresAtUtc:u.nullish(),ActiveOffer:op.nullish(),NextCycleStartsAtUtc:u.nullish(),LastUpdatedUtc:u.nullish(),DismissSkipAvailableAtUtc:u.nullish(),LastDismissedAtUtc:u.nullish(),ActiveScheduleInstanceKey:z.string().nullish()}).passthrough(),aS=z.object({TotalExecutions:z.number().nullish(),DailyExecutions:z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),lS=z.object({TotalActivations:z.number().nullish(),TotalExhausted:z.number().nullish(),TotalExpired:z.number().nullish(),TotalDismissed:z.number().nullish(),TotalShows:z.number().nullish(),LastShownAtUtc:u.nullish(),LastActivatedAtUtc:u.nullish(),LastExhaustedAtUtc:u.nullish(),NodeCounts:z.record(z.string(),aS).nullish()}).passthrough(),uS=z.object({Slots:z.record(z.string(),oS).nullish(),OfferHistory:z.record(z.string(),lS).nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),cS={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},pS={Eq:"Eq",Gte:"Gte",Lte:"Lte"},hS=z.object({Order:z.number().nullish(),OfferID:z.string().nullish(),DurationSec:z.number().nullish(),DelayBeforeActivationSec:z.number().nullish()}).passthrough(),zs=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(),ap=z.object({Schedule:Ce.nullish(),Gate:te.nullish()}).passthrough(),lp=z.object({AllowDismissSkip:z.boolean().nullish(),DismissSkipDelaySec:z.number().nullish()}).passthrough(),dS=z.object({Identity:J.nullish(),Availability:J.nullish(),Behaviour:J.nullish()}).passthrough(),mS=z.object({SlotID:z.string().nullish(),Enabled:z.boolean().nullish(),Identity:zs.nullish(),Availability:ap.nullish(),Behaviour:lp.nullish(),Queue:z.array(hS).nullish(),Presets:dS.nullish()}).passthrough(),fS=z.object({ViewsRequiredToComplete:z.number().nullish(),MaxViewsPerActivation:z.number().nullish(),GrantRewardsPerView:z.boolean().nullish()}).passthrough(),gS=z.object({RewardedVideo:fS.nullish()}).passthrough(),yS=z.object({TrackID:z.string().nullish(),Operator:z.string().nullish(),Value:z.number().nullish()}).passthrough(),RS=z.object({Identity:J.nullish(),Graph:J.nullish(),Milestones:J.nullish()}).passthrough(),CS=z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish()}).passthrough(),SS=z.object({TrackID:z.string().nullish(),Amount:z.number().nullish(),RespectBounds:z.boolean().nullish()}).passthrough(),xS=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(),bS=z.object({RequiredCompletedNodeIDs:z.array(z.string()).nullish(),RequiredAnyCompletedNodeIDs:z.array(z.string()).nullish(),RequiredTracks:z.array(yS).nullish(),VisibleWhileLocked:z.boolean().nullish()}).passthrough(),up=z.object({Options:de.nullish()}).passthrough(),cp=z.object({Grants:$.nullish(),TrackChanges:z.array(SS).nullish(),MilestonePoints:z.number().nullish()}).passthrough(),DS=z.object({NodeID:z.string().nullish(),Type:z.string().nullish(),Identity:zs.nullish(),Pricing:up.nullish(),Reward:cp.nullish(),Action:gS.nullish(),UnlockRules:bS.nullish(),NextNodeIDs:z.array(z.string()).nullish(),ChoiceGroupID:z.string().nullish(),Limits:Pe.nullish(),HideWhenCompleted:z.boolean().nullish(),ExhaustOfferOnComplete:z.boolean().nullish(),Presets:CS.nullish()}).passthrough(),pp=z.object({RootNodeIDs:z.array(z.string()).nullish(),Nodes:z.array(DS).nullish(),Tracks:z.array(xS).nullish(),ExhaustedWhenAllTerminalNodesCompleted:z.boolean().nullish()}).passthrough(),hp=z.object({Milestones:z.record(z.string(),je).nullish(),ClaimMode:z.string().nullish(),Token:Tt.nullish()}).passthrough(),dp=z.object({OfferID:z.string().nullish(),Version:z.number().nullish(),Enabled:z.boolean().nullish(),Identity:zs.nullish(),Graph:pp.nullish(),Milestones:hp.nullish(),Presets:RS.nullish()}).passthrough(),IS=z.object({Identity:z.record(z.string(),zs).nullish(),Availability:z.record(z.string(),ap).nullish(),Behaviour:z.record(z.string(),lp).nullish(),Graph:z.record(z.string(),pp).nullish(),Milestones:z.record(z.string(),hp).nullish(),Pricing:z.record(z.string(),up).nullish(),Reward:z.record(z.string(),cp).nullish()}).passthrough(),ga=z.object({Slots:z.record(z.string(),mS).nullish(),Offers:z.record(z.string(),dp).nullish(),Presets:IS.nullish()}).passthrough(),mp=z.object({DealOfferDefinitions:ga.nullish()}),fp=z.object({DealOffers:uS.nullish()}),PS=z.object({EntityID:z.string().nullish(),TotalEarned:z.number().nullish(),ClaimedIDs:z.array(z.string()).nullish(),ReachedUnclaimedIDs:z.array(z.string()).nullish()}).passthrough(),vS=z.object({SlotID:z.string().nullish(),SortOrder:z.number().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),OfferDef:dp.nullish(),ActivationState:op.nullish(),IsNewActivation:z.boolean().nullish(),ComputedExpiresAtUtc:u.nullish(),Cost:Ut.nullish(),Milestone:PS.nullish(),ScheduleInstanceKey:z.string().nullish()}).passthrough(),ks=z.object({Slots:z.array(vS).nullish()}),gp=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),SlotID:z.string().nullish(),NodeID:z.string().nullish(),NodeCompleted:z.boolean().nullish(),OfferExhausted:z.boolean().nullish(),Idempotent:z.boolean().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),yp=z.object({ServerTimeUtc:u.nullish(),SlotID:z.string().nullish(),Resources:O.nullish()}),Rp=z.object({ServerTimeUtc:u.nullish(),SlotID:z.string().nullish(),Resources:O.nullish()}),Cp=z.object({ServerTimeUtc:u.nullish(),SlotID:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),Sp=z.object({ServerTimeUtc:u.nullish(),SlotID:z.string().nullish(),ClaimedIDs:z.array(z.string()).nullish(),Rejected:z.record(z.string(),z.string()).nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),kt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var AS="DealOffer",xp={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},Ms=class{constructor(e){this.ctx=e;e.cache.bindLoginView(xp,{schema:ks,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(AS,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(xp,()=>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}_${a()}`},n=await this.ctx.api.dealOffer.dismissDeal(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",n.data)),n}async executeNode(e,t,n,i){if(!e||!t)return b("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return c;let s=n&&n.trim().length>0?n.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:s??`deal_exec_${e}_${t}_${a()}`},p=await this.ctx.api.dealOffer.executeNode(r);return p.ok&&!p.data.CreditsConfirmation&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${a()}`},n=await this.ctx.api.dealOffer.recordShow(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",n.data)),n}async claimMilestone(e,t){if(!e||!t)return b("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${a()}`},i=await this.ctx.api.dealOffer.claimMilestone(n);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",i.data)),i}async claimMilestonesBatch(e,t){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let n=[...new Set(t.map(r=>r.trim()).filter(r=>r.length>0))],i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:n,RelatedEntityID:`deal_milestone_batch_${e}_${a()}`},s=await this.ctx.api.dealOffer.claimMilestonesBatch(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",s.data)),s}};var bp="Referral",Os=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(bp,e);if(t){let s={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",s),a$1(s)}let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.referral.getDefinitions(n);return i.ok&&i.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(bp,i.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",i.data)),i}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=on.parseReferralCode(e)?.toUpperCase();if(!t)return b("client","ReferralCode is required.");let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${n.userID}`},s=await this.ctx.api.referral.activateReferralCode(i);if(s.ok){let r=s.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 s}async claimInviteReward(e){let t=e.trim();if(!t)return b("client","InviteRewardID is required.");let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${n.userID}`},s=await this.ctx.api.referral.claimInviteReward(i);if(s.ok){let r=s.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 s}async claimInviteRewardsBatch(e){let t=(e??[]).map(r=>r?.trim()).filter(Boolean);if(t.length===0)return b("client","InviteRewardIDs is required.");let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${n.userID}`},s=await this.ctx.api.referral.claimInviteRewardsBatch(i);if(s.ok){let r=s.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 s}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 Dp=z.object({ServerTimeUtc:u,SourceType:g,SourceID:z.string(),TargetType:g,TargetID:z.string(),SourceSpent:H,FeeAmount:H,RateApplied:ie,TargetCredited:H}),Ip=z.object({ServerTimeUtc:u,SourceType:g,SourceID:z.string(),TargetType:g,TargetID:z.string(),SourceSpent:ie,FeeAmount:ie,RateApplied:ie,TargetCredited:ie}),Pp=z.object({ServerTimeUtc:u,SpendID:z.string(),Resources:O.nullish()}),Kn={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},TS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},vp=z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),wS={Automatic:"Automatic",Manual:"Manual"},zS=z.enum(["Automatic","Manual"]).catch("Automatic"),kS=z.object({ValueInUSD:ie.nullish(),ValueInUSDUpdatedAt:u.nullish(),InitialDeposit:z.number().nullish(),MinBalance:z.number().nullish(),MaxBalance:z.number().nullish(),DailyEarnLimit:z.number().nullish(),DailySpendLimit:z.number().nullish()}).passthrough(),MS=z.object({Rate:z.number().nullish(),Max:z.number().nullish(),Period:z.number().nullish()}).passthrough(),OS=z.object({IsTradable:z.boolean().nullish(),IsPurchasable:z.boolean().nullish(),IsRefundable:z.boolean().nullish()}).passthrough(),ES=z.object({TargetCurrencyType:g.nullish(),TargetCurrencyID:z.string(),Rate:ie.nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish(),DailyLimit:z.number().nullish()}).passthrough(),Ap=z.object({Enabled:z.boolean().nullish(),RateMode:zS.nullish(),Fee:z.number().nullish(),Targets:z.array(ES).nullish()}).passthrough(),Tp=z.object({CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough(),qS=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Economy:kS.nullish(),Recharge:MS.nullish(),Conversion:Ap.nullish(),Permissions:OS.nullish(),Audit:Tp.nullish(),Status:vp.nullish()}).passthrough(),US=z.object({NetworkID:z.string(),ContractAddress:z.string().nullish(),Decimals:z.number().nullish(),MinWithdraw:ie.nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),LS=z.object({DailyWithdrawUsd:ie.nullish(),MonthlyWithdrawUsd:ie.nullish(),KycRequiredAboveUsd:ie.nullish()}).passthrough(),BS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),SpendableInGame:z.boolean().nullish(),ConvertibleToVirtual:z.boolean().nullish()}).passthrough(),GS=z.object({Mode:z.string().nullish(),FundingNetworkID:z.string().nullish(),PerPlayerDailyTokens:z.number().nullish(),TitleDailyTokens:z.number().nullish(),RefuseOverCap:z.boolean().nullish()}).passthrough(),ya=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),DisplayDecimals:z.number().nullish(),ValueInUSD:ie.nullish(),ValueInUSDUpdatedAt:u.nullish(),UsdPriceRefreshMinutes:z.number().nullish(),DeveloperWithdrawalFeePercent:ie.nullish(),CommunityMarketingWithdrawalFeePercent:ie.nullish(),WithdrawalBurnPercent:ie.nullish(),PlayerTradeFeePercent:ie.nullish(),TradeShareCommunityMarketingPercent:ie.nullish(),Networks:z.array(US).nullish(),Limits:LS.nullish(),Permissions:BS.nullish(),Conversion:Ap.nullish(),Audit:Tp.nullish(),Status:vp.nullish(),ServerGrantPolicy:GS.nullish(),UnbackedRewardCurrencyID:z.string().nullish()}).passthrough(),NS=z.object({SpendID:z.string().nullish(),DisplayName:z.string().nullish(),PriceOptions:z.record(z.string(),Li).nullish()}).passthrough(),Es=z.object({VirtualCurrencies:z.record(z.string(),qS).nullish(),CryptoCurrencies:z.record(z.string(),ya).nullish(),Spends:z.record(z.string(),NS).nullish()}).passthrough(),_S={Marketplace:"Marketplace",MailboxTransfer:"MailboxTransfer",Match:"Match",Workshop:"Workshop"},VS={Pending:"Pending",Released:"Released",Voided:"Voided"},yt=z.object({PayoutID:z.string().nullish(),Source:z.string().nullish(),SourceRefID:z.string().nullish(),Status:z.enum(["Pending","Released","Voided"]).catch("Pending").nullish(),Amount:pe.nullish(),CreatedAt:u.nullish(),ReleaseAt:u.nullish(),ReturnedGoods:pe.nullish(),GoodsReturned:z.boolean().nullish()}).passthrough(),wp=z.object({Pending:z.array(yt).nullish(),Released:z.array(yt).nullish(),Voided:z.array(yt).nullish()}).passthrough();var jS={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},zp=z.enum(["System","Reward","Gift","Social"]).catch("System"),FS={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},WS=z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),KS={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},QS=z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),ct={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},HS={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"},$S=100,JS=z.object({Subject:z.string().nullish(),Body:z.string().nullish()}).passthrough(),kp=z.object({FeatureID:z.string().nullish(),Args:z.record(z.string(),z.string()).nullish(),Url:z.string().nullish(),Label:z.string().nullish()}).passthrough(),ZS=z.object({Texts:z.record(z.string(),JS).nullish(),Category:zp.nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:kp.nullish(),SenderName:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),YS=z.object({Enabled:z.boolean().nullish(),Grant:pe.nullish(),Cost:pe.nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:u.nullish(),SenderGate:te.nullish(),TemplateID:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),XS=z.object({Type:z.string().nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxAmountPerGift:z.number().nullish()}).passthrough(),ex=z.object({Enabled:z.boolean().nullish(),AllowedResources:z.array(XS).nullish(),MaxEntriesPerGift:z.number().nullish(),AllowItemInstances:z.boolean().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:u.nullish(),FeePercent:z.number().nullish(),FeeCost:pe.nullish(),SenderGate:te.nullish(),ExpirationDays:z.number().nullish(),TemplateID:z.string().nullish()}).passthrough(),Mp=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(),ZS).nullish(),Gifts:z.object({Social:z.record(z.string(),YS).nullish(),Transfer:ex.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(),tx=z.object({MessageID:z.string(),Source:WS,Category:zp,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:kp.nullish(),SenderName:z.string().nullish(),SenderUserID:z.string().nullish(),SenderAvatarUrl:z.string().nullish(),SenderNote:z.string().nullish(),Rewards:$.nullish(),Instances:z.array(xn).nullish(),HasRewards:z.boolean().nullish(),IsTransfer:z.boolean().nullish(),SentAt:u,ExpiresAt:u.nullish(),ReadAt:u.nullish(),ClaimedAt:u.nullish()}).passthrough(),nx=z.object({MessageID:z.string(),Module:QS,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:$.nullish()}).passthrough(),Ra=z.object({ID:z.string(),Error:z.string().nullish()}).passthrough(),Op=z.object({ServerTimeUtc:u.nullish(),Messages:z.array(tx).default([]),NextCursor:z.string().nullish(),PendingRewards:z.array(nx).nullish(),UnreadCount:z.number().nullish(),UnclaimedCount:z.number().nullish(),DeliveredNow:z.number().nullish()}).passthrough(),qs=z.object({ServerTimeUtc:u.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Ca=z.object({ServerTimeUtc:u.nullish(),AffectedCount:z.number().default(0),Failed:z.array(Ra).default([]),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),ix=z.object({MessageID:z.string(),Rewards:pe.nullish(),Instances:z.array(xn).nullish(),HeldPayout:yt.nullish()}).passthrough(),Us=z.object({ServerTimeUtc:u.nullish(),Claimed:z.array(ix).default([]),Failed:z.array(Ra).default([]),Resources:O.nullish(),Inventory:Q.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Ep=z.object({ServerTimeUtc:u.nullish(),GiftID:z.string().nullish(),Sent:z.array(z.string()).default([]),Failed:z.array(Ra).default([]),Resources:O.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:u.nullish()}).passthrough(),qp=z.object({ServerTimeUtc:u.nullish(),MessageID:z.string().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish(),RecipientReceives:pe.nullish(),RecipientInstances:z.array(xn).nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:u.nullish(),IdempotentReplay:z.boolean().nullish()}).passthrough(),Up=z.object({ServerTimeUtc:u.nullish(),ResetsAt:u.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:u.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:u.nullish()}).passthrough().nullish()}).passthrough();var Sa="Mailbox",xa={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},Ls=class{constructor(e){this.ctx=e;e.cache.bindLoginView(xa,{schema:qs,apply:t=>this.emitCounters(t)});}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}emitCounters(e){if(e.UnreadCount==null||e.UnclaimedCount==null)return;let t={UnreadCount:e.UnreadCount,UnclaimedCount:e.UnclaimedCount};this.ctx.cache.put(xa,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Sa)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Sa,e);if(t)return a$1(t);let n=this.request();if(!n)return c;let i=await this.ctx.api.mailbox.getDefinitions(n);return i.ok&&this.ctx.data.config.patchSection(Sa,i.data),i}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return c;let n=await this.ctx.api.mailbox.getMessages(t);return n.ok&&(this.emitCounters(n.data),this.ctx.emitter.emit("mailbox:messagesLoaded",n.data)),n}getUnreadCount(e){return this.ctx.cache.read(xa,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return 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 n=await this.ctx.api.mailbox.readMessages(t);return n.ok&&this.emitCounters(n.data),n}async claimReward(e){let t=e?.trim();if(!t)return b("client","MessageID is required.");let n=this.request({MessageID:t});return n?this.afterClaim(await this.ctx.api.mailbox.claimReward(n)):c}async claimRewards(e){let t=(e??[]).map(i=>i?.trim()).filter(Boolean);if(t.length===0)return b("client","MessageIDs are required.");let n=this.request({MessageIDs:t});return n?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(n)):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 n=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!n)return c;let i=await this.ctx.api.mailbox.deleteMessages(n);return i.ok&&this.emitCounters(i.data),i}async sendGift(e,t){if(!e?.trim())return b("client","GiftID is required.");let n=(t??[]).filter(Boolean);if(n.length===0)return b("client","Recipients are required.");let i=this.request({GiftID:e.trim(),RecipientUserIDs:n});if(!i)return c;let s=await this.ctx.api.mailbox.sendGift(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",s.data)),s}async sendTransfer(e,t,n){if(!e?.trim())return b("client","RecipientUserID is required.");if(!n?.requestID?.trim())return b("client","requestID is required.");let i=this.request({RecipientUserID:e.trim(),TransferEntries:t,TransferInstanceIDs:n.instanceIDs?.length?n.instanceIDs:void 0,Note:n.note,RelatedEntityID:n.requestID.trim()});if(!i)return c;let s=await this.ctx.api.mailbox.sendTransfer(i);return s.ok&&(s.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(s.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",s.data)),s}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):c}};var sx={Head:"Head",Torso:"Torso",Legs:"Legs"},Bs=z.enum(["Head","Torso","Legs"]).catch("Head"),rx={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},ba=z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Bp=z.object({AttackTarget:Bs,DefenseTarget:Bs});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:Bs.nullish(),DefenseZone:Bs.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:u,ExpiresAt:u.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Lp=z.object({UserID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),SelectedCharacter:Fn.nullish(),BattleStrategy:z.array(Bp).nullish(),UnstackableItems:z.record(z.string(),ux).nullish(),Stats:lx.nullish()}).passthrough(),Qn=z.object({WinnerUserID:z.string().nullish(),LoserUserID:z.string().nullish(),Entry:pe.nullish(),NetReward:pe.nullish(),BattleLog:z.array(ax).nullish(),IsDraw:z.boolean().nullish(),P1BattleProfile:Lp.nullish(),P2BattleProfile:Lp.nullish()}).passthrough(),Gp=z.object({MatchID:z.string(),TitleID:z.string().nullish(),RuleID:z.string().nullish(),CreatedAt:u.nullish(),CreatorID:z.string().nullish(),CreatorCharacterID:z.string().nullish(),CreatorStrategy:z.array(Bp).nullish(),TargetUserID:z.string().nullish(),Entry:pe.nullish(),CreationCostPaid:pe.nullish(),RefundCreationCostOnCancel:z.boolean().nullish(),ExpiresAt:u.nullish(),JoinedByUserID:z.string().nullish(),JoinedByCharacterID:z.string().nullish(),JoinedAt:u.nullish(),Status:ba.nullish(),WinnerUserID:z.string().nullish(),CompletedAt:u.nullish(),IsRewardDistributed:z.boolean().nullish(),RewardDistributedAt:u.nullish()}).passthrough(),Np=z.object({Status:ba,MatchID:z.string(),Entry:pe.nullish(),Resources:O.nullish()}),_p=z.object({Match:Gp.nullish()}),Vp=z.object({MatchID:z.string(),Status:ba,Resources:O.nullish()}),jp=z.object({Battle:Qn.nullish(),Resources:O.nullish(),ResourcesDual:Lt.nullish(),HeldPayout:yt.nullish()}),Da=z.object({Matches:z.array(Gp).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}),Mt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var cx=z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var px=z.enum(["Constant","Variable","Curve"]).catch("Constant"),hx=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(),dx=z.enum(["Flat","PercentReduction"]).catch("Flat"),mx=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:dx.nullish(),MaxArmorReduction:z.number().nullish()}).passthrough(),fx=z.object({Kind:px.nullish(),Constant:z.number().nullish(),VariableID:z.string().nullish(),Argument:z.string().nullish(),Curve:Je.nullish(),OnePlus:z.boolean().nullish()}).passthrough(),gx=z.object({Coefficient:z.number().nullish(),Factors:z.array(fx).nullish()}).passthrough(),un=z.object({Terms:z.array(gx).nullish()}).passthrough(),yx=z.object({Health:un.nullish(),Damage:un.nullish(),Armor:un.nullish(),AttackSpeed:un.nullish(),CritChance:un.nullish(),CritDamage:un.nullish(),Dodge:un.nullish()}).passthrough(),Fp=z.object({StatMapping:hx.nullish(),Combat:mx.nullish(),Formula:yx.nullish()}).passthrough(),Rx=z.object({BurnRate:z.number().nullish()}).passthrough(),Hn=z.object({Kind:cx.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),TokenType:o.nullish(),EntityID:z.string().nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish()}).passthrough(),Wp=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Hn).nullish(),MaxPositions:z.number().nullish()}).passthrough(),Kp=z.object({PriceOptions:de.nullish(),RefundCostOnCancel:z.boolean().nullish(),MaxOpenMatches:z.number().nullish(),OfferLifetimeSeconds:z.number().nullish(),Limits:Pe.nullish(),AllowPrivateMatches:z.boolean().nullish(),MaxMatchesPerOpponentPerDay:z.number().nullish()}).passthrough(),Cx=z.object({RuleID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Economy:Rx.nullish(),Entry:Wp.nullish(),Creation:Kp.nullish(),Settings:Fp.nullish()}).passthrough(),Sx=z.object({Rules:z.record(z.string(),Cx).nullish(),Defaults:Fp.nullish(),EntryDefaults:Wp.nullish(),CreationDefaults:Kp.nullish()}).passthrough(),Ia=z.object({InstantBattle:Sx.nullish()}).passthrough(),Qp=Ia;var xx={Open:"Open",Request:"Request",InviteOnly:"InviteOnly"},bx=z.enum(["Open","Request","InviteOnly"]).catch("Open"),Dx={Application:"Application",Invite:"Invite"},Ix={Invite:"invite",ManageApplications:"manage_applications",Kick:"kick",SetRole:"set_role",EditInfo:"edit_info",EditAnnouncement:"edit_announcement",ModerateChat:"moderate_chat",CreateRequest:"create_request",SpendTreasury:"spend_treasury",ManageProjects:"manage_projects",StartActivity:"start_activity",SelectQuests:"select_quests"},Le={GetDefinitions:"GetDefinitions",GetMyClans:"GetMyClans",SearchClans:"SearchClans",GetRecommendedClans:"GetRecommendedClans",GetClan:"GetClan",GetClanMembers:"GetClanMembers",GetRankings:"GetRankings",CreateClan:"CreateClan",UpdateClan:"UpdateClan",DisbandClan:"DisbandClan",JoinClan:"JoinClan",ApplyToClan:"ApplyToClan",CancelApplication:"CancelApplication",GetApplications:"GetApplications",AcceptApplication:"AcceptApplication",RejectApplication:"RejectApplication",InvitePlayer:"InvitePlayer",GetMyInvites:"GetMyInvites",AcceptInvite:"AcceptInvite",DeclineInvite:"DeclineInvite",LeaveClan:"LeaveClan",KickMember:"KickMember",SetMemberRole:"SetMemberRole",TransferLeadership:"TransferLeadership",GetClanLog:"GetClanLog",CreateRequest:"CreateRequest",Donate:"Donate",Help:"Help",ClaimRequest:"ClaimRequest",GetRequests:"GetRequests",GetGifts:"GetGifts",ClaimGift:"ClaimGift",ClaimAllGifts:"ClaimAllGifts",GetRewards:"GetRewards",ClaimRewards:"ClaimRewards",GetTreasury:"GetTreasury",DepositToTreasury:"DepositToTreasury",BuyTreasuryPurchase:"BuyTreasuryPurchase",GetProjects:"GetProjects",ContributeToProject:"ContributeToProject",SetRecommendedProject:"SetRecommendedProject",GetActivities:"GetActivities",StartActivity:"StartActivity",SubmitActivityScore:"SubmitActivityScore",ClaimActivityRewards:"ClaimActivityRewards",GetClanQuests:"GetClanQuests",SelectClanQuests:"SelectClanQuests",TakeClanQuest:"TakeClanQuest",AbandonClanQuest:"AbandonClanQuest",ClaimClanQuestRewards:"ClaimClanQuestRewards",GetCompetitions:"GetCompetitions",RegisterForCompetition:"RegisterForCompetition",GetBracket:"GetBracket",ClaimCompetitionRewards:"ClaimCompetitionRewards",StartWarAttack:"StartWarAttack",GetDiplomacy:"GetDiplomacy",SetDiplomacy:"SetDiplomacy",GetRevenges:"GetRevenges",TakeRevenge:"TakeRevenge",GetLeague:"GetLeague",ClaimSeasonReward:"ClaimSeasonReward"},Px={Disabled:"CLAN_DISABLED",UnknownKind:"CLAN_UNKNOWN_KIND",KindRequired:"CLAN_KIND_REQUIRED",NotFound:"CLAN_NOT_FOUND",NotMember:"CLAN_NOT_MEMBER",AlreadyInClan:"CLAN_ALREADY_IN_CLAN",Full:"CLAN_FULL",NoPermission:"CLAN_NO_PERMISSION",RankTooLow:"CLAN_RANK_TOO_LOW",RoleFull:"CLAN_ROLE_FULL",UnknownRole:"CLAN_UNKNOWN_ROLE",NameTaken:"CLAN_NAME_TAKEN",TagTaken:"CLAN_TAG_TAKEN",NameInvalid:"CLAN_NAME_INVALID",TagInvalid:"CLAN_TAG_INVALID",TextInvalid:"CLAN_TEXT_INVALID",TextBlocked:"CLAN_TEXT_BLOCKED",GateFailed:"CLAN_GATE_FAILED",RequirementsNotMet:"CLAN_REQUIREMENTS_NOT_MET",JoinModeMismatch:"CLAN_JOIN_MODE_MISMATCH",JoinCooldown:"CLAN_JOIN_COOLDOWN",RejoinCooldown:"CLAN_REJOIN_COOLDOWN",TooManyApplications:"CLAN_TOO_MANY_APPLICATIONS",ApplicationNotFound:"CLAN_APPLICATION_NOT_FOUND",InviteNotFound:"CLAN_INVITE_NOT_FOUND",PlayerNotFound:"CLAN_PLAYER_NOT_FOUND",LeaderMustTransfer:"CLAN_LEADER_MUST_TRANSFER",CannotTargetSelf:"CLAN_CANNOT_TARGET_SELF",KickLimit:"CLAN_KICK_LIMIT",RenameCooldown:"CLAN_RENAME_COOLDOWN",InvalidArgument:"CLAN_INVALID_ARGUMENT",FeatureDisabled:"CLAN_FEATURE_DISABLED",RequestNotFound:"CLAN_REQUEST_NOT_FOUND",RequestClosed:"CLAN_REQUEST_CLOSED",RequestCooldown:"CLAN_REQUEST_COOLDOWN",RequestLimit:"CLAN_REQUEST_LIMIT",RequestFilled:"CLAN_REQUEST_FILLED",DonateLimit:"CLAN_DONATE_LIMIT",AlreadyHelped:"CLAN_ALREADY_HELPED",NothingToClaim:"CLAN_NOTHING_TO_CLAIM",GiftNotFound:"CLAN_GIFT_NOT_FOUND",TenureRequired:"CLAN_TENURE_REQUIRED",Conflict:"CLAN_CONFLICT",SystemCapReached:"CLAN_SYSTEM_CAP_REACHED",ItemNotAllowed:"CLAN_ITEM_NOT_ALLOWED",ItemLevelTooHigh:"CLAN_ITEM_LEVEL_TOO_HIGH",ItemEquipped:"CLAN_ITEM_EQUIPPED",ItemWrongLevel:"CLAN_ITEM_WRONG_LEVEL",NotEnoughTreasury:"CLAN_NOT_ENOUGH_TREASURY",DepositLimit:"CLAN_DEPOSIT_LIMIT",PurchaseNotFound:"CLAN_PURCHASE_NOT_FOUND",BuffActive:"CLAN_BUFF_ACTIVE",LevelTooLow:"CLAN_LEVEL_TOO_LOW",ProjectNotFound:"CLAN_PROJECT_NOT_FOUND",ProjectLocked:"CLAN_PROJECT_LOCKED",ProjectMaxed:"CLAN_PROJECT_MAXED",ContributeLimit:"CLAN_CONTRIBUTE_LIMIT",ActivityNotFound:"CLAN_ACTIVITY_NOT_FOUND",ActivityNotActive:"CLAN_ACTIVITY_NOT_ACTIVE",ActivityRunning:"CLAN_ACTIVITY_RUNNING",ActivityCooldown:"CLAN_ACTIVITY_COOLDOWN",NoAttempts:"CLAN_NO_ATTEMPTS",ScoreRejected:"CLAN_SCORE_REJECTED",BossDefeated:"CLAN_BOSS_DEFEATED",BoardNotFound:"CLAN_BOARD_NOT_FOUND",QuestNotFound:"CLAN_QUEST_NOT_FOUND",QuestFull:"CLAN_QUEST_FULL",TakeLimit:"CLAN_TAKE_LIMIT",QuestNotTaken:"CLAN_QUEST_NOT_TAKEN",QuestDone:"CLAN_QUEST_DONE",AbandonCooldown:"CLAN_ABANDON_COOLDOWN",SelectionLocked:"CLAN_SELECTION_LOCKED",ClaimAfterEnd:"CLAN_CLAIM_AFTER_END",NotEligible:"CLAN_NOT_ELIGIBLE",ClaimExpired:"CLAN_CLAIM_EXPIRED",CompetitionNotFound:"CLAN_COMPETITION_NOT_FOUND",CompetitionNotActive:"CLAN_COMPETITION_NOT_ACTIVE",RegistrationClosed:"CLAN_REGISTRATION_CLOSED",NotRegistered:"CLAN_NOT_REGISTERED",TooFewMembers:"CLAN_TOO_FEW_MEMBERS",WarPreparation:"CLAN_WAR_PREPARATION",NotInRoster:"CLAN_NOT_IN_ROSTER",TargetInvalid:"CLAN_TARGET_INVALID",AttackPending:"CLAN_ATTACK_PENDING",AttackNotFound:"CLAN_ATTACK_NOT_FOUND",AttackExpired:"CLAN_ATTACK_EXPIRED",RelationExists:"CLAN_RELATION_EXISTS",RelationLimit:"CLAN_RELATION_LIMIT",RelationNotFound:"CLAN_RELATION_NOT_FOUND",RelationDisabled:"CLAN_RELATION_DISABLED"},vx={Duel:"Duel",Battle:"Battle",League:"League",War:"War"},Ax={Ally:"Ally",Pact:"Pact",Enemy:"Enemy",None:"None"},Gs="clan",cn=z.array(z.string()).nullish(),Y=z.number().nullish(),Tx=z.record(z.string(),z.number()).nullish(),wx=z.object({NounKey:z.string().nullish(),DisplayName:z.string().nullish(),Icon:z.string().nullish(),SortOrder:Y}).passthrough(),zx=z.object({NameMinLength:Y,NameMaxLength:Y,TagRequired:z.boolean().nullish(),TagMinLength:Y,TagMaxLength:Y,DescriptionMaxLength:Y,AnnouncementMaxLength:Y,Emblem:z.object({Backgrounds:cn,Symbols:cn,Colors:cn}).passthrough().nullish(),Languages:cn,Attributes:z.record(z.string(),z.object({NameKey:z.string().nullish(),Values:cn,Required:z.boolean().nullish()}).passthrough()).nullish(),RenameCooldownHours:Y}).passthrough(),kx=z.object({BaseCapacity:Y,JoinModes:z.array(z.string()).nullish(),DefaultJoinMode:z.string().nullish(),ApplicationHours:Y,InviteHours:Y,JoinCooldownHours:Y,TenureHoursForRewards:Y,NoBoardAttacksOnClanmates:z.boolean().nullish(),SuggestJoinAfterHours:Y,KickInactiveDays:Y}).passthrough(),Mx=z.object({Rank:z.number().catch(0),NameKey:z.string().nullish(),DisplayName:z.string().nullish(),MaxCount:Y,Permissions:cn}).passthrough(),Ox=z.object({Enabled:z.boolean().nullish(),Type:z.string().catch("Resource"),NameKey:z.string().nullish(),CooldownMinutes:Y,LifetimeHours:Y,MaxOpenPerMember:Y,Resources:z.array(At.passthrough()).nullish(),Funding:z.string().nullish(),MaxPerDonor:Y,MaxHelps:Y,MaxItemLevel:Y,MinMembershipHoursToDonate:Y}).passthrough(),Ex=z.object({Enabled:z.boolean().nullish(),Identity:wx.nullish(),Create:zx.nullish(),Membership:kx.nullish(),Roles:z.object({Roles:z.record(z.string(),Mx).nullish(),LeaderRoleID:z.string().nullish(),DefaultRoleID:z.string().nullish()}).passthrough().nullish(),Rankings:z.object({Metrics:cn,ByLanguage:z.boolean().nullish(),ByRegion:z.boolean().nullish()}).passthrough().nullish(),Counters:z.record(z.string(),z.object({}).passthrough()).nullish(),Progression:z.object({}).passthrough().nullish(),Requests:z.record(z.string(),Ox).nullish(),Gifts:z.object({Gifts:z.record(z.string(),z.object({}).passthrough()).nullish(),ShowSender:z.boolean().nullish()}).passthrough().nullish(),Treasury:z.object({Currencies:z.record(z.string(),z.object({NameKey:z.string().nullish(),Icon:z.string().nullish(),Deposits:z.array(z.object({Resource:At.passthrough().nullish(),Gives:z.number().catch(1)}).passthrough()).nullish(),DailyDepositCapPerMember:Y,Max:Y}).passthrough()).nullish(),Purchases:z.record(z.string(),z.object({Enabled:z.boolean().nullish(),NameKey:z.string().nullish(),Icon:z.string().nullish(),Cost:Tx,DurationHours:z.number().catch(24),MinClanLevel:Y}).passthrough()).nullish()}).passthrough().nullish(),Projects:z.record(z.string(),z.object({Enabled:z.boolean().nullish(),NameKey:z.string().nullish(),Icon:z.string().nullish(),SortOrder:Y,Inputs:z.array(z.object({Resource:At.passthrough().nullish(),TreasuryCurrencyID:z.string().nullish(),PointsPerUnit:Y}).passthrough()).nullish()}).passthrough()).nullish(),Activities:z.record(z.string(),z.object({Enabled:z.boolean().nullish(),Type:z.string().catch("Goal"),NameKey:z.string().nullish(),Icon:z.string().nullish()}).passthrough()).nullish(),Quests:z.record(z.string(),z.object({Enabled:z.boolean().nullish(),Mode:z.string().catch("Shared"),NameKey:z.string().nullish()}).passthrough()).nullish(),Competitions:z.record(z.string(),z.object({Enabled:z.boolean().nullish(),Type:z.string().catch("Battle"),NameKey:z.string().nullish(),Icon:z.string().nullish(),Registration:z.string().nullish(),MinMembers:Y,BracketSize:Y,Phases:z.array(z.object({DurationHours:z.number().catch(24),NameKey:z.string().nullish()}).passthrough()).nullish(),War:z.object({AttacksPerMember:Y,MaxStars:Y,RosterSize:Y,PreparationHours:Y,ResultSource:z.string().nullish()}).passthrough().nullish()}).passthrough()).nullish(),Leagues:z.object({StartRating:Y,Tiers:z.array(z.object({LeagueID:z.string(),MinRating:z.number().catch(0),NameKey:z.string().nullish(),Icon:z.string().nullish(),SeasonReward:$.nullish()}).passthrough()).nullish(),Season:z.object({IntervalSeconds:Y,AnchorUtc:z.string().nullish(),KeepPercent:Y}).passthrough().nullish()}).passthrough().nullish(),Revenge:z.object({Enabled:z.boolean().nullish(),WindowHours:Y,MaxPerMemberPerDay:Y}).passthrough().nullish(),ChatNotices:z.object({Enabled:z.boolean().nullish(),Events:z.array(z.string()).nullish()}).passthrough().nullish(),Diplomacy:z.object({MaxAllies:Y,MaxPacts:Y,MaxEnemies:Y,ProposalHours:Y}).passthrough().nullish()}).passthrough(),qx=z.object({IsEnabled:z.boolean().nullish(),Kinds:z.record(z.string(),Ex).nullish(),RefreshSeconds:Y}).passthrough(),va=z.record(z.string(),z.string()).nullish(),Pa=z.record(z.string(),z.number()).nullish(),Zt=z.object({ClanID:z.string(),KindID:z.string().catch(Gs),Name:z.string().catch(""),Tag:z.string().nullish(),Description:z.string().nullish(),Announcement:z.string().nullish(),Emblem:z.object({Background:z.string().nullish(),Symbol:z.string().nullish(),Color:z.string().nullish()}).passthrough().nullish(),Language:z.string().nullish(),Country:z.string().nullish(),Attributes:va,JoinMode:bx,MinPower:Y,MinLevel:Y,LeaderUserID:z.string().nullish(),MemberCount:z.number().catch(0),Capacity:z.number().catch(0),Level:z.number().catch(1),Xp:z.number().catch(0),NextLevelXp:Y,GiftPoints:z.number().catch(0),GiftLevel:z.number().catch(0),Power:z.number().catch(0),Trophies:z.number().catch(0),Counters:Pa,Perks:Pa,Modifiers:z.array(z.object({}).passthrough()).nullish(),Treasury:Pa,RecommendedProjectID:z.string().nullish(),LeagueRating:z.number().catch(0),LeagueID:z.string().nullish(),CreatedAt:u.nullish(),ActiveAt:u.nullish()}).passthrough(),Aa=z.object({RoleID:z.string().catch(""),JoinedAt:u.nullish(),Permissions:z.array(z.string()).catch([]),IsLeader:z.boolean().catch(false),ContributionTotal:z.number().catch(0),ContributionToday:z.number().catch(0),ContributionWeek:z.number().catch(0),DonatedTotal:z.number().catch(0),RewardsFrom:u.nullish()}).passthrough(),Ux=z.object({KindID:z.string(),Clan:Zt.nullish(),Membership:Aa.nullish(),JoinAllowedAt:u.nullish(),InvitesCount:z.number().catch(0),MyApplicationsCount:z.number().catch(0),ClaimableRewards:z.number().catch(0),ClaimableGifts:z.number().catch(0),ClaimableCompetitions:z.number().catch(0),SuggestJoin:z.boolean().catch(false)}).passthrough(),$p=z.object({ServerTimeUtc:u.nullish(),RefreshSeconds:z.number().catch(30),Kinds:z.array(Ux).catch([])}).passthrough(),Ta=z.object({ServerTimeUtc:u.nullish(),Clans:z.array(Zt).catch([]),NextCursor:z.string().nullish()}).passthrough(),Jp=z.object({ServerTimeUtc:u.nullish(),Clan:Zt,Membership:Aa.nullish(),Applied:z.boolean().catch(false)}).passthrough(),Zp=z.object({UserID:z.string(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),PlayerLevel:z.number().catch(0),RoleID:z.string().catch(""),JoinedAt:u.nullish(),ActiveAt:u.nullish(),Power:z.number().catch(0),Trophies:z.number().catch(0),ContributionTotal:z.number().catch(0),ContributionWeek:z.number().catch(0),ContributionToday:z.number().catch(0),DonatedTotal:z.number().catch(0)}).passthrough(),Yp=z.object({ServerTimeUtc:u.nullish(),ClanID:z.string().nullish(),Members:z.array(Zp).catch([])}).passthrough(),Hp=z.object({Rank:z.number().catch(0),Value:z.number().catch(0),Clan:Zt}).passthrough(),Xp=z.object({ServerTimeUtc:u.nullish(),Metric:z.string().nullish(),Slice:z.string().nullish(),Rows:z.array(Hp).catch([]),Mine:Hp.nullish()}).passthrough(),Lx=z.object({ID:z.string(),Type:z.string().catch("Application"),KindID:z.string().nullish(),ClanID:z.string().nullish(),Clan:Zt.nullish(),UserID:z.string().nullish(),Player:Zp.nullish(),InviterUserID:z.string().nullish(),Message:z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),wa=z.object({ServerTimeUtc:u.nullish(),Items:z.array(Lx).catch([])}).passthrough(),Bx=z.object({Type:z.string().catch(""),ActorUserID:z.string().nullish(),TargetUserID:z.string().nullish(),Params:va,At:u.nullish()}).passthrough(),eh=z.object({ServerTimeUtc:u.nullish(),Entries:z.array(Bx).catch([]),NextCursor:z.string().nullish()}).passthrough(),th=z.object({RequestID:z.string(),RequestKindID:z.string().catch(""),Type:z.string().catch("Resource"),UserID:z.string().catch(""),Username:z.string().nullish(),Resource:At.passthrough().nullish(),ItemLevel:z.number().nullish(),Needed:z.number().catch(0),Filled:z.number().catch(0),Claimed:z.number().catch(0),MyDonation:z.number().catch(0),TaskKey:z.string().nullish(),Helps:z.number().catch(0),MaxHelps:z.number().catch(0),HelpedByMe:z.boolean().catch(false),Status:z.string().catch("Open"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),nh=z.object({ServerTimeUtc:u.nullish(),Requests:z.array(th).catch([])}).passthrough(),Gx=z.object({GiftUid:z.string(),GiftID:z.string().catch(""),SenderUserID:z.string().nullish(),Level:z.number().catch(0),Content:$.nullish(),Claimed:z.boolean().catch(false),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),ih=z.object({ServerTimeUtc:u.nullish(),GiftLevel:z.number().catch(0),GiftPoints:z.number().catch(0),NextGiftLevelPoints:Y,Gifts:z.array(Gx).catch([])}).passthrough(),Ns=z.object({Key:z.string(),Source:z.string().nullish(),MilestoneID:z.string().nullish(),RequiredProgress:z.number().catch(0),Rewards:$.nullish(),ReachedAt:u.nullish(),Claimed:z.boolean().catch(false),Claimable:z.boolean().catch(false),Blocked:z.string().nullish()}).passthrough(),sh=z.object({ServerTimeUtc:u.nullish(),Rewards:z.array(Ns).catch([])}).passthrough(),rh=z.object({AttackID:z.string(),AttackerUserID:z.string().nullish(),TargetUserID:z.string().nullish(),Status:z.string().catch("Pending"),Stars:z.number().catch(0),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),oh=z.object({ClanID:z.string(),Clan:Zt.nullish(),Relation:z.string().catch("None"),Status:z.string().catch("Active"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),ah=z.object({ServerTimeUtc:u.nullish(),Clan:Zt.nullish(),Membership:Aa.nullish(),Request:th.nullish(),Resources:O.nullish(),Inventory:Q.nullish(),Done:z.array(z.string()).nullish(),Failed:va,WarAttack:rh.nullish(),WarBattle:Qn.nullish(),Relation:oh.nullish()}).passthrough(),lh=z.object({ServerTimeUtc:u.nullish(),Definitions:qx.nullish(),DefaultKindID:z.string().nullish()}).passthrough(),Nx=z.object({Target:z.string().catch(""),Operation:z.string().catch("AddPercent"),Value:z.number().catch(0),Tag:z.string().nullish()}).passthrough(),_x=z.object({PurchaseID:z.string(),ExpiresAt:u.nullish(),Modifiers:z.array(Nx).nullish()}).passthrough(),Vx=z.object({CurrencyID:z.string().catch(""),Delta:z.number().catch(0),Kind:z.string().nullish(),ActorUserID:z.string().nullish(),RefID:z.string().nullish(),At:u.nullish()}).passthrough(),uh=z.object({ServerTimeUtc:u.nullish(),Balances:z.record(z.string(),z.number()).catch({}),Buffs:z.array(_x).catch([]),Ledger:z.array(Vx).catch([]),NextCursor:z.string().nullish(),MyDepositsToday:z.record(z.string(),z.number()).catch({})}).passthrough(),jx=z.object({ProjectID:z.string(),Points:z.number().catch(0),Level:z.number().catch(0),MaxLevel:z.number().catch(0),NextLevelPoints:Y,Locked:z.string().nullish(),MyPointsToday:z.number().catch(0),DailyCap:Y,Recommended:z.boolean().catch(false)}).passthrough(),ch=z.object({ServerTimeUtc:u.nullish(),RecommendedProjectID:z.string().nullish(),Projects:z.array(jx).catch([])}).passthrough(),Fx=z.object({ActivityID:z.string(),Type:z.string().catch("Goal"),Status:z.string().catch("Idle"),InstanceKey:z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),Points:z.number().catch(0),MyPoints:z.number().catch(0),MyPointsToday:z.number().catch(0),BossLevel:z.number().catch(0),BossHp:z.number().catch(0),BossDamage:z.number().catch(0),BossDefeated:z.boolean().catch(false),AttemptsLeft:z.number().catch(0),CanStart:z.boolean().catch(false),StartAllowedAt:u.nullish(),Rewards:z.array(Ns).catch([])}).passthrough(),ph=z.object({ServerTimeUtc:u.nullish(),Activities:z.array(Fx).catch([])}).passthrough(),Wx=z.object({ObjectiveID:z.string().catch(""),Target:z.number().catch(0),Progress:z.number().catch(0),MyProgress:z.number().catch(0)}).passthrough(),Kx=z.object({QuestID:z.string(),Identity:z.object({DisplayName:z.string().nullish(),Description:z.string().nullish()}).passthrough().nullish(),Objectives:z.array(Wx).catch([]),Reward:z.object({Grant:$.nullish(),PointsReward:Y}).passthrough().nullish(),ClanXp:Y,Status:z.string().catch("Available"),Takers:z.number().catch(0),MyContribution:z.number().catch(0),Claimable:z.boolean().catch(false),Claimed:z.boolean().catch(false),Blocked:z.string().nullish()}).passthrough(),Qx=z.object({BoardID:z.string(),Mode:z.string().catch("Shared"),CycleKey:z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),Ended:z.boolean().catch(false),Points:z.number().catch(0),MyPoints:z.number().catch(0),MyTaken:z.number().catch(0),MaxTaken:z.number().catch(0),TakeAllowedAt:u.nullish(),SelectedBy:z.string().nullish(),CanSelect:z.boolean().catch(false),Quests:z.array(Kx).catch([]),Rewards:z.array(Ns).catch([])}).passthrough(),hh=z.object({ServerTimeUtc:u.nullish(),Boards:z.array(Qx).catch([])}).passthrough(),Hx=z.object({CompetitionID:z.string(),Type:z.string().catch("Battle"),Status:z.string().catch("Idle"),InstanceKey:z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),PhaseIndex:Y,PhaseEndsAt:u.nullish(),Registered:z.boolean().catch(false),CanRegister:z.boolean().catch(false),RegisterBlocked:z.string().nullish(),RegistrationClosesAt:u.nullish(),BracketID:z.string().nullish(),ClansInBracket:z.number().catch(0),Score:z.number().catch(0),Place:Y,Finalized:z.boolean().catch(false),NoContest:z.boolean().catch(false),RatingDelta:Y,MyPoints:z.number().catch(0),MyPointsToday:z.number().catch(0),AttacksLeft:Y,InRoster:z.boolean().nullish(),AttacksFrom:u.nullish(),Rewards:z.array(Ns).catch([])}).passthrough(),dh=z.object({ServerTimeUtc:u.nullish(),LeagueRating:z.number().catch(0),LeagueID:z.string().nullish(),Competitions:z.array(Hx).catch([])}).passthrough(),$x=z.object({Place:z.number().catch(0),Clan:Zt.nullish(),Score:z.number().catch(0),RatingDelta:Y,IsMine:z.boolean().catch(false)}).passthrough(),Jx=z.object({UserID:z.string(),ClanID:z.string().nullish(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),Power:z.number().catch(0),BestStars:z.number().catch(0),AttacksUsed:z.number().catch(0)}).passthrough(),mh=z.object({ServerTimeUtc:u.nullish(),BracketID:z.string().nullish(),CompetitionID:z.string().nullish(),Type:z.string().catch("Battle"),InstanceKey:z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),Finalized:z.boolean().catch(false),NoContest:z.boolean().catch(false),Rows:z.array($x).catch([]),War:z.array(Jx).nullish(),MyAttacks:z.array(rh).nullish()}).passthrough(),fh=z.object({ServerTimeUtc:u.nullish(),CanManage:z.boolean().catch(false),Relations:z.array(oh).catch([]),Limits:z.record(z.string(),z.number()).catch({}),Counts:z.record(z.string(),z.number()).catch({})}).passthrough(),Zx=z.object({RevengeID:z.string(),VictimUserID:z.string().nullish(),VictimName:z.string().nullish(),AttackerUserID:z.string().nullish(),AttackerName:z.string().nullish(),AttackerAvatarUrl:z.string().nullish(),Action:z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish(),TakenBy:z.string().nullish(),TakenByName:z.string().nullish(),IsMine:z.boolean().catch(false)}).passthrough(),gh=z.object({ServerTimeUtc:u.nullish(),Revenges:z.array(Zx).catch([]),TakenToday:z.number().catch(0),DailyLimit:z.number().catch(0)}).passthrough(),Yx=z.object({Key:z.string().nullish(),LeagueID:z.string().nullish(),Rating:z.number().catch(0),EndedAt:u.nullish(),Reward:$.nullish(),Claimable:z.boolean().catch(false),Claimed:z.boolean().catch(false)}).passthrough(),yh=z.object({ServerTimeUtc:u.nullish(),LeagueRating:z.number().catch(0),LeagueID:z.string().nullish(),SeasonKey:z.string().nullish(),SeasonEndsAt:u.nullish(),LastSeason:Yx.nullish()}).passthrough();var za="Clan",_s=class{constructor(e){this.ctx=e;}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}get definitions(){return this.ctx.data.config.getSection(za)}get enabled(){let e=this.definitions;return !e||e.IsEnabled===false?false:Object.values(e.Kinds??{}).some(t=>t?.Enabled!==false)}get kindIDs(){let e=this.definitions?.Kinds??{};return Object.entries(e).filter(([,t])=>t?.Enabled!==false).sort(([,t],[,n])=>(t?.Identity?.SortOrder??0)-(n?.Identity?.SortOrder??0)).map(([t])=>t)}kind(e){return (this.definitions?.Kinds??{})[e??this.kindIDs[0]??Gs]}async getDefinitions(e){let t=this.ctx.cache.configSection(za,e);if(t)return a$1(t);let n=this.request();if(!n)return c;let i=await this.ctx.api.clan.getDefinitions(n);if(!i.ok)return i;let s=i.data.Definitions??{};return this.ctx.data.config.patchSection(za,s),a$1(s)}async getMyClans(){let e=this.request();if(!e)return c;let t=await this.ctx.api.clan.getMyClans(e);return t.ok&&this.ctx.emitter.emit("clan:myClansLoaded",t.data),t}async searchClans(e){let t=this.request({KindID:e?.kindID,Query:e?.query,OnlyOpen:e?.onlyOpen,NotFull:e?.notFull,Language:e?.language,PageSize:e?.pageSize});return t?this.ctx.api.clan.searchClans(t):c}async getRecommendedClans(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRecommendedClans(t):c}async getClan(e,t){if(!e?.trim())return b("client","ClanID is required.");let n=this.request({ClanID:e.trim(),KindID:t});return n?this.ctx.api.clan.getClan(n):c}async getMembers(e,t){let n=this.request({ClanID:e,KindID:t});return n?this.ctx.api.clan.getClanMembers(n):c}async getRankings(e){let t=this.request({KindID:e?.kindID,Metric:e?.metric,Slice:e?.slice,PageSize:e?.pageSize});return t?this.ctx.api.clan.getRankings(t):c}async getApplications(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getApplications(t):c}async getMyInvites(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getMyInvites(t):c}async getLog(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getClanLog(t):c}async getRequests(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRequests(t):c}async getGifts(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getGifts(t):c}async getRewards(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRewards(t):c}async getTreasury(e,t){let n=this.request({KindID:e,Cursor:t});return n?this.ctx.api.clan.getTreasury(n):c}async getProjects(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getProjects(t):c}async getActivities(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getActivities(t):c}async getClanQuests(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getClanQuests(t):c}async getCompetitions(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getCompetitions(t):c}async getBracket(e,t){let n=this.request({CompetitionID:e,BracketID:t?.bracketID,InstanceKey:t?.instanceKey,KindID:t?.kindID});return n?this.ctx.api.clan.getBracket(n):c}async getDiplomacy(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getDiplomacy(t):c}async getRevenges(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRevenges(t):c}async getLeague(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getLeague(t):c}async mutate(e,t){let n=this.request(t);if(!n)return c;let i=await this.ctx.api.clan.mutate(e,n);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("clan:changed",{action:e,...i.data})),i}info(e){return {ClanName:e.name,Tag:e.tag,Description:e.description,Announcement:e.announcement,Emblem:e.emblem,Language:e.language,Attributes:e.attributes,JoinMode:e.joinMode,MinPower:e.minPower,MinLevel:e.minLevel,PriceOptionID:e.priceOptionID}}createClan(e,t){return e?.name?.trim()?this.mutate("CreateClan",{KindID:t,...this.info(e)}):Promise.resolve(b("client","Name is required."))}updateClan(e,t){return this.mutate("UpdateClan",{KindID:t,...this.info(e)})}disbandClan(e){return this.mutate("DisbandClan",{KindID:e})}joinClan(e,t){return this.mutate("JoinClan",{ClanID:e,KindID:t})}applyToClan(e,t,n){return this.mutate("ApplyToClan",{ClanID:e,Message:t,KindID:n})}cancelApplication(e,t){return this.mutate("CancelApplication",{ClanID:e,KindID:t})}acceptApplication(e,t){return this.mutate("AcceptApplication",{TargetUserID:e,KindID:t})}rejectApplication(e,t){return this.mutate("RejectApplication",{TargetUserID:e,KindID:t})}invitePlayer(e,t,n){return this.mutate("InvitePlayer",{TargetUserID:e,Message:t,KindID:n})}acceptInvite(e,t){return this.mutate("AcceptInvite",{ClanID:e,KindID:t})}declineInvite(e,t){return this.mutate("DeclineInvite",{ClanID:e,KindID:t})}leaveClan(e){return this.mutate("LeaveClan",{KindID:e})}kickMember(e,t){return this.mutate("KickMember",{TargetUserID:e,KindID:t})}setMemberRole(e,t,n){return this.mutate("SetMemberRole",{TargetUserID:e,RoleID:t,KindID:n})}transferLeadership(e,t){return this.mutate("TransferLeadership",{TargetUserID:e,KindID:t})}createRequest(e,t){return this.mutate("CreateRequest",{RequestKindID:e,Resource:t?.resource,TaskKey:t?.taskKey,ItemInstanceID:t?.itemInstanceID,KindID:t?.kindID})}donateItems(e,t,n){return this.mutate("Donate",{RequestID:e,ItemInstanceIDs:t,KindID:n})}donate(e,t=1,n){return this.mutate("Donate",{RequestID:e,Amount:t,KindID:n})}help(e,t){return this.mutate("Help",{RequestID:e,KindID:t})}claimRequest(e,t){return this.mutate("ClaimRequest",{RequestID:e,KindID:t})}claimGift(e,t){return this.mutate("ClaimGift",{GiftUid:e,KindID:t})}claimAllGifts(e){return this.mutate("ClaimAllGifts",{KindID:e})}claimRewards(e,t){return this.mutate("ClaimRewards",{RewardKeys:e,KindID:t})}depositToTreasury(e,t,n=1,i){return this.mutate("DepositToTreasury",{CurrencyID:e,PayWith:t,Steps:n,KindID:i,RelatedEntityID:`clan_deposit_${a()}`})}buyTreasuryPurchase(e,t){return this.mutate("BuyTreasuryPurchase",{PurchaseID:e,KindID:t})}contributeToProject(e,t){return this.mutate("ContributeToProject",{ProjectID:e,Amount:t.amount,PayWith:t.payWith,FromTreasury:t.fromTreasury,CurrencyID:t.currencyID,KindID:t.kindID,RelatedEntityID:`clan_project_${a()}`})}setRecommendedProject(e,t){return this.mutate("SetRecommendedProject",{ProjectID:e??void 0,KindID:t})}startActivity(e,t){return this.mutate("StartActivity",{ActivityID:e,KindID:t})}submitActivityScore(e,t,n){return this.mutate("SubmitActivityScore",{ActivityID:e,Score:t,KindID:n})}claimActivityRewards(e){return this.mutate("ClaimActivityRewards",{ActivityID:e?.activityID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}selectClanQuests(e,t,n){return this.mutate("SelectClanQuests",{BoardID:e,QuestIDs:t,KindID:n})}takeClanQuest(e,t,n){return this.mutate("TakeClanQuest",{BoardID:e,QuestID:t,KindID:n})}abandonClanQuest(e,t,n){return this.mutate("AbandonClanQuest",{BoardID:e,QuestID:t,KindID:n})}claimClanQuestRewards(e){return this.mutate("ClaimClanQuestRewards",{BoardID:e?.boardID,QuestID:e?.questID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}registerForCompetition(e,t){return this.mutate("RegisterForCompetition",{CompetitionID:e,KindID:t})}claimCompetitionRewards(e){return this.mutate("ClaimCompetitionRewards",{CompetitionID:e?.competitionID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}startWarAttack(e,t,n){return this.mutate("StartWarAttack",{CompetitionID:e,TargetUserID:t,CharacterID:n?.characterID,KindID:n?.kindID})}setDiplomacy(e,t,n){return this.mutate("SetDiplomacy",{TargetClanID:e,Relation:t,KindID:n})}takeRevenge(e,t){return this.mutate("TakeRevenge",{RevengeID:e,KindID:t})}claimSeasonReward(e){return this.mutate("ClaimSeasonReward",{KindID:e})}};var wn={GetDefinitions:"GetDefinitions",GetAvatars:"GetAvatars",GetShop:"GetShop",BuyItem:"BuyItem"},Xx={TooManyUsers:"AVATAR_TOO_MANY_USERS",Disabled:"AVATAR_DISABLED",NotForSale:"AVATAR_ITEM_NOT_FOR_SALE"},Vs=50,js=z.object({Enabled:z.boolean().nullish(),Styles:z.array(z.string()).nullish(),BlockedSlots:z.array(z.string()).nullish(),HeightMin:z.number().nullish(),HeightMax:z.number().nullish()}).passthrough(),eb=48,tb=z.object({UserID:z.string(),Rev:z.string(),NotModified:z.boolean().nullish(),HasAvatar:z.boolean(),Spec:z.record(z.string(),z.unknown()).nullish()}).passthrough(),Rh=z.object({id:z.string(),slot:z.string()}).passthrough(),Ch=z.object({Enabled:z.boolean(),Avatars:z.array(tb).nullish().transform(o=>o??[]),Items:z.record(z.string(),Rh).nullish().transform(o=>o??{})}).passthrough(),nb=z.object({ItemID:z.string(),Slot:z.string(),PriceCredits:z.number(),OnSale:z.boolean().nullish(),Name:z.string().nullish(),Source:z.enum(["platform","authors"]).nullish().catch(null),AuthorName:z.string().nullish(),IsOwned:z.boolean().nullish()}).passthrough(),Sh=z.object({Enabled:z.boolean(),Offers:z.array(nb).nullish().transform(o=>o??[]),Owned:z.array(z.string()).nullish().transform(o=>o??[]),LoginRequired:z.boolean().nullish().transform(o=>o??false),Items:z.record(z.string(),Rh).nullish().transform(o=>o??{}),Paged:z.boolean().nullish(),Next:z.string().nullish(),Slots:z.array(z.string()).nullish(),AuthorsOpen:z.boolean().nullish()}).passthrough(),xh=z.object({ItemID:z.string().nullish(),Owned:z.boolean().nullish().transform(o=>o??false),TestPurchase:z.boolean().nullish().transform(o=>o??false),CreditsConfirmation:ye.nullish()}).passthrough();var ib="Avatar",Fs=class{constructor(e){this.ctx=e;e.emitter.on("auth:loggedOut",()=>{this.held.clear(),this.inflight.clear(),this.disabled=false;});}ctx;held=new Map;inflight=new Map;disabled=false;get definitions(){return this.ctx.cache.configSection(ib)??null}get enabled(){return this.definitions?.Enabled===true&&!this.disabled}peek(e){return this.held.get(e)}async getMine(){let e=this.ctx.auth.context?.userID;if(!e)return c;let t=await this.get([e]);return t.ok?a$1(t.data[0]??null):t}async get(e){if(!this.ctx.authedRequest())return c;let n=[...new Set(e.map(r=>r?.trim()).filter(r=>!!r))];if(n.length===0)return a$1([]);let i=new Set,s=[];for(let r of n){let p=this.inflight.get(r);p?i.add(p):s.push(r);}for(let r=0;r<s.length;r+=Vs){let p=s.slice(r,r+Vs),m=this.request(p);for(let R of p)this.inflight.set(R,m);m.finally(()=>{for(let R of p)this.inflight.get(R)===m&&this.inflight.delete(R);}),i.add(m);}for(let r of await Promise.all(i)){if(!r.ok)return r;if(!r.data.Enabled)return a$1([])}return a$1(n.map(r=>this.held.get(r)).filter(r=>!!r))}async getShop(){let e=this.ctx.authedRequest();return e?this.ctx.api.avatar.getShop(e):c}async browseShop(e={}){let t=this.ctx.authedRequest();if(!t)return c;t.Sort=e.sort??"new",e.slot&&(t.Slot=e.slot);let n=e.query?.trim();return n&&(t.Query=n),e.ownedOnly&&(t.OwnedOnly=true),e.source&&(t.Source=e.source),e.cursor&&(t.Cursor=e.cursor),this.ctx.api.avatar.getShop(t)}async buyItem(e,t,n){let i=this.ctx.authedRequest();return i?(i.ItemID=e,i.PriceCredits=t,n&&(i.CreditsConfirmationID=n),this.ctx.api.avatar.buyItem(i)):c}async request(e){let t=this.ctx.authedRequest();if(!t)return c;t.UserIDs=e;let n={};for(let s of e){let r=this.held.get(s);r&&(n[s]=r.rev);}Object.keys(n).length>0&&(t.KnownRevs=n);let i=await this.ctx.api.avatar.getAvatars(t);if(!i.ok)return i;if(this.disabled=!i.data.Enabled,!i.data.Enabled){for(let s of e)this.held.delete(s);return i}if(i.data.Avatars.some(s=>s.NotModified&&this.held.get(s.UserID)?.rev!==s.Rev)){for(let p of e)this.held.delete(p);let s=this.ctx.authedRequest();if(!s)return c;s.UserIDs=e;let r=await this.ctx.api.avatar.getAvatars(s);return r.ok?r.data.Avatars.some(p=>p.NotModified)?b("client","AVATAR_REVISION_MISMATCH"):(this.apply(r.data),r):r}return this.apply(i.data),i}apply(e){let t=[];for(let n of e.Avatars){if(n.NotModified)continue;let i=n.HasAvatar?n.Spec??null:null;this.held.set(n.UserID,{userID:n.UserID,rev:n.Rev,hasAvatar:n.HasAvatar&&!!i,spec:i,items:i?sb(i,e.Items):[]}),t.push(n.UserID);}t.length>0&&this.ctx.emitter.emit("avatar:changed",{userIDs:t});}};function sb(o,e){let t=o.wear;if(!t||typeof t!="object")return [];let n=[];for(let i of Object.values(t))typeof i=="string"&&e[i]&&n.push(e[i]);return n}var Ws=class{constructor(e){this.ctx=e;}ctx;async getMine(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.getMyPartnership(e):c}async apply(e){let t=this.ctx.authedRequest();return t?(t.Links=(e.links??[]).map(n=>n.trim()).filter(n=>n.length>0),e.publicName?.trim()&&(t.PublicName=e.publicName.trim()),e.about?.trim()&&(t.About=e.about.trim()),typeof e.followers=="number"&&e.followers>=0&&(t.Followers=Math.floor(e.followers)),this.ctx.api.partners.apply(t)):c}async acceptInvite(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.acceptInvite(e):c}async getStats(e){let t=this.ctx.authedRequest();return t?(typeof e=="number"&&e>0&&(t.Days=Math.floor(e)),this.ctx.api.partners.getStats(t)):c}async listCreators(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.listCreators(e):c}async getPayouts(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.getPayouts(e):c}};var Ks={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},ka="idos-app",bh=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()}),Dh=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:O.nullish()});var rb=new Set(["CANCELLED","DECLINED","CLOSED"]),ob=45e3,ab=o=>new Promise(e=>setTimeout(e,o)),Qs=class{constructor(e){this.ctx=e;}ctx;get available(){return this.ctx.host.supports.rewardedAds}async showRewarded(e){if(!this.ctx.host.supports.rewardedAds)return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let n=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!n.ok)return {status:"unavailable",reason:n.error};let i=n.data;if(!i.Allowed)return {status:"denied",reason:i.DenyReason??void 0,retryAfterSeconds:i.RetryAfterSeconds??void 0};if(!i.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let s=null;if(i.ProviderID!==ka&&(s=this.titleProvider(i.ProviderID),!s))return {status:"unavailable",reason:"NO_WEB_ADS"};let r=await this.ctx.host.showRewardedAd({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:i.RequestID,placementID:e,adUnitID:i.AdUnitID,provider:s});return r.ok?{...await this.awaitReward(i.RequestID,r.via),requestID:i.RequestID}:{status:rb.has(r.error??"")?"cancelled":"unavailable",reason:r.error}}titleProvider(e){if(!this.ctx.host.supports.titleAds||!e)return null;let n=this.ctx.data.config.getSection("Advertising")?.Providers?.[e];if(!n||n.Enabled===false)return null;let i=this.ctx.host.getClientPlatform(),s=i===j.Android?n.AndroidAppID:i===j.Ios?n.IosAppID:n.WebAppID;return s?{id:e,kind:n.Kind??"AppLovinMax",appKey:s}:null}async awaitReward(e,t){let n=Date.now()+ob;for(;;){let i=this.ctx.authedRequest();if(!i)return {status:"pending",via:t};let s=await this.ctx.api.advertising.completeView({...i,RequestID:e});if(s.ok&&s.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:s.data.CreditsAwarded??0,via:t};let r=Math.min(Math.max((s.ok?s.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+r>n)return {status:"pending",via:t,reason:s.ok?void 0:s.error};await ab(r);}}};var _t={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},lb={Client:"Client",Server:"Server",System:"System"},ub=z.enum(["Client","Server","System"]).catch("Client"),Ma=z.object({Value:z.string().nullish(),UpdatedAt:u.nullish(),Version:z.number().nullish(),LastWriter:ub.nullish(),ExpiresAt:u.nullish()}).passthrough(),Hs=z.record(z.string(),Ma),Ih=z.object({Version:z.number().nullish(),Private:Hs.nullish(),Public:Hs.nullish(),ReadOnly:Hs.nullish()}),Oa=z.object({UserID:z.string().nullish(),Version:z.number().nullish(),Public:Hs.nullish()}),Ea=z.object({ServerTimeUtc:u.nullish(),Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:u.nullish()}),cb=z.object({Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:u.nullish()}),Ph=z.object({ServerTimeUtc:u.nullish(),Results:z.array(cb).nullish()}),vh=z.object({ServerTimeUtc:u.nullish(),DeletedCount:z.number().nullish()}),Ah=z.object({Results:z.array(Oa).nullish(),NotFoundUserIDs:z.array(z.string()).nullish()}),pb={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},hb=z.enum(["String","Int","Bool","Json"]).catch("String"),db=z.object({KeyID:z.string(),Bucket:z.string().nullish(),ValueType:hb.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),$s=z.object({Keys:z.record(z.string(),db).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),vt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var mb={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},fb={Title:"Title",Platform:"Platform"},Th=z.object({UserID:z.string(),PublicData:Ge.nullish(),Source:z.enum(["Title","Platform"]).nullish()});var gb=z.object({StageLevel:z.number().nullish(),SpecialPlayedCount:z.number().nullish()}),wh=z.object({UserID:z.string(),IsSelf:z.boolean().nullish(),PublicData:Ge.nullish(),Characters:z.record(z.string(),Fn).nullish(),StrongestCharacterID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),Board:gb.nullish(),PublicCustomData:z.record(z.string(),Ma).nullish(),Relation:z.enum(["None","Friend","RequestSent","RequestReceived"]).nullish(),FriendSource:z.enum(["Title","Platform"]).nullish(),BlockedByMe:z.boolean().nullish(),FriendRequestsAllowed:z.boolean().nullish()});var $n=z.object({Friends:z.array(Th).nullish()}),yb=z.object({FriendsCount:z.number().nullish(),IncomingRequestsCount:z.number().nullish(),OutgoingRequestsCount:z.number().nullish()}),Jn=z.object({TargetUserID:z.string().nullish(),Status:z.string().nullish(),Target:Th.nullish(),Counters:yb.nullish()}),Rb={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},Cb={Like:"Like",Favorite:"Favorite"},Sb={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},xb={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},bb={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived",ArenaDefeat:"ArenaDefeat"},Db=z.object({Key:z.string().nullish(),DisplayName:z.string().nullish(),AvatarUrl:z.string().nullish()}).passthrough(),Ib=z.object({Id:z.string(),Verb:z.string().nullish(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),Count:z.number().nullish(),LastActors:z.array(Db).nullish(),Payload:z.object({Title:z.string().nullish(),Excerpt:z.string().nullish(),ImageUrl:z.string().nullish()}).passthrough().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),OccurredAt:u.nullish(),OwnerImpact:O.nullish(),IsBlocked:z.boolean().nullish(),TargetObjectName:z.string().nullish()}).passthrough(),zh=z.object({Items:z.array(Ib).nullish(),HasMore:z.boolean().nullish(),NextBeforeUpdatedAt:z.string().nullish(),NextBeforeID:z.string().nullish(),UnreadCount:z.number().nullish(),SeenAt:u.nullish()}).passthrough(),Zn=z.object({UnreadCount:z.number().nullish(),SeenAt:u.nullish()}).passthrough(),Pb=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(),Yt=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Counts:Pb.nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish(),Following:z.boolean().nullish(),Blocked:z.boolean().nullish()}).passthrough(),kh=z.object({Items:z.array(Yt).nullish()}).passthrough(),qa={HasMore:z.boolean().nullish(),NextCursorAt:z.string().nullish(),NextCursorID:z.string().nullish()},vb=z.object({UserID:z.string(),PublicData:Ge.nullish(),Mutual:z.boolean().nullish(),Since:u.nullish()}).passthrough(),Js=z.object({Items:z.array(vb).nullish(),...qa}).passthrough(),Ab=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Kind:z.string().nullish(),At:u.nullish()}).passthrough(),Mh=z.object({Items:z.array(Ab).nullish(),...qa}).passthrough(),Zs=z.object({CommentID:z.string(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),ParentCommentID:z.string().nullish(),AuthorUserID:z.string().nullish(),AuthorPublicData:Ge.nullish(),Text:z.string().nullish(),Status:z.string().nullish(),Pinned:z.boolean().nullish(),CreatedAt:u.nullish(),EditedAt:u.nullish(),Likes:z.number().nullish(),Replies:z.number().nullish(),Liked:z.boolean().nullish(),IsMine:z.boolean().nullish()}).passthrough(),Oh=z.object({Items:z.array(Zs).nullish(),...qa,TotalCount:z.number().nullish()}).passthrough(),Eh=z.object({CommentID:z.string().nullish(),Deleted:z.boolean().nullish()}).passthrough(),qh=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish(),AutoHidden:z.boolean().nullish()}).passthrough(),Uh=z.object({CommentsEnabled:z.boolean().nullish(),CommentableTypes:z.array(z.string()).nullish(),CommentMaxLength:z.number().nullish(),CommentMaxLinks:z.number().nullish()}).passthrough(),Tb="FRIENDS_FROM_PLATFORM",wb={Off:"Off",Default:"Default",Always:"Always"},zb={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Lh=z.object({Profile:z.enum(["Off","Default","Always"]).nullish(),Friends:z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:z.boolean().nullish()}).passthrough(),De={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report",GetPlayerProfile:"GetPlayerProfile"};var Ua={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Ys=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ua,{schema:Zn,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 n=await this.ctx.api.social.getRecommendedFriends(t);return n.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",n.data),n}async getPlayerProfile(e){if(!e)return b("client","TargetUserID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.getPlayerProfile(t);return n.ok&&this.ctx.emitter.emit("social:playerProfileLoaded",n.data),n}async sendFriendRequest(e){if(!e)return b("client","TargetUserID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.sendFriendRequest(t);return n.ok&&(n.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",n.data)),n}async acceptFriendRequest(e){if(!e)return b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.acceptFriendRequest(t);return n.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",n.data)),n}async declineFriendRequest(e){if(!e)return b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.declineFriendRequest(t);return n.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",n.data)),n}async removeFriend(e){if(!e)return b("client","FriendUserID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.removeFriend(t);return n.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRemoved",n.data)),n}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return c;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let n=await this.ctx.api.social.getInbox(t);return n.ok&&this.ctx.emitter.emit("social:inboxLoaded",n.data),n}getInboxUnread(e){return this.ctx.cache.read(Ua,()=>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(Ua,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let n=this.ctx.authedRequest();return n?(n.ReactionKind=e,n.EntityType=t.entityType,this.applyPage(n,t.cursor,t.limit),this.ctx.api.social.getMyReactions(n)):c}async getEntityStates(e,t){if(!t?.length)return b("client","EntityIDs are required.");let n=this.ctx.authedRequest();return n?(n.EntityType=e,n.EntityIDs=t,this.ctx.api.social.getEntityStates(n)):c}async addComment(e,t,n,i){let s=this.targetRequest(e,t);if("ok"in s)return s;if(!n?.trim())return b("client","Text is required.");s.Text=n,s.ParentCommentID=i;let r=await this.ctx.api.social.addComment(s);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 n=this.ctx.authedRequest();if(!n)return c;n.CommentID=e,n.Text=t;let i=await this.ctx.api.social.editComment(n);return i.ok&&this.ctx.emitter.emit("social:commentEdited",i.data),i}async deleteComment(e){if(!e)return b("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.CommentID=e;let n=await this.ctx.api.social.deleteComment(t);return n.ok&&this.ctx.emitter.emit("social:commentDeleted",n.data),n}async getComments(e,t,n={}){let i=this.targetRequest(e,t);return "ok"in i?i:(i.ParentCommentID=n.parentCommentID,this.applyPage(i,n.cursor,n.limit),this.ctx.api.social.getComments(i))}async report(e,t,n,i){let s=this.targetRequest(e,t);if("ok"in s)return s;if(!n)return b("client","ReportReason is required.");s.ReportReason=n,s.ReportComment=i;let r=await this.ctx.api.social.report(s);return r.ok&&this.ctx.emitter.emit("social:reported",r.data),r}async mutate(e,t,n,i){let s=this.targetRequest(t,n);if("ok"in s)return s;s.ReactionKind=i;let r=await this.ctx.api.social[e](s);return r.ok&&this.ctx.emitter.emit("social:entityStateChanged",r.data),r}async page(e,t,n){let i=this.ctx.authedRequest();return i?(this.applyPage(i,t,n),this.ctx.api.social[e](i)):c}applyPage(e,t,n){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=n;}targetRequest(e,t){if(!e)return b("client","EntityType is required.");if(!t)return b("client","EntityID is required.");let n=this.ctx.authedRequest();return n?(n.EntityType=e,n.EntityID=t,n):c}};var Bh="TimedBoost";function kb(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Xs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Bh,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),a$1(t);let n=this.ctx.authedRequest();if(!n)return c;let i=await this.ctx.api.timedBoost.getDefinitions(n);return i.ok&&(this.ctx.data.config.patchSection(Bh,i.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",i.data)),i}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 n=e.trim();if(!kb(n))return b("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),BoostID:n,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${n}_${a()}`},s=await this.ctx.api.timedBoost.activate(i);if(s.ok&&!s.data.CreditsConfirmation){let r=s.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 s}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 Mb="UserCustomData";function Gh(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var er=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(Mb,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 n=this.ctx.authedRequest();if(!n)return c;n.TargetUserID=t;let i=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(n);return i.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",i.data),i}async setPrivateData(e,t){return this.setData(e,t,_t.Private)}async setPublicData(e,t){return this.setData(e,t,_t.Public)}async setData(e,t,n){let i=e.trim();if(!Gh(i))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 s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Value:t},p=await(n===_t.Private?this.ctx.api.userCustomData.setPrivateData(s):this.ctx.api.userCustomData.setPublicData(s));if(p.ok){let m=p.data;this.ctx.data.user.patchUserCustomDataKey(n,m.KeyID,t,m.Version??0,m.ExpiresAt),this.ctx.emitter.emit(n===_t.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",m);}return p}async deleteKey(e,t){let n=e.trim();if(!Gh(n))return b("client",'KeyID is required and must not contain "." or "$".');if(t!==_t.Private&&t!==_t.Public)return b("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Bucket:t},s=await this.ctx.api.userCustomData.deleteKey(i);return s.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,n),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),s}async batchSet(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},n=await this.ctx.api.userCustomData.batchSet(t);if(n.ok){for(let i of n.data.Results??[]){let s=i.Bucket??_t.Private,r=e.find(p=>p.Bucket===s&&p.KeyID===i.KeyID);r&&this.ctx.data.user.patchUserCustomDataKey(s,i.KeyID,r.Value,i.Version??0,i.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",n.data);}return n}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},n=await this.ctx.api.userCustomData.batchDelete(t);if(n.ok){for(let i of e)this.ctx.data.user.removeUserCustomDataKey(i.Bucket,i.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",n.data);}return n}async batchGetPublicUserCustomDataOf(e){if(!e.length)return b("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return c;t.TargetUserIDs=e;let n=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return n.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",n.data),n}};var Ob="TitleCustomDataDefinitions",Nh=50;function Eb(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}function La(o){if(o.ExpiresAt==null)return false;let e=Date.parse(o.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function qb(o){let e={};for(let[t,n]of Object.entries(o))La(n)||(e[t]=n);return e}var tr=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(Ob,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 n=await this.ctx.api.titleCustomData.getPublicTitleData(t);return n.ok&&this.absorb(n.data),n}async getPublicTitleDataKeys(e){let t=e.map(s=>s.trim()).filter(s=>s.length>0);if(!t.length)return b("client","At least one KeyID is required.");if(t.some(s=>!Eb(s)))return b("client",'KeyID must not contain "." or "$".');if(t.length>Nh)return b("client",`At most ${Nh} keys per call \u2014 request them in chunks.`);let n=this.ctx.authedRequest();if(!n)return c;n.KeyIDs=t;let i=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(n);return i.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",i.data),i}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!La(t))return t.Value;let n=this.staticCache[e];if(n?.Value!=null&&!La(n))return n.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=qb(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 nr=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 Ub={Fast:"Fast",Sequential:"Sequential"},Lb={Instant:"Instant",Timed:"Timed"};var Bb={Hit:"Hit",Blocked:"Blocked"},Gb=z.object({SlotIndex:z.number(),Level:z.number().nullish(),IsDamaged:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish()}).passthrough(),Nb=z.object({Symbol:z.union([z.string(),z.number()]).nullish(),OnOpenBonus:$.nullish(),BonusTag:z.string().nullish()}).passthrough();z.object({ElapsedSeconds:z.number().nullish(),Reward:$.nullish()}).passthrough();var _b=z.object({RequiredValue:z.number().nullish(),Reward:$.nullish()}).passthrough(),Vb=z.object({Reward:$.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(_b).nullish(),Rate:Vb.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 _h=z.object({}).passthrough().transform(o=>o),Vh=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),Ye=z.object({Operation:O.nullish(),ScaleWithRollMultiplier:z.boolean().nullish()}).passthrough(),jb=z.object({Count:z.number().nullish(),Sides:z.number().nullish()}).passthrough(),Fb=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(),Wb=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:pe.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(),Kb=z.object({CostMatrix:z.array(z.array(z.number())).nullish(),PerBoardGrowth:z.number().nullish(),EconomyScale:z.number().nullish(),ScaledResources:pe.nullish()}).passthrough(),jh=z.object({SlotIndex:z.number().nullish(),Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxLevel:z.number().nullish(),MaxLevelReward:$.nullish()}).passthrough(),Qb=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(),Hb=z.object({Tiles:z.record(z.string(),Qb).nullish()}).passthrough(),$b=z.object({Weight:z.number().nullish(),Bonus:Ye.nullish(),Tag:z.string().nullish()}).passthrough(),Jb=z.object({Weight:z.number().nullish(),Tag:z.string().nullish(),MinBonusCells:z.number().nullish(),MaxBonusCells:z.number().nullish(),BonusPool:z.array($b).nullish(),GuaranteedBonus:Ye.nullish(),IsJackpot:z.boolean().nullish(),JackpotFinalMultiplier:z.number().nullish(),JackpotSymbolDistribution:z.record(z.string(),z.number()).nullish()}).passthrough(),Zb=z.object({Variants:z.array(Jb).nullish()}).passthrough(),Yb=z.object({Weight:z.number().nullish(),OutcomeID:z.string().nullish(),Reward:Ye.nullish(),ForceAction:z.string().nullish(),SpecialModeID:z.string().nullish()}).passthrough(),Xb=z.object({Outcomes:z.array(Yb).nullish()}).passthrough(),Fh=z.object({PerAdMultiplierRange:Vh.nullish(),MaxAdViews:z.number().nullish(),AdCreditCost:z.number().nullish(),FormulaKind:z.string().nullish(),ApplyMultiplierOnEarlyClaim:z.boolean().nullish(),PremiumMultiplier:z.number().nullish(),MinPremiumTier:z.number().nullish()}).passthrough(),eD=z.object({ElapsedSeconds:z.number().nullish(),Reward:Ye.nullish()}).passthrough(),tD=z.object({Tiers:z.array(eD).nullish(),TierMode:z.string().nullish(),BelowFirstTierReward:Ye.nullish()}).passthrough(),nD=z.object({RequiredValue:z.number().nullish(),Reward:Ye.nullish()}).passthrough(),iD=z.object({Reward:Ye.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough(),sD=z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(nD).nullish(),Rate:iD.nullish()}).passthrough(),Wh=z.object({MetricsByID:z.record(z.string(),sD).nullish()}).passthrough(),rD=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:Ye.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:de.nullish(),Multipliers:Fh.nullish(),Gradation:tD.nullish(),RunStats:Wh.nullish()}).passthrough(),oD=z.object({Choices:z.array(rD).nullish(),OfferExpireSeconds:z.number().nullish(),ClaimExpireSeconds:z.number().nullish()}).passthrough(),aD=z.object({Chance:z.number().nullish(),RequiredOutcome:z.string().nullish(),Reward:Ye.nullish(),Tag:z.string().nullish()}).passthrough(),lD=z.object({OnPassStart:Ye.nullish(),OnTileLanding:z.record(z.string(),Ye).nullish(),OnAttack:z.record(z.string(),Ye).nullish(),OnRaid:z.record(z.string(),Ye).nullish(),OnBuild:Ye.nullish(),OnStageComplete:Ye.nullish(),OnAttackBonusDrops:z.array(aD).nullish(),ChanceTablesByID:z.record(z.string(),Xb).nullish(),SpecialModesByID:z.record(z.string(),oD).nullish()}).passthrough(),Kh=z.object({BaseAttackReward:$.nullish(),BaseRaidReward:$.nullish(),MaxRollMultiplier:z.number().nullish(),MaxShields:z.number().nullish(),Buildings:z.array(jh).nullish(),HeistGridBonusConfig:Zb.nullish(),StageOperations:lD.nullish(),TileLandingMultiplier:Vh.nullish(),EconomyOverride:Kb.nullish()}).passthrough(),uD=z.object({Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BoardTemplateID:z.string().nullish(),Buildings:z.array(jh).nullish(),StageTemplateID:z.string().nullish(),CostMatrixTemplateID:z.string().nullish(),UnitValue:z.number().nullish(),Override:Kh.nullish()}).passthrough(),cD=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(),pD=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(),hD=z.object({Enabled:z.boolean().nullish(),Sources:z.array(z.string()).nullish(),AdMultiplier:z.number().nullish(),PremiumMultiplier:z.number().nullish(),AdCreditCost:z.number().nullish(),AdDailyLimit:z.number().nullish(),PremiumDailyLimit:z.number().nullish(),TtlSeconds:z.number().nullish(),MinPremiumTier:z.number().nullish()}).passthrough(),ir=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(),Hb).nullish(),StageTemplatesByID:z.record(z.string(),Kh).nullish(),StagesByLevel:z.record(z.string(),uD).nullish(),SoftCurrencyID:z.string().nullish(),ProceduralEconomy:Wb.nullish(),Dice:jb.nullish(),Bots:Fb.nullish(),Targeting:cD.nullish(),BotRaids:pD.nullish(),RewardBoost:hD.nullish()}).passthrough(),dD=z.object({IsActive:z.boolean().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AnchorUtc:u.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(),je).nullish(),GrandPrize:$.nullish()}).passthrough(),sr=z.object({Board:ir.nullish(),CommunityChest:dD.nullish()}).passthrough(),Qh=z.object({AttackerGainByOutcome:z.record(z.string(),pe).nullish()}).passthrough(),mD=z.object({TargetUserID:z.string().nullish(),IsBot:z.boolean().nullish(),PublicData:Ge.nullish(),TargetBuildingStates:z.array(Gb).nullish(),TargetHasShield:z.boolean().nullish(),TargetStageLevel:z.number().nullish(),RaidRewardPreview:Qh.nullish()}).passthrough(),fD=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:Ye.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:de.nullish(),Multipliers:Fh.nullish(),RunStats:Wh.nullish()}).passthrough(),gD=z.object({ModeID:z.string().nullish(),Choices:z.array(fD).nullish()}).passthrough(),yD=z.object({GroupID:z.string().nullish(),Delta:H.nullish(),NewProgress:H.nullish(),MaxProgress:H.nullish(),UnlockedMilestoneIDs:z.array(z.string()).nullish(),Completed:z.boolean().nullish()}).passthrough(),Hh=z.object({UsedMultiplier:z.number().nullish(),Steps:z.number().nullish(),DiceValues:z.array(z.number()).nullish(),OldPosition:z.number().nullish(),NewPosition:z.number(),CyclesCompletedDelta:H.nullish(),LandedTileType:z.string().nullish(),Operation:O.nullish(),Inventory:Q.nullish(),ActionRequired:z.string().nullish(),ActionData:mD.nullish(),SpecialModeOffer:gD.nullish(),CommunityChestContribution:yD.nullish()}).passthrough(),rr={Ad:"Ad",Premium:"Premium"},$h=z.object({BoostID:z.string().nullish(),Source:z.string().nullish(),ExpiresAtUtc:u.nullish(),AdMultiplier:z.number().nullish(),PremiumMultiplier:z.number().nullish(),AdCreditCost:z.number().nullish(),MinPremiumTier:z.number().nullish(),AdRemainingToday:z.number().nullish(),PremiumRemainingToday:z.number().nullish(),BaseEntries:z.array(At).nullish()}).passthrough(),Jh=z.object({BoostID:z.string().nullish(),Mode:z.string().nullish(),Multiplier:z.number().nullish(),AlreadyApplied:z.boolean().nullish(),Operation:O.nullish(),Inventory:Q.nullish(),AdRemainingToday:z.number().nullish(),PremiumRemainingToday:z.number().nullish()}).passthrough(),Zh=z.object({Outcome:z.string().nullish(),IsBotTarget:z.boolean().nullish(),BuildingIndexHit:z.number().nullish(),Operation:O.nullish(),Inventory:Q.nullish(),DualResult:Lt.nullish(),RewardBoost:$h.nullish()}).passthrough(),Ba=z.object({Status:z.string().nullish(),Outcome:z.string().nullish(),FoundSymbol:z.union([z.string(),z.number()]).nullish(),FoundBonus:$.nullish(),OpenedIndex:z.number().nullish(),AttemptsLeft:z.number().nullish(),RaidLayout:z.array(Nb).nullish(),HeistVariantTag:z.string().nullish(),IsJackpot:z.boolean().nullish(),Operation:O.nullish(),Inventory:Q.nullish(),DualResult:Lt.nullish(),RaidRewardPreview:Qh.nullish(),RewardBoost:$h.nullish()}).passthrough(),Yh=z.object({BuiltIndex:z.number(),NewLevel:z.number().nullish(),StageComplete:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish(),Operation:O.nullish(),Inventory:Q.nullish()}).passthrough(),Xh=z.object({CreditsConfirmation:ye.nullish(),Mode:z.union([z.string(),z.number()]).nullish(),Operation:O.nullish(),Inventory:Q.nullish(),DurationSeconds:z.number().nullish(),StartedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish()}).passthrough(),ed=z.object({AdViewsUsed:z.number().nullish(),RolledMultiplier:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),RemainingAdViews:z.number().nullish(),PremiumApplied:z.boolean().nullish()}).passthrough(),RD=z.object({MetricID:z.string().nullish(),ReachedTierIndex:z.number().nullish(),RequiredValue:z.number().nullish(),RewardUnits:z.number().nullish()}).passthrough(),td=z.object({FinalMultiplier:z.number().nullish(),AdViewsUsed:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),IsEarlyClaim:z.boolean().nullish(),ReachedTierIndex:z.number().nullish(),Operation:O.nullish(),Inventory:Q.nullish(),AcceptedRunStats:z.record(z.string(),z.number()).nullish(),RunStatAwards:z.array(RD).nullish(),RunStatsClamped:z.boolean().nullish(),RunStatGrant:$.nullish()}).passthrough(),CD={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},nd=z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),SD={Active:"Active",Left:"Left",Replaced:"Replaced"},xD=z.enum(["Active","Left","Replaced"]).catch("Active"),bD=z.object({CurrentProgress:H.nullish(),MaxProgress:H.nullish()}).passthrough(),DD=z.object({UserID:z.string().nullish(),PublicData:Ge.nullish(),IsBot:z.boolean().nullish(),ContributionPoints:H.nullish(),MilestoneClaims:z.record(z.string(),Yl).nullish(),GrandPrizeClaimed:z.boolean().nullish(),MemberStatus:xD.nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),id=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),RoundIndex:z.number().nullish(),Members:z.array(DD).nullish(),SharedProgress:bD.nullish(),Status:nd.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:z.number().nullish()}).passthrough(),ID=z.object({GroupID:z.string().nullish(),RoundIndex:z.number().nullish(),FinalStatus:nd.nullish(),GrandPrizeReceived:z.boolean().nullish(),FinishedAtUtc:u.nullish()}).passthrough(),PD=z.object({ActiveGroupID:z.string().nullish(),ActiveRoundIndex:z.number().nullish(),History:z.array(ID).nullish()}).passthrough(),sd=z.object({ServerTimeUtc:u.nullish(),UserState:PD.nullish(),ActiveGroup:id.nullish(),SecondsRemaining:H.nullish()}),rd=z.object({ServerTimeUtc:u.nullish(),Group:id.nullish(),SecondsRemaining:H.nullish()}),Ga=z.object({ServerTimeUtc:u.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),od=z.object({ServerTimeUtc:u.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),We={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",BoardRewardBoostApply:"BoardRewardBoostApply",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var vD=15,AD="GameLoop",ad="BoardDefinition",Yn="InventoryV2",TD="GameLoop",or=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(AD,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let n=this.ctx.cache.configSection(ad,t);if(n)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n),a$1(n);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.gameLoop.getBoardDefinition(i,e);return s.ok&&(this.ctx.data.config.patchSection(ad,s.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",s.data)),s}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return b("client","stageLevel must be > 0.");let n=this.ctx.authedRequest();if(!n)return c;n.StageLevel=e;let i=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(n,t);return i.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",i.data),i}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return c;let t=false,n=this.ctx.emitter.on("user:stateVersions",({versions:s})=>{s[Yn]!==void 0&&(t=true);}),i;try{i=await this.ctx.api.gameLoop.getUserBoardState(e);}finally{n();}return i.ok&&(this.ctx.data.user.applyBoardState(i.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",i.data),t&&(this.ctx.cache.invalidateState([Yn]),this.ctx.cache.ensureState([Yn]),this.ctx.emitter.emit("user:changedElsewhere",{containers:[Yn]}))),i}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 n={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${a()}`},i=await this.ctx.api.gameLoop.boardLoopRoll(n);if(i.ok){let s=i.data,r=Iu(new Date,vD);this.ctx.data.user.patchBoardState(p=>{p.Position=s.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(s.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),s.ActionRequired&&s.ActionData?p.Pending={Type:s.ActionRequired,TargetUserID:s.ActionData.TargetUserID,TargetPublicData:s.ActionData.PublicData,TargetBuildingStates:s.ActionData.TargetBuildingStates??void 0,TargetHasShield:s.ActionData.TargetHasShield??void 0,RollMultiplier:s.UsedMultiplier??1,ExpiresAtUtc:r}:s.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:s.UsedMultiplier??1,ExpiresAtUtc:r,Special:{ModeID:s.SpecialModeOffer.ModeID??void 0,Choices:s.SpecialModeOffer.Choices??void 0}});}),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),s.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",s);}return i}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return c;let n={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${a()}`},i=await this.ctx.api.gameLoop.boardLoopAttack(n);if(i.ok){let s=i.data;this.ctx.data.user.clearBoardPending(),s.IsBotTarget&&s.Operation?this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs):!s.IsBotTarget&&s.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(s.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",s);}else await this.getUserBoardState();return i}async boardLoopRaid(e,t){if(e<0||e>11)return b("client","digIndex must be between 0 and 11.");let n=this.ctx.auth.context;if(!n)return c;let i={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${n.userID}_${a()}`},s=await this.ctx.api.gameLoop.boardLoopRaid(i);if(s.ok){let r=s.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 s}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 n={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${a()}`},i=await this.ctx.api.gameLoop.boardLoopRaidFast(n);if(i.ok){let s=i.data;s.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(s)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",s);}else await this.getUserBoardState();return i}async boardLoopBuild(e){if(e<0)return b("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return c;let n={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${a()}`},i=await this.ctx.api.gameLoop.boardLoopBuild(n);if(!i.ok&&i.reason==="server"&&await this.ctx.cache.ensureState([Yn,TD],{force:true}),i.ok){let s=i.data;s.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(s.BuiltIndex,r=>{s.NewLevel!=null&&(r.Level=s.NewLevel),r.IsDamaged=false,s.MaxLevelRewardClaimed&&(r.MaxLevelRewardClaimed=true);}),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",s);}return i}async boardSpecialChoose(e,t,n){if(!e)return b("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:n,RelatedEntityID:`special_choose_${i.userID}_${a()}`},r=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(r.ok&&!r.data.CreditsConfirmation){let p=r.data;p.Mode==="Instant"||p.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(R=>{R.ChoiceID=e,R.ChosenMode=p.Mode??"Timed",R.StartedAtUtc=p.StartedAtUtc??null,R.DurationSeconds=p.DurationSeconds??null,R.AdViewsUsed=0;}),p.Operation&&this.ctx.data.user.applyResourcesWithDelta(p.Operation,p.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",p);}return r}async boardSpecialApplyMultiplier(e,t=rr.Ad){let n=this.ctx.auth.context;if(!n)return c;let i=t===rr.Premium,s={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_${i?"vip":"ad"}_${n.userID}_${a()}`,...i?{BoostMode:rr.Premium}:{}},r=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(s);if(r.ok){let p=r.data;this.ctx.data.user.patchBoardSpecialPending(m=>{m.AdViewsUsed=p.AdViewsUsed??0,m.AccumulatedMultiplier=p.AccumulatedMultiplier??0,p.PremiumApplied&&(m.PremiumApplied=true);}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",p);}return r}async boardRewardBoostApply(e,t){if(!this.ctx.auth.context)return c;if(!e)return b("client","boostID must not be empty.");let i={...this.ctx.buildAuthedBaseRequest(),BoostID:e,BoostMode:t,RelatedEntityID:`boost_${e}_${t}`},s=await this.ctx.api.gameLoop.boardRewardBoostApply(i);if(s.ok){let r=s.data;!r.AlreadyApplied&&r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardRewardBoostApplied",r);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return c;let n={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${a()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},i=await this.ctx.api.gameLoop.boardSpecialClaim(n);if(i.ok){let s=i.data;this.ctx.data.user.clearBoardPending(),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",s);}return i}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return 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 n=t.data.Group;n?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:n.GroupID,ActiveRoundIndex:n.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return b("client","milestoneID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},i=await this.ctx.api.gameLoop.claimCommunityChestMilestone(n);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",i.data)),i}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",n.data)),n}async leaveCommunityChest(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.gameLoop.leaveCommunityChest(t);return n.ok&&(n.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",n.data)),n}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var ar=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,n,i){let s=e.trim();if(!s)return b("client","FunctionName is required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),FunctionName:s,FunctionParameter:t,RevisionSelection:n,SpecificRevision:i},p=await this.ctx.api.cloudCode.execute(r);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var wD={EVM:"EVM",Solana:"Solana"},zD=z.enum(["EVM","Solana"]).catch("EVM"),kD={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},MD=z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),OD={Token:"Token",Nft:"Nft"},ld=z.enum(["Token","Nft"]).catch("Token"),ED={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},qD=z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),UD={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},LD=z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),BD={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Na=z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),ud={GameTopUp:"game_topup",CommunityReward:"community_reward"};function lr(o){let e=o?.trim();return e||ud.GameTopUp}var GD={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},cd=z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),ND=z.object({ContractAddress:z.string().nullish(),ItemCatalogID:z.string().nullish(),DisplayName:z.string().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),pd=z.object({Ios:z.boolean().nullish(),Android:z.boolean().nullish(),Web:z.boolean().nullish()}).passthrough(),_D=z.object({NetworkID:z.string().nullish(),DisplayName:z.string().nullish(),Type:zD.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:pd.nullish(),NftCollections:z.array(ND).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(),VD=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:pd.nullish()}).passthrough(),jD=z.object({MinAccountAgeDays:z.number().nullish(),MultiAccountCheckEnabled:z.boolean().nullish(),BanOnSharedWithdrawalAddress:z.boolean().nullish(),PendingWithdrawalTtlHours:z.number().nullish()}).passthrough(),FD={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},WD=z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),hd=z.object({Enabled:z.boolean().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),MinBalance:ie.nullish(),BalanceSource:WD.nullish(),DenyMessage:z.string().nullish()}).passthrough(),KD=z.object({Enabled:z.boolean().nullish(),WalletConnectProjectId:z.string().nullish(),ShowOnLoginScreen:z.boolean().nullish()}).passthrough(),QD={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Xn=z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),HD=z.object({Mode:Xn.nullish(),TokenGates:z.array(hd).nullish()}).passthrough(),_a=z.object({SystemState:VD.nullish(),Networks:z.record(z.string(),_D).nullish(),AccountSafety:jD.nullish(),WalletLogin:KD.nullish(),PlayAccess:HD.nullish(),IframeConnectHosts:z.array(z.string()).nullish()}).passthrough(),$D=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),LinkedAt:u.nullish(),LastUsedAt:u.nullish(),LinkType:MD.nullish(),IsSignatureVerified:z.boolean().nullish()}).passthrough(),dd=z.object({TitleTransactionID:z.string().nullish(),Type:ld.nullish(),NetworkID:z.string().nullish(),AssetID:z.string().nullish(),Amount:ie.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),JD=z.object({Status:qD.nullish(),Tier:LD.nullish(),VerifiedAt:u.nullish(),ExpiresAt:u.nullish(),RejectedAt:u.nullish(),ProviderReference:z.string().nullish(),RejectionReason:z.string().nullish()}).passthrough(),ZD=z.object({CurrencyID:z.string().nullish(),Deposits:z.number().nullish(),DepositsVolumeNative:ie.nullish(),DepositsVolumeUsd:ie.nullish(),Withdrawals:z.number().nullish(),WithdrawalsVolumeNative:ie.nullish(),WithdrawalsVolumeUsd:ie.nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),YD=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),TotalDepositsVolumeUsd:ie.nullish(),TotalWithdrawalsVolumeUsd:ie.nullish(),PerCurrency:z.record(z.string(),ZD).nullish()}).passthrough(),XD=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:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),eI=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),PerCollection:z.record(z.string(),XD).nullish()}).passthrough(),tI=z.object({Tokens:YD.nullish(),Nfts:eI.nullish()}).passthrough(),Va=z.object({CurrencyID:z.string().nullish(),Balance:ie.nullish(),MinBalance:ie.nullish()}).passthrough(),Xt=z.object({Granted:z.boolean(),Mode:Xn.nullish(),Error:z.string().nullish(),WalletRequired:z.boolean().nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),GrantedUntil:u.nullish(),Balances:z.array(Va).nullish()}).passthrough(),nI=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:u.nullish(),Passed:z.boolean().nullish(),GrantedUntil:u.nullish(),Error:z.string().nullish(),Balances:z.array(Va).nullish()}).passthrough(),iI=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CanUnlink:z.boolean().nullish()}).passthrough(),md=z.object({Mode:Xn.nullish(),TokenGates:z.array(hd).nullish(),WalletLoginEnabled:z.boolean().nullish(),CanLinkWallet:z.boolean().nullish(),WalletsFromPlatformProfile:z.boolean().nullish(),LinkedWallets:z.array(iI).nullish(),Status:Xt.nullish()}).passthrough(),sI=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:u.nullish(),LoggedInAt:u.nullish(),GatePassed:z.boolean().nullish(),GatedBalances:z.array(Va).nullish()}).passthrough(),rI=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),UnlinkedAt:u.nullish()}).passthrough(),oI=z.object({Version:z.number().nullish(),Stats:tI.nullish(),LinkedWallets:z.record(z.string(),$D).nullish(),LastWalletLogin:sI.nullish(),PlayAccess:nI.nullish(),PendingWithdrawals:z.array(dd).nullish(),Kyc:JD.nullish(),FirstActivityAt:u.nullish(),LastActivityAt:u.nullish(),IsFlagged:z.boolean().nullish(),FlagReason:z.string().nullish(),UnlinkedWallets:z.array(rI).nullish()}).passthrough(),aI=z.object({CurrencyID:z.string(),AmountDelta:ie,FrozenDelta:ie,UpdatedAt:u}).passthrough(),zn=z.object({CryptoBalances:z.record(z.string(),aI).nullish(),PendingAdded:dd.nullish(),PendingRemovedIDs:z.array(z.string()).nullish()}).passthrough(),lI=z.object({Amount:ie,Frozen:ie,CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough().transform(o=>o),uI=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.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:cd.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:ie.nullish(),Status:Na.nullish(),SignatureData:z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),TokenID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountUsd:ie.nullish(),NetPayoutAmount:ie.nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:u.nullish(),BurnAmount:z.number().nullish(),RefundedAt:u.nullish(),RefundCheckedAt:u.nullish()}).passthrough(),cI=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.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:cd.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:ie.nullish(),Status:Na.nullish(),SignatureData:z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.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:u.nullish()}).passthrough(),fd=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),ja=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(fd).nullish(),Signature:z.string().nullish()}).passthrough(),Fa=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(fd).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(),gd=z.object({Blockchain:_a.nullish(),CryptoCurrencies:z.record(z.string(),ya).nullish()}).passthrough(),yd=z.object({State:oI.nullish(),CryptoBalances:z.record(z.string(),lI).nullish()}).passthrough(),Rd=z.object({ServerTimeUtc:u.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:ie.nullish(),AmountUsd:ie.nullish(),StateDelta:zn.nullish()}).passthrough(),Cd=z.object({ServerTimeUtc:u.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:O.nullish(),Inventory:Q.nullish()}).passthrough(),Sd=z.object({ServerTimeUtc:u.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:ie.nullish(),NetAmountNative:ie.nullish(),BurnAmountNative:ie.nullish(),AmountUsd:ie.nullish(),ExpiresAt:u.nullish(),EvmSignature:ja.nullish(),SolanaSignature:Fa.nullish(),StateDelta:zn.nullish(),ChainID:z.number().nullish()}).passthrough(),xd=z.object({ServerTimeUtc:u.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:u.nullish(),Resources:O.nullish(),EvmSignature:ja.nullish(),SolanaSignature:Fa.nullish(),StateDelta:zn.nullish(),Inventory:Q.nullish()}).passthrough(),bd=z.object({TokenTransactions:z.array(uI).nullish(),NFTTransactions:z.array(cI).nullish(),RefundedIDs:z.array(z.string()).nullish()}).passthrough(),Wa=z.object({ServerTimeUtc:u.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:ie.nullish(),AmountUsd:ie.nullish(),Target:z.string().nullish()}).passthrough(),Dd=z.object({TitleTransactionID:z.string().nullish(),Kind:ld.nullish(),EvmSignature:ja.nullish(),SolanaSignature:Fa.nullish()}).passthrough(),Id=z.object({TitleTransactionID:z.string().nullish(),OnChainTxHash:z.string().nullish(),Status:Na.nullish(),StateDelta:zn.nullish()}).passthrough(),it={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",DepositToken:"DepositToken",DepositNFT:"DepositNFT",RequestTokenWithdrawal:"RequestTokenWithdrawal",RequestNFTWithdrawal:"RequestNFTWithdrawal",GetTransactionHistory:"GetTransactionHistory",RetryWithdrawal:"RetryWithdrawal",ConfirmWithdrawal:"ConfirmWithdrawal",DonateToDeveloper:"DonateToDeveloper",DonateToUsersPool:"DonateToUsersPool",GetPlayAccess:"GetPlayAccess",ConfirmPlayAccess:"ConfirmPlayAccess"};var pI="Blockchain",Pd="Blockchain:Definitions",ur=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Pd,e);if(t)return a$1(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let n=this.ctx.authedRequest();if(!n)return c;let i=this.ctx.api.blockchain.getDefinitions(n).then(s=>(s.ok&&(this.ctx.data.config.patchSection(pI,s.data.Blockchain),this.ctx.data.config.patchSection(Pd,s.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",s.data)),s)).finally(()=>{this.definitionsInflight===i&&(this.definitionsInflight=null);});return this.definitionsInflight=i,i}async getUserState(){let e=this.ctx.authedRequest();if(!e)return 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 n=this.ctx.authedRequest();if(!n)return c;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.depositToken(n);return i.ok&&(this.ctx.data.user.applyBlockchainStateDelta(i.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",i.data)),i}async depositNFT(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return c;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.depositNFT(n);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",i.data)),i}async requestTokenWithdrawal(e,t,n,i,s){if(!e)return b("client","CurrencyID is required.");if(!t)return b("client","NetworkID is required.");if(!n)return b("client","WalletAddress is required.");if(!i)return b("client","Amount is required.");let r=this.ctx.authedRequest();if(!r)return c;r.CurrencyID=e,r.NetworkID=t,r.WalletAddress=n,r.Amount=i,r.Category=lr(s);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,n,i,s,r,p){if(!e)return b("client","ItemID is required.");if(!t)return b("client","NetworkID is required.");if(!n)return b("client","WalletAddress is required.");if(!i)return b("client","Amount is required.");let m=this.ctx.authedRequest();if(!m)return c;m.ItemID=e,m.NetworkID=t,m.WalletAddress=n,m.Amount=i,m.Category=lr(s),r!==void 0&&(m.Level=r),p&&(m.ItemInstanceID=p);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(m);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 n=await this.ctx.api.blockchain.getTransactionHistory(t);return n.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",n.data),n}async retryWithdrawal(e){if(!e)return b("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.TitleTransactionID=e;let n=await this.ctx.api.blockchain.retryWithdrawal(t);return n.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",n.data),n}async confirmWithdrawal(e,t){if(!e)return b("client","TitleTransactionID is required.");if(!t)return b("client","On-chain TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return c;n.TitleTransactionID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.confirmWithdrawal(n);return i.ok&&(this.ctx.data.user.applyBlockchainStateDelta(i.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",i.data)),i}async donateToDeveloper(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return c;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.donateToDeveloper(n);return i.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",i.data),i}async donateToUsersPool(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return c;n.NetworkID=e,n.TransactionHash=t;let i=await this.ctx.api.blockchain.donateToUsersPool(n);return i.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",i.data),i}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return 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 n=await this.ctx.api.blockchain.confirmPlayAccess(t);return n.ok&&this.ctx.auth.setPlayAccess(n.data),n}};var hI={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Ka=z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),dI={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Qa=z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),mI={Burn:"Burn",Ledger:"Ledger"},fI=z.enum(["Burn","Ledger"]).catch("Burn"),pr={Item:"Item",VirtualCurrency:"VirtualCurrency"},Ha=z.enum(["Item","VirtualCurrency"]).catch("Item"),gI=z.object({Percent:z.number().nullish(),MinPerPosition:H.nullish()}).passthrough(),hr=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Hn).nullish(),MaxPositions:z.number().nullish()}).passthrough(),$a=z.object({Percent:z.number().nullish(),MinPerPosition:H.nullish(),Sink:fI.nullish(),LedgerAccountID:z.string().nullish(),PerCatalogOverrides:z.record(z.string(),gI).nullish(),ApplyToDirectTrades:z.boolean().nullish()}).passthrough(),yI=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(),RI=z.object({Enabled:z.boolean().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),MaxActiveListings:z.number().nullish(),CreateLimits:Pe.nullish(),BuyLimits:Pe.nullish(),ListingFeeOptions:de.nullish(),RefundListingFeeOnCancel:z.boolean().nullish()}).passthrough(),CI=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:H.nullish(),BidLimits:Pe.nullish()}).passthrough(),SI=z.object({Enabled:z.boolean().nullish(),MaxActiveOrders:z.number().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),CreateLimits:Pe.nullish(),FillLimits:Pe.nullish()}).passthrough(),xI=z.object({Enabled:z.boolean().nullish(),OfferExpirationHours:z.number().nullish(),MaxPendingOutgoing:z.number().nullish(),AllowGifts:z.boolean().nullish(),CreateLimits:Pe.nullish()}).passthrough(),bI=z.object({Enabled:z.boolean().nullish()}).passthrough(),Ja=z.object({Enabled:z.boolean().nullish(),Gate:te.nullish(),Schedule:Ce.nullish(),PricePolicy:hr.nullish(),Commission:$a.nullish(),Tradability:yI.nullish(),Listings:RI.nullish(),Auctions:CI.nullish(),BuyOrders:SI.nullish(),DirectTrades:xI.nullish(),Matching:bI.nullish()}).passthrough(),vd=z.object({BidIndex:z.number().nullish(),UserID:z.string().nullish(),Amount:H.nullish(),Settled:z.boolean().nullish(),SettledAt:u.nullish()}).passthrough(),DI=z.object({BidAxisType:i.nullish(),BidCurrencyID:z.string().nullish(),BidCatalogID:z.string().nullish(),BidItemID:z.string().nullish(),StartingBid:H.nullish(),CurrentBid:H.nullish(),CurrentBidderID:z.string().nullish(),BidCount:z.number().nullish(),ExtensionCount:z.number().nullish(),PendingRefunds:z.array(vd).nullish()}).passthrough(),cr=z.object({LastAt:u.nullish(),DailyCount:z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),II=z.object({Create:cr.nullish(),Buy:cr.nullish(),Sell:cr.nullish(),Bid:cr.nullish()}).passthrough(),PI=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),vI=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:u,ExpiresAt:u.nullish(),EquippedSlot:PI.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Vt=z.object({OfferID:z.string().nullish(),OfferType:Ka.nullish(),Status:Qa.nullish(),CreatorUserID:z.string().nullish(),CreatorPublicData:Ge.nullish(),TargetUserID:z.string().nullish(),GoodsType:Ha.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:H.nullish(),GoodsInstances:z.array(vI).nullish(),Price:pe.nullish(),Auction:DI.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),AI=z.object({GoodsType:Ha.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),CountsByType:z.partialRecord(Ka,H).nullish()}).passthrough(),Ad=z.object({Definitions:Ja.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish()}).passthrough(),Za=z.object({Offers:z.array(Vt).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Td=z.object({Groups:z.array(AI).nullish()}).passthrough(),wd=z.object({Offer:Vt.nullish()}).passthrough(),Rt=z.object({OfferID:z.string().nullish(),Status:Qa.nullish(),Settlement:Lt.nullish(),Resources:O.nullish(),CommissionTaken:pe.nullish(),HeldPayout:yt.nullish()}).passthrough(),ei=z.object({OfferID:z.string().nullish(),Offer:Vt.nullish(),Resources:O.nullish(),Matched:z.boolean().nullish(),Settlement:Rt.nullish()}).passthrough(),zd=z.object({OfferID:z.string().nullish(),CurrentBid:H.nullish(),BidCount:z.number().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish()}).passthrough(),dr=z.object({MyOffers:z.array(Vt).nullish(),MyBids:z.array(Vt).nullish(),MyBuyOrders:z.array(Vt).nullish(),IncomingTrades:z.array(Vt).nullish(),OutgoingTrades:z.array(Vt).nullish(),Claimables:z.array(Vt).nullish(),DrainedRefunds:z.array(vd).nullish(),Limits:II.nullish(),PendingPayouts:z.array(yt).nullish(),ReleasedPayouts:z.array(yt).nullish(),VoidedPayouts:z.array(yt).nullish(),PayoutOperations:z.array(O).nullish()}).passthrough(),TI=z.object({OfferID:z.string().nullish(),OfferType:Ka.nullish(),FinalStatus:Qa.nullish(),SellerUserID:z.string().nullish(),BuyerUserID:z.string().nullish(),GoodsType:Ha.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:H.nullish(),PricePaid:pe.nullish(),CommissionTaken:pe.nullish(),CompletedAt:u.nullish(),MyRole:z.string().nullish()}).passthrough(),kd=z.object({Entries:z.array(TI).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Be={GetDefinitions:"GetDefinitions",GetGroupedOffers:"GetGroupedOffers",GetOffersByItem:"GetOffersByItem",GetOffer:"GetOffer",GetBuyOrders:"GetBuyOrders",GetMyState:"GetMyState",GetHistory:"GetHistory",CreateListing:"CreateListing",CancelListing:"CancelListing",Buy:"Buy",MarketBuy:"MarketBuy",MarketSell:"MarketSell",CreateAuction:"CreateAuction",PlaceBid:"PlaceBid",ClaimAuction:"ClaimAuction",CreateBuyOrder:"CreateBuyOrder",CancelBuyOrder:"CancelBuyOrder",FillBuyOrder:"FillBuyOrder",CreateDirectTrade:"CreateDirectTrade",RespondDirectTrade:"RespondDirectTrade",CancelDirectTrade:"CancelDirectTrade",ClaimBack:"ClaimBack"};var wI="Marketplace",Md={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"]},mr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Md,{schema:dr,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(wI,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,n,i=20){if(!e)return b("client","ItemID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.ItemID=e,s.OfferTypeFilter=t,s.ContinuationToken=n,s.PageSize=i;let r=await this.ctx.api.marketplace.getOffersByItem(s);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;t.OfferID=e;let n=await this.ctx.api.marketplace.getOffer(t);return n.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",n.data),n}async getBuyOrders(e,t,n=20){let i=this.ctx.authedRequest();if(!i)return c;i.ItemID=e,i.ContinuationToken=t,i.PageSize=n;let s=await this.ctx.api.marketplace.getBuyOrders(i);return s.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",s.data),s}getMyState(e,t){return this.ctx.cache.read(Md,()=>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 n=await this.ctx.api.marketplace.getMyState(t);if(n.ok){for(let i of n.data.PayoutOperations??[])this.ctx.data.user.applyResourceOperation(i,this.ctx.data.config.itemDefinitions);this.applyMyState(n.data);}return n}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,n){let i=this.ctx.authedRequest();if(!i)return c;n&&(i.HistoryFilter=n),i.ContinuationToken=e,i.PageSize=t;let s=await this.ctx.api.marketplace.getHistory(i);return s.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",s.data),s}async createListing(e,t,n,i,s,r,p){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!i)return b("client","PriceBundle is required.");let m=this.ctx.authedRequest();if(!m)return c;m.ItemID=e,m.CatalogID=t,m.GoodsAmount=n,m.PriceBundle=i,m.DurationHours=s,m.ItemInstanceIDs=r,m.SelectedOptionID=p;let R=await this.ctx.api.marketplace.createListing(m);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 n=await this.ctx.api.marketplace.buy(t);return n.ok&&(this.applyDualPartySettlement(n.data.Settlement),this.ctx.emitter.emit("marketplace:bought",n.data)),n}async marketBuy(e,t,n){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let i=this.ctx.authedRequest();if(!i)return c;let s=this.applyGoodsSelector(i,n);if(s)return s;i.GoodsAmount=e,i.PriceBundle=t;let r=await this.ctx.api.marketplace.marketBuy(i);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",r.data)),r}async marketSell(e,t,n){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let i=this.ctx.authedRequest();if(!i)return c;let s=this.applyGoodsSelector(i,n);if(s)return s;i.GoodsAmount=e,i.PriceBundle=t;let r=await this.ctx.api.marketplace.marketSell(i);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",r.data)),r}async createAuction(e,t,n,i,s,r,p={}){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");let m=this.ctx.authedRequest();if(!m)return c;m.ItemID=e,m.CatalogID=t,m.GoodsAmount=n,m.BidAxisType=i,m.BidCurrencyID=p.bidCurrencyID,m.BidCatalogID=p.bidCatalogID,m.BidItemID=p.bidItemID,m.StartingBid=s,m.DurationHours=r,m.ItemInstanceIDs=p.itemInstanceIDs,m.SelectedOptionID=p.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(m);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 n=this.ctx.authedRequest();if(!n)return c;n.OfferID=e,n.BidAmount=t;let i=await this.ctx.api.marketplace.placeBid(n);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",i.data)),i}async claimAuction(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.OfferID=e;let n=await this.ctx.api.marketplace.claimAuction(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",n.data)),n}async createBuyOrder(e,t,n,i,s){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!i)return b("client","PriceBundle is required.");let r=this.ctx.authedRequest();if(!r)return c;r.ItemID=e,r.CatalogID=t,r.GoodsAmount=n,r.PriceBundle=i,r.DurationHours=s;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;t.OfferID=e;let n=await this.ctx.api.marketplace.fillBuyOrder(t);return n.ok&&(this.applyDualPartySettlement(n.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",n.data)),n}async createDirectTrade(e,t,n,i,s){if(!e)return b("client","TargetUserID is required.");if(!t)return b("client","CatalogID is required.");if(!n)return b("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return c;r.TargetUserID=e,r.CatalogID=t,r.ItemID=n,r.ItemInstanceIDs=i,r.RequestedBundle=s;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 n=this.ctx.authedRequest();if(!n)return c;n.OfferID=e,n.Accept=t;let i=await this.ctx.api.marketplace.respondDirectTrade(n);return i.ok&&(t&&(i.data.Settlement?this.applyDualPartySettlement(i.data.Settlement):i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",i.data)),i}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return c;t.OfferID=e;let n=await this.ctx.api.marketplace.claimBack(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",n.data)),n}async cancelOffer(e,t,n){if(!e)return b("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.OfferID=e;let s=await t(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(n,s.data)),s}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=pr.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=pr.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 n=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,n):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,n);}};var fr=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return b("client","RoomName is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomName=e,n.Topology=t.topology,n.ChatMode=t.chatMode,n.MaxPlayers=t.maxPlayers,n.Visibility=t.visibility,n.JoinCode=t.joinCode,n.Mode=t.mode,n.Voice=t.voice;let i=await this.ctx.api.multiplayer.createRoom(n);return i.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",i.data),i}async joinRoom(e,t){if(!e)return b("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.JoinCode=t;let i=await this.ctx.api.multiplayer.joinRoom(n);return i.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",i.data),i}async leaveRoom(e,t={}){if(!e)return b("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.SuccessorUserID=t.successorUserID;let i=await this.ctx.api.multiplayer.leaveRoom(n,t.keepalive??false);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",i.data),i}async claimHost(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.RoomID=e;let n=await this.ctx.api.multiplayer.claimHost(t);return n.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",n.data),n}async kickMember(e,t,n=false){if(!e)return 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,i.Ban=n;let s=await this.ctx.api.multiplayer.kickMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",s.data),s}async unbanMember(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.TargetUserID=t;let i=await this.ctx.api.multiplayer.unbanMember(n);return i.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",i.data),i}async listRooms(e=0,t=20){let n=this.ctx.authedRequest();if(!n)return c;n.Page=e,n.PageSize=t;let i=await this.ctx.api.multiplayer.listRooms(n);return i.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",i.data),i}async getRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.RoomID=e;let n=await this.ctx.api.multiplayer.getRoom(t);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",n.data),n}async closeRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;t.RoomID=e;let n=await this.ctx.api.multiplayer.closeRoom(t);return n.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",n.data),n}async poll(e,t){if(!e)return b("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.LastSeq=t;let i=await this.ctx.api.multiplayer.poll(n);return i.ok&&this.ctx.emitter.emit("multiplayer:polled",i.data),i}async sendSignal(e,t,n,i){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");if(!n)return b("client","SignalKind is required.");let s=this.ctx.authedRequest();if(!s)return c;s.RoomID=e,s.TargetUserID=t,s.SignalKind=n,s.Payload=i;let r=await this.ctx.api.multiplayer.sendSignal(s);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 n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.ChatText=t;let i=await this.ctx.api.multiplayer.sendChat(n);return i.ok&&this.ctx.emitter.emit("multiplayer:chatSent",i.data),i}async setMemberState(e,t,n){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.Ready=t,i.MemberState=n;let s=await this.ctx.api.multiplayer.setMemberState(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",s.data),s}};var Od=" (if the network is fine, the storage bucket has no CORS rule for this origin)",gr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return 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,n){if(!e)return b("client","CreatorUserID is required.");let i=this.ctx.authedRequest();return i?(i.CreatorUserID=e,i.ContinuationToken=t,i.PageSize=n,this.ctx.api.workshop.getCreatorProfile(i)):c}async publish(e){if(!e.files||e.files.length===0)return b("client","At least one file is required.");let t=new Map,n=e.files.map((m,R)=>{if("sourceAssetUrl"in m)return {Role:m.role,ContentType:m.contentType,SourceAssetUrl:m.sourceAssetUrl};let W=Ed(m.data,m.contentType);return t.set(R,W),{Role:m.role,ContentType:m.contentType,Size:W.size}}),i=e.thumbnail?Ed(e.thumbnail.data,e.thumbnail.contentType):null,s=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:n,Thumbnail:e.thumbnail&&i?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:i.size}:void 0});if(!s.ok)return s;let r=s.data.Uploads??[];for(let m=0;m<r.length;m++){let R=r[m];if(!R||R.ServerCopy||!R.Url)continue;let W=t.get(m);if(!W)return b("client",`No bytes for file #${m+1}.`);let fe=await this.putBytes(R.Url,W,R.ContentType??W.type);if(!fe.ok)return fe}let p=s.data.ThumbnailUpload;if(p?.Url&&i){let m=await this.putBytes(p.Url,i,p.ContentType??i.type);if(!m.ok)return m}return this.ctx.credits.pay(m=>this.publishUploaded({CreditsConfirmationID:m,ContentID:s.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID}),e.credits)}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):c}async publishUploaded(e){if(!e.ContentID)return b("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return c;let n=await this.ctx.api.workshop.publish({...t,...e});return n.ok&&!n.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",n.data)),n}async updateContent(e,t){let n=this.contentRequest(e);if("ok"in n)return n;n.Title=t.title,n.Description=t.description,n.Tags=t.tags,n.Metadata=t.metadata,n.Visibility=t.visibility,n.Access=t.access;let i=await this.ctx.api.workshop.updateContent(n);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let n=await this.ctx.api.workshop.unpublish(t);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async getMyContent(e,t,n){let i=this.ctx.authedRequest();return i?(i.ContentType=e,i.ContinuationToken=t,i.PageSize=n,this.ctx.api.workshop.getMyContent(i)):c}async acquire(e,t){let n=this.contentRequest(e);if("ok"in n)return n;n.OptionID=t?.OptionID??void 0,n.ExpectedPrice=t?.Price??void 0;let i=await this.ctx.api.workshop.acquire(n);return i.ok&&(i.data.Settlement?this.applyDualPartySettlement(i.data.Settlement):this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",i.data)),i}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let n=[];for(let i of t.data.Files??[])if(i.Url)try{let s=await this.ctx.fetchImpl(i.Url);if(!s.ok)return b("connection",`Download failed (HTTP ${s.status}).`);n.push({role:i.Role??"main",contentType:i.ContentType??"application/octet-stream",data:await s.arrayBuffer()});}catch(s){return b("connection",`Download failed: ${s instanceof Error?s.message:String(s)}${Od}`)}return a$1({download:t.data,files:n})}async getMyLicenses(e,t){let n=this.ctx.authedRequest();return n?(n.ContinuationToken=e,n.PageSize=t,this.ctx.api.workshop.getMyLicenses(n)):c}async getMyFavorites(e,t){let n=this.ctx.authedRequest();return n?(n.ContinuationToken=e,n.PageSize=t,this.ctx.api.workshop.getMyFavorites(n)):c}async putBytes(e,t,n){try{let i=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":n},body:t});return i.ok?a$1(!0):b("connection",`Upload failed (HTTP ${i.status}).`)}catch(i){return b("connection",`Upload failed: ${i instanceof Error?i.message:String(i)}${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 n=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,n):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,n);}};function Ed(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 zI={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},kI=z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),MI={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},qd=z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),OI={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Ud=z.enum(["Everyone","Owner","Server"]).catch("Everyone"),EI={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},qI=z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),UI={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},LI=z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),BI={Count:"Count",Sum:"Sum"},GI=z.enum(["Count","Sum"]).catch("Count"),NI={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},_I=z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),VI={Strict:"Strict",Loose:"Loose"},jI=z.enum(["Strict","Loose"]).catch("Strict"),FI=z.object({Kind:LI,Collection:z.string().nullish(),Validate:z.boolean().nullish()}),WI=z.object({Type:qd,ItemType:qd.nullish(),Ref:FI.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()}),KI=z.object({ID:z.string(),Components:z.array(z.object({Field:z.string(),Descending:z.boolean().optional()})).default([])}),yr=z.object({Mode:qI,Role:z.string().nullish(),MembersField:z.string().nullish()}),QI=z.object({Read:z.array(yr).nullish(),Create:z.array(yr).nullish(),Update:z.array(yr).nullish(),Delete:z.array(yr).nullish()}),Ya=z.object({Cost:pe.nullish(),Grant:pe.nullish()}),HI=z.object({ID:z.string(),SortKey:z.string(),PartitionField:z.string().nullish(),PageSize:z.number().optional(),MaxItems:z.number().optional(),PublishItems:z.boolean().optional()}),$I=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:kI,Mode:jI.optional(),SchemaVersion:z.number().optional(),Fields:z.record(z.string(),WI).nullish(),SortKeys:z.array(KI).nullish(),Access:QI.nullish(),Limits:z.object({MaxItemBytes:z.number().nullish(),MaxItemsPerOwner:z.number().nullish(),TtlSeconds:z.number().nullish()}).nullish(),OnOwnerDeleted:_I.optional(),Counters:z.array(z.object({ID:z.string(),Kind:GI,SumField:z.string().nullish(),GroupBy:z.string().nullish(),Visibility:Ud.optional()})).nullish(),Economy:z.object({OnCreate:Ya.nullish(),OnUpdate:Ya.nullish(),OnDelete:Ya.nullish()}).nullish(),WriteGate:te.nullish(),PublicViews:z.array(HI).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()}),Ld=z.object({Enabled:z.boolean().optional(),Collections:z.record(z.string(),$I).default({})}),JI=z.object({FileID:z.string(),Url:z.string(),ContentType:z.string().nullish(),Size:z.number()}),Bd=z.object({FileID:z.string(),UploadUrl:z.string(),ContentType:z.string(),MaxBytes:z.number(),ExpiresAt:z.string()}),kn=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(),JI).nullish()}),Xa=z.object({Item:kn}),Gd=z.object({Items:z.array(kn).default([]),Missing:z.array(z.string()).default([])}),el=z.object({Items:z.array(kn).default([]),NextCursor:z.string().nullish()}),Nd=z.object({Count:z.number(),Capped:z.boolean().optional()}),tl=z.object({Item:kn,AlreadyExists:z.boolean().optional(),Economy:O.nullish()}),_d=z.object({ItemID:z.string(),Deleted:z.boolean(),Economy:O.nullish()}),Vd=z.object({CounterID:z.string(),Group:z.unknown().optional(),Value:z.number()}),jd=z.object({Results:z.array(z.object({Op:z.string(),Collection:z.string(),ItemID:z.string(),Item:kn.nullish(),Deleted:z.boolean().optional()})).default([])}),Fd=z.object({Roles:z.array(z.string()).default([])}),Wd=z.object({Views:z.record(z.string(),z.string()).default({}),ItemUrlTemplate:z.string().nullish()}),Kd=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({})}),Qd=z.object({Page:z.number(),HasMore:z.boolean(),Items:z.array(kn).default([])}),ZI={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 YI=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Jd=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,il=100,Hd=25,$d=100;function XI(o,e,t){return {Field:o,Op:e,Value:t}}var Rr=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,n={}){let i=pt(e)??ti(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.get({...s,Collection:e,ItemID:t,Expand:n.expand}))}getMany(e,t,n={}){let i=pt(e);if(i)return Promise.resolve(i);let s=[...new Set(t.filter(r=>Jd.test(r)))];return s.length?s.length>$d?Promise.resolve(b("client",`At most ${$d} ids per call.`)):this.call(r=>this.ctx.api.dataCollections.getMany({...r,Collection:e,ItemIDs:s,Expand:n.expand})):Promise.resolve(b("client","At least one valid item id is required."))}query(e,t={},n={}){let i=pt(e)??nl(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.query({...s,Collection:e,Query:t,Expand:n.expand}))}async queryAll(e,t={},n={}){let i=Math.max(1,n.maxItems??500),s=[],r=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:r,Limit:t.Limit??il},n);if(!p.ok)return p;if(s.push(...p.data.Items),r=p.data.NextCursor??void 0,!r||s.length>=i)return a$1(s.slice(0,i))}}count(e,t={}){let n=pt(e)??nl(t);return n?Promise.resolve(n):this.call(i=>this.ctx.api.dataCollections.count({...i,Collection:e,Query:t}))}create(e,t,n={}){let i=pt(e)??(n.itemID?ti(n.itemID):null);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.create({...s,Collection:e,ItemID:n.itemID,Data:t}))}update(e,t,n,i={}){let s=pt(e)??ti(t);return s?Promise.resolve(s):this.call(r=>this.ctx.api.dataCollections.update({...r,Collection:e,ItemID:t,Update:n,ExpectedVersion:i.expectedVersion}))}set(e,t,n,i={}){return this.update(e,t,{Set:n},i)}increment(e,t,n,i=1){return this.update(e,t,{Inc:{[n]:i}})}delete(e,t,n={}){let i=pt(e)??ti(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.delete({...s,Collection:e,ItemID:t,ExpectedVersion:n.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(b("client","Operations are empty."));if(e.length>Hd)return Promise.resolve(b("client",`At most ${Hd} operations per batch.`));let t=e.map(n=>pt(n.Collection)).find(n=>n!=null);return t?Promise.resolve(t):this.call(n=>this.ctx.api.dataCollections.batch({...n,Operations:e}))}getCounter(e,t,n){let i=pt(e);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.getCounter({...s,Collection:e,CounterID:t,Group:n}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,n,i){let s=pt(e);return s?Promise.resolve(s):t?i>0?this.call(r=>this.ctx.api.dataCollections.beginFileUpload({...r,Collection:e,Field:t,ContentType:n,FileSize:i})):Promise.resolve(b("client","File size must be positive.")):Promise.resolve(b("client","Field is required."))}async uploadFile(e,t,n,i={}){let s=i.contentType||n.type||"application/octet-stream",r=await this.beginFileUpload(e,t,s,n.size);if(!r.ok)return r;let p=await this.putBytes(r.data.UploadUrl,n,r.data.ContentType||s);return p.ok?r:p}async getPublicViews(e){let t=pt(e);if(t)return t;let n=this.publicViews.get(e);if(n)return a$1(n);let i=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return i.ok&&this.publicViews.set(e,i.data),i}async readPublicView(e,t,n={}){let i=await this.getPublicViews(e);if(!i.ok)return i;let s=i.data.Views[t];if(!s)return b("client",`Collection '${e}' has no public view '${t}'.`);let r=await this.fetchJson(s,Kd);if(!r.ok)return r;let p=r.data.Partitions[n.partition??""],m=Math.max(1,n.page??1);if(!p||m>p.Pages)return a$1({pointer:r.data,page:{Page:m,HasMore:false,Items:[]}});let R=await this.fetchJson(`${r.data.BaseUrl}${p.Segment}/page-${m}.json`,Qd);return R.ok?a$1({pointer:r.data,page:R.data}):R}getPublic(e,t){let n=pt(e)??ti(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let n=pt(e)??nl(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(c)}async putBytes(e,t,n){try{let i=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":n},body:t});return i.ok?a$1(!0):b("connection",`Upload failed (HTTP ${i.status}).`)}catch(i){return b("connection",`Upload failed: ${i instanceof Error?i.message:String(i)}`)}}async fetchJson(e,t){let n;try{n=await this.ctx.fetchImpl(e);}catch{return b("connection","Internet Connection Error")}if(!n.ok)return b("server",`CDN answered ${n.status}.`);let i;try{i=await n.json();}catch{return b("server","CDN answer is not JSON.")}let s=t.safeParse(i);return s.success?a$1(s.data):b("server","CDN answer has an unexpected shape.")}};function pt(o){return YI.test(o??"")?null:b("client",`Collection id '${o}' is invalid (letters, digits, '_', '-', ':').`)}function ti(o){return Jd.test(o??"")?null:b("client",`Item id '${o}' is invalid.`)}function nl(o){return o.Limit!=null&&(o.Limit<1||o.Limit>il)?b("client",`Limit must be 1..${il}.`):(o.Where?.length??0)>8?b("client","At most 8 filters per query."):null}var sl={Open:"Open",Declared:"Declared"},eP=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Blocked:z.boolean().nullish(),Highlight:z.number().nullish()}).passthrough(),tP=z.object({ParamName:z.string().nullish(),DisplayName:z.string().nullish()}).passthrough(),Zd=z.object({Enabled:z.boolean().nullish(),EventNaming:z.string().nullish(),Events:z.record(z.string(),eP).nullish(),Dimensions:z.array(tP).nullish(),RetentionDays:z.number().nullish(),AutomaticEvents:z.boolean().nullish()}).passthrough(),en={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Ot={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Cr=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,nP={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},iP=z.object({Index:z.number().nullish(),Name:z.string().nullish(),Reason:z.string().nullish()}).passthrough(),Yd=z.object({Accepted:z.number().nullish(),Dropped:z.array(iP).nullish(),Duplicate:z.boolean().nullish(),Disabled:z.boolean().nullish()}).passthrough(),rl={LogEvents:"LogEvents"};function Xd(o,e=0){let t=o??"",n=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(n){let p=n[1]??"iPhone";return {osName:"iOS",osVersion:(n[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let i=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(i){let p=(i[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:i[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let s=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(s)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(s[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let 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 em(o){let e=typeof navigator>"u"?void 0:navigator,t=Xd(e?.userAgent??"",e?.maxTouchPoints??0),n={};o.appVersion&&(n.AppVersion=o.appVersion),t.osName&&(n.OsName=t.osName),t.osVersion&&(n.OsVersion=t.osVersion),t.deviceCategory&&(n.DeviceCategory=t.deviceCategory),t.deviceModel&&(n.DeviceModel=t.deviceModel);let i=o.locale||e?.language;return i&&(n.Language=i),n}var sP=25,rP=3e4,tm=1800*1e3,nm=500,oP=5,aP=1e3,lP=3600*1e3,im="idos_analytics_queue",ol="idos_analytics_pending",al="idos_analytics_opt_out",sm="idos_analytics_first_open",rm="idos_analytics_last_activity",om="idos_analytics_last_context",am="idos_analytics_owner",Sr=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;stopVisibility=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,n){return typeof e!="string"||!Cr.test(e)?b("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):uP(e)?b("client",`Event name "${e}" uses a reserved prefix (${Ot.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,n,false))}logScreenView(e,t){if(!e)return b("client","screenName is required.");let n={screen_name:e};return t&&(n.screen_class=t),this.enqueue(en.ScreenView,n,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return a$1(null);if(this.config()?.Enabled===false)return this.clear(),a$1(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return a$1(null);this.pending={BatchID:a(),Events:this.queue.splice(0,Ot.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 n=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return n.ok?(this.pending=null,n.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),n.data.Dropped&&n.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",n.data.Dropped),this.ctx.emitter.emit("analytics:flushed",n.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),n):(n.reason!=="throttled"&&t.Attempts++,(n.reason==="validation"||t.Attempts>=oP)&&(this.pending=null),this.persist(),n)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(al);return}this.write(al,"1"),this.clear();}get isEnabled(){return this.read(al)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(am);e&&t&&t!==e&&this.clear(),e&&this.write(am,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},rP),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide),this.beginAutomatic(),this.flush();}async stop(){this.started&&(this.started=false,this.automaticDone=false,this.timer&&clearInterval(this.timer),this.drainTimer&&clearTimeout(this.drainTimer),this.timer=null,this.drainTimer=null,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null,this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),await this.flush());}beginAutomatic(){if(this.automaticDone||!this.started)return;if(this.config()?.Enabled!==true){this.stopWaitingForConfig??=this.ctx.emitter.on("title:publicConfigurationReceived",()=>this.beginAutomatic());return}this.automaticDone=true,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null;let e=Number(this.read(rm)??"0");this.read(sm)||(this.write(sm,new Date().toISOString()),this.enqueue(en.FirstOpen,void 0,void 0,true));let t=this.clientContext(),n=this.readJson(om);n?.AppVersion&&t.AppVersion&&n.AppVersion!==t.AppVersion&&this.enqueue(en.AppUpdate,{previous_app_version:n.AppVersion},void 0,true),n?.OsVersion&&t.OsVersion&&n.OsVersion!==t.OsVersion&&this.enqueue(en.OsUpdate,{previous_os_version:n.OsVersion},void 0,true),this.writeJson(om,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=tm)&&this.enqueue(en.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=e=>{if(!e){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=tm&&this.enqueue(en.SessionStart,void 0,void 0,true),this.hiddenAt=null;};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,n,i){if(!this.isEnabled||this.disabledByServer)return a$1(null);let s=this.config();if(s?.Enabled===false)return a$1(null);if(i&&s?.AutomaticEvents===false)return a$1(null);if(s?.Events?.[e]?.Blocked)return b("client",`Event "${e}" is blocked by the title.`);if(!i&&s?.EventNaming?.toLowerCase()===sl.Declared.toLowerCase()&&!s.Events?.[e])return b("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(n!==void 0&&!Number.isFinite(n))return b("client","value must be a finite number.");let r=cP(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),n!==void 0&&(p.Value=n),this.queue.push(p),this.queue.length>nm&&this.queue.splice(0,this.queue.length-nm),this.touch(),this.persist(),this.started&&this.queue.length>=sP&&this.flush(),a$1(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},aP));}dropStale(){let e=Date.now()-(Ot.maxEventAgeMs-lP);this.queue=this.queue.filter(t=>{let n=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(n)||n>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=em({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(im);Array.isArray(e)&&(this.queue=e.filter(n=>typeof n?.Name=="string").concat(this.queue));let t=this.readJson(ol);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(im,this.queue),this.pending?this.writeJson(ol,this.pending):this.remove(ol);}touch(){this.write(rm,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.host.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.host.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.host.storage.remove(this.key(e));}catch{}}readJson(e){let t=this.read(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}writeJson(e,t){this.write(e,JSON.stringify(t));}};function uP(o){let e=o.toLowerCase();return Ot.reservedPrefixes.some(t=>e.startsWith(t))}function cP(o){if(!o)return {};let e=Object.keys(o);if(e.length===0)return {};if(e.length>Ot.maxParams)return {error:`Too many parameters: ${e.length}, max ${Ot.maxParams}.`};let t={};for(let n of e){if(!Cr.test(n))return {error:`Invalid parameter name "${n}".`};let i=o[n];typeof i=="string"?t[n]=i.length>Ot.maxStringValueLength?i.slice(0,Ot.maxStringValueLength):i:typeof i=="number"?Number.isFinite(i)&&(t[n]=i):typeof i=="boolean"&&(t[n]=i);}return {params:t}}var pP="idos_experiments",xr=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 n=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),n.length>0&&this.ctx.emitter.emit("experiments:changed",n);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,n){let i=this.getParams(e)[t];if(i===void 0)return n;if(typeof n=="number"){let s=Number(i);return i.trim()!==""&&Number.isFinite(s)?s:n}if(typeof n=="boolean"){let s=i.trim().toLowerCase();return s==="true"||s==="1"?true:s==="false"||s==="0"?false:n}return i}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let i of e.Experiments??[])i?.ExperimentID&&t.set(i.ExperimentID,i);let n=[];for(let[i,s]of t){let r=this.views.get(i);(!r||r.VariantID!==s.VariantID||r.Status!==s.Status)&&n.push(s);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,n}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.host.storage.getString(this.key());if(!t)return;let n=JSON.parse(t);n?.UserID===e&&n.Data&&this.apply(n.Data);}catch{}}save(e,t){try{let n={UserID:e,Data:t};this.ctx.host.storage.setString(this.key(),JSON.stringify(n));}catch{}}key(){return `${pP}:${this.ctx.settings.titleID}`}};function tn(o,e,t,n){let s=`api/v2/${o&&o.length>0?o:"0"}/Client/${e}/${t}`;return n==null?s:`${s}/${n}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return tn(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,n,i){return this.ctx.transport.post(this.endpoint(e,t),t,n,{...i,ticket:t.ClientSessionTicket})}};var br=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(rl.LogEvents,e,Yd,{silent:true})}};var hP=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(),dP={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},mP=z.object({MetricID:z.string().nullish(),Kind:z.string().nullish(),EventName:z.string().nullish(),IsPrimary:z.boolean().nullish()}).passthrough(),fP=z.object({ExperimentID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),IsEnabled:z.boolean().nullish(),Schedule:Ce.nullish(),Gate:te.nullish(),Variants:z.array(hP).nullish(),Salt:z.string().nullish(),LayerID:z.string().nullish(),StickyAssignment:z.boolean().nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Goals:z.array(mP).nullish(),ActivationEvent:z.string().nullish(),RolloutVariantID:z.string().nullish()}).passthrough(),lm=z.object({Experiments:z.record(z.string(),fP).nullish()}).passthrough(),gP={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},yP=z.object({ExperimentID:z.string().nullish(),VariantID:z.string().nullish(),Status:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),um=z.object({Experiments:z.array(yP).nullish(),IsAbTestingAvailable:z.boolean().nullish()}).passthrough(),ll={GetExperiments:"GetExperiments"};var Dr=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(ll.GetExperiments,e,um)}};var RP={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},cm=z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),CP=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),IsEnabled:z.boolean().nullish(),Order:z.number().nullish()}).passthrough(),pm=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),Locales:z.record(z.string(),CP).nullish(),MissingKeyMode:cm.nullish(),MaxEntriesPerLocale:z.number().nullish(),MaxValueLengthBytes:z.number().nullish()}).passthrough(),SP=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish()}).passthrough(),hm=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish(),Fallback:SP.nullish()}).passthrough(),Ir={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},xP=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),Order:z.number().nullish(),Version:z.number().nullish()}).passthrough(),dm=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),MissingKeyMode:cm.nullish(),ResolvedLocale:z.string().nullish(),Locales:z.array(xP).nullish()}).passthrough(),mm=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 ni=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:hm.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(),PeerPayouts:wp.nullish()}).passthrough().transform(o=>o),fm=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish()}).passthrough().transform(o=>o),gm=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),User:z.unknown().nullish()}).passthrough().transform(o=>o),ym=z.object({}).passthrough().transform(o=>o),Rm=z.object({}).passthrough().transform(o=>o),Cm=z.object({Today:z.number(),Yesterday:z.number(),CurrentWeek:z.number(),CurrentMonth:z.number(),Total:z.number(),TotalSessions:z.number(),FirstActiveAt:u.nullish(),LastActiveAt:u.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(),Sm=z.object({Username:z.string()}),Ct={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var xm=z.object({PlatformUserID:z.string().nullish(),PlatformAuthToken:z.string().nullish(),PlatformAuthTokenExpiration:u.nullish(),TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:u,PlayAccess:Xt.nullish(),RefreshToken:z.string().nullish(),RefreshTokenExpiration:u.nullish(),ClientState:ni.nullish()}),bm=z.object({TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:u,RefreshToken:z.string(),RefreshTokenExpiration:u.nullish(),PlayAccess:Xt.nullish()}),bP=z.object({ReturnMode:z.string().nullish(),UrlScheme:z.string().nullish(),UserCodeSupported:z.boolean().nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),Dm=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:Xn.nullish(),WalletLoginNetworks:z.array(z.object({NetworkID:z.string().nullish(),Type:z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:z.boolean().nullish(),NativeSso:bP.nullish()}).passthrough(),Im=z.object({Linked:z.boolean().nullish(),Challenge:z.string().nullish(),ExpiresAt:u.nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),PlayAccess:Xt.nullish()}).passthrough(),Pm=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CooldownUntil:u.nullish(),PlayAccess:Xt.nullish()}).passthrough(),vm=z.object({CodeTtlMinutes:z.number().nullish(),ResendCooldownSeconds:z.number().nullish()}),Qe=z.object({IsCompleted:z.boolean().nullish(),ServerTime:u.nullish()}),Am=z.object({Message:z.string(),ExpiresAt:u}),Ke={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 Pr=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return tn(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,xm,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ke.RefreshSession),e,bm,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ke.GetAuthOptions),e,Dm,{ticket:null})}linkWallet(e){return this.ctx.transport.post(tn(this.ctx.settings.titleID,"Authentication",Ke.LinkWallet,e.UserID??""),e,Im,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(tn(this.ctx.settings.titleID,"Authentication",Ke.UnlinkWallet,e.UserID??""),e,Pm,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ke.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ke.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ke.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ke.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ke.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ke.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(Ke.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ke.RegisterWithEmail),e,vm,{ticket:null})}confirmEmailRegistration(e){return this.login(Ke.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ke.ResendVerificationCode),e,Qe,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ke.RequestWalletChallenge),e,Am,{ticket:null})}loginWithWallet(e){return this.login(Ke.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ke.ForgotPassword),e,Qe,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ke.ResetPassword),e,Qe,{ticket:null})}};var vr=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(Ct.GetClientState,e,ni)}getClientStateExcept(e){return this.send(Ct.GetClientStateExcept,e,ni)}getStateVersions(e){return this.send(Ct.GetStateVersions,e,fm)}getUserState(e){return this.send(Ct.GetUserState,e,gm)}getInventory(e){return this.send(Ct.GetInventory,e,ym)}getEventTokens(e){return this.send(Ct.GetEventTokens,e,Rm)}getUsageTime(e){return this.send(Ct.GetUsageTime,e,Cm)}addUsageTime(e){return this.send(Ct.AddUsageTime,e,Qe,{silent:true})}deleteUserAccount(e){return this.send(Ct.DeleteUserAccount,e,Qe)}changeUsername(e){return this.send(Ct.ChangeUsername,e,Sm)}};var Ar=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(Kn.Convert,e,Dp)}spend(e){return this.send(Kn.Spend,e,Pp)}cryptoConvert(e){return this.send(Kn.CryptoConvert,e,Ip)}};var DP=z.object({ItemInstanceID:z.string(),Units:z.number(),Level:z.number()}),ul=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Level:z.number(),Resources:O.nullish(),FodderConsumed:z.array(DP).nullish()}),Tm=z.array(Me(ul)),Tr={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},IP={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},PP=z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),vP={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},AP=z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),TP=z.object({ContractAddress:z.string().nullish(),TokenID:z.string().nullish(),TokenStandard:z.string().nullish(),MaxLevel:z.number().nullish()}).passthrough(),wP=z.object({Networks:z.record(z.string(),TP).nullish(),MetadataUrl:z.string().nullish()}).passthrough(),zP=z.object({FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),kP=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(),MP=z.object({ValuationMode:PP.nullish(),WeightCurve:Je.nullish(),Selection:AP.nullish()}).passthrough(),OP=z.object({MaxLevel:z.number().nullish(),PriceOptions:de.nullish(),CostCurve:Je.nullish(),FlatBonusCurve:Je.nullish(),PercentBonusCurve:Je.nullish(),PowerCurve:Je.nullish(),Fodder:MP.nullish()}).passthrough(),EP=z.object({RarityID:z.string().nullish(),CollectionID:z.string().nullish(),AuthorID:z.string().nullish()}).passthrough(),qP=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:wP.nullish(),Stats:zP.nullish(),Equipment:kP.nullish(),Upgrade:OP.nullish(),Metadata:EP.nullish(),ExpirationDurationSeconds:z.number().nullish(),MaxSupply:z.number().nullish()}).passthrough(),UP=z.object({Items:z.record(z.string(),qP).nullish()}).passthrough(),LP={Cumulative:"Cumulative",HighestOnly:"HighestOnly"},BP=z.enum(["Cumulative","HighestOnly"]).catch("Cumulative"),GP=z.object({Pieces:z.number().nullish(),FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),NP=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BonusMode:z.enum(["Cumulative","HighestOnly"]).nullish().catch(null),Bonuses:z.array(GP).nullish()}).passthrough(),_P=z.object({BonusMode:BP.nullish()}).passthrough(),wr=z.object({Catalogs:z.record(z.string(),UP).nullish(),Sets:z.record(z.string(),NP).nullish(),SetSettings:_P.nullish()}).passthrough();function Te(o){return z.unknown().transform((e,t)=>{let n=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(n!=null){let s=ye.safeParse(n);return s.success?{...e,CreditsConfirmation:s.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${s.error.message}`}),z.NEVER)}let i=o.safeParse(e);return i.success?i.data:(t.addIssue({code:"custom",message:i.error.message}),z.NEVER)})}var zr=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(Tr.UpgradeLevel,e,Te(ul))}upgradeLevelsBatch(e){return this.send(Tr.UpgradeLevelsBatch,e,Tm)}};var kr=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(Gt.Purchase,e,$o)}purchaseBatch(e){return this.send(Gt.PurchaseBatch,e,ku)}getDefinitions(e){return this.send(Gt.GetDefinitions,e,Gi)}getUserState(e){return this.send(Gt.GetUserState,e,Mu)}getStorefront(e){return this.send(Gt.GetStorefront,e,Ni)}getCreditsConfirmation(e){return this.send(Gt.GetCreditsConfirmation,e,ye)}getCreditsBalance(e){return this.send(Gt.GetCreditsBalance,e,zu)}};var VP={Apple:"Apple",Google:"Google"},Mr=z.object({PremiumID:z.string().nullish(),PurchaseDate:z.string().nullish(),ExpirationDate:z.string().nullish(),TransactionID:z.string().nullish(),IsAutoRenewEnabled:z.boolean().nullish()}).passthrough(),Or=z.object({Subscriptions:z.record(z.string(),Mr).nullish(),ActivatedTrialIDs:z.array(z.string()).nullish(),MaxActiveTier:z.number().nullish()}).passthrough().transform(o=>o),jP=z.object({PremiumID:z.string().nullish(),DisplayName:z.string().nullish(),Tier:z.number().nullish(),DurationDays:z.number().nullish(),TrialDurationDays:z.number().nullish(),PriceOptions:de.nullish(),Benefits:z.record(z.string(),z.string()).nullish()}).passthrough(),pl=z.object({Definitions:z.record(z.string(),jP).nullish()}).passthrough(),wm=z.object({Premium:pl.nullish()}),zm=z.object({ServerTimeUtc:u.nullish(),Premium:Or.nullish()}),Er=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),Premium:Or.nullish(),Subscription:Mr.nullish(),Resources:O.nullish()}),pn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var FP={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},WP=z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),km=z.object({StartUtc:u.nullish(),EndUtc:u.nullish(),Gate:te.nullish(),Limits:Pe.nullish()}).passthrough(),hl=z.object({ResourceAction:z.string().nullish(),RevokeEntitlement:z.boolean().nullish(),BlockFuturePurchases:z.boolean().nullish()}).passthrough(),KP=z.object({PremiumID:z.string().nullish(),RenewalRewards:$.nullish(),FallbackDurationDays:z.number().nullish(),RevokeOnRefund:z.boolean().nullish()}).passthrough(),QP=z.object({Rewards:J.nullish(),Rules:J.nullish(),Refund:J.nullish()}).passthrough(),HP=z.object({ProductID:z.string().nullish(),Name:z.string().nullish(),Type:WP.nullish(),Enabled:z.boolean().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish(),Rewards:$.nullish(),PriceUsdCents:z.number().nullish(),TelegramStarsPrice:z.number().nullish(),Rules:km.nullish(),Refund:hl.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Subscription:KP.nullish(),Presets:QP.nullish()}).passthrough(),$P=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(),JP=z.object({Rewards:$.nullish()}).passthrough(),ZP=z.object({Rules:km.nullish()}).passthrough(),YP=z.object({Refund:hl.nullish()}).passthrough(),XP=z.object({Rewards:z.record(z.string(),JP).nullish(),Rules:z.record(z.string(),ZP).nullish(),Refund:z.record(z.string(),YP).nullish()}).passthrough(),ev=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(),tv=z.object({Enabled:z.boolean().nullish(),Products:z.record(z.string(),HP).nullish(),Stores:z.record(z.string(),$P).nullish(),Presets:XP.nullish(),Validation:ev.nullish(),Refund:hl.nullish()}).passthrough(),Mm=z.object({ProductID:z.string().nullish(),TotalPurchases:z.number().nullish(),DailyPurchases:z.number().nullish(),DailyResetUtc:u.nullish(),LastPurchasedAt:u.nullish(),Owned:z.boolean().nullish(),Refunded:z.boolean().nullish(),PurchaseBlocked:z.boolean().nullish(),Store:z.string().nullish(),LastTransactionID:z.string().nullish()}).passthrough(),Om=z.object({ProductID:z.string().nullish(),PremiumID:z.string().nullish(),Store:z.string().nullish(),OriginalTransactionID:z.string().nullish(),LastTransactionID:z.string().nullish(),ExpiresAt:u.nullish(),AutoRenew:z.boolean().nullish(),Status:z.string().nullish(),RenewalCount:z.number().nullish(),LastStoreCheckAt:u.nullish(),LastStoreCheckError:z.string().nullish(),UpdatedAt:u.nullish()}).passthrough(),nv=z.object({Products:z.record(z.string(),Mm).nullish(),LifetimeSpendUsdCents:z.number().nullish(),Subscriptions:z.record(z.string(),Om).nullish(),LastRefundCheckAt:u.nullish(),TotalPurchases:z.number().nullish(),FirstPurchaseAt:u.nullish(),LastPurchaseAt:u.nullish()}).passthrough(),iv=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(),Em=z.object({ServerTimeUtc:u,Purchase:tv.nullish(),Availability:z.array(iv).nullish()}),qm=z.object({ServerTimeUtc:u,Purchase:nv.nullish()}),sv={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},rv=z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),dl=z.object({ServerTimeUtc:u,Store:m.nullish(),ProductID:z.string().nullish(),TransactionID:z.string().nullish(),Status:rv.nullish(),Granted:z.boolean().nullish(),Quantity:z.number().nullish(),Resources:O.nullish(),Inventory:Q.nullish(),ProductState:Mm.nullish(),Premium:Or.nullish(),Subscription:Mr.nullish(),SubscriptionMirror:Om.nullish()}).passthrough(),Um=z.object({ServerTimeUtc:u,ProductID:z.string().nullish(),Stars:z.number().nullish(),InvoiceLink:z.string(),ExpiresAt:u.nullish()}).passthrough(),Lm=wt(dl),hn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var qr=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(hn.GetDefinitions,e,Em)}getUserState(e){return this.send(hn.GetUserState,e,qm)}validatePurchase(e){return this.send(hn.ValidatePurchase,e,dl)}validatePurchasesBatch(e){return this.send(hn.ValidatePurchasesBatch,e,Lm)}createTelegramInvoice(e){return this.send(hn.CreateTelegramInvoice,e,Um)}};var ov=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),Bm=z.object({Reward:$.nullish(),Weight:z.number().nullish(),AmountRange:ov.nullish()}).passthrough(),Mn=z.object({SlotID:z.string().nullish(),MinRolls:z.number().nullish(),MaxRolls:z.number().nullish(),Pool:z.array(Bm).nullish()}).passthrough(),On=z.object({RuleID:z.string().nullish(),Threshold:z.number().nullish(),Pool:z.array(Bm).nullish()}).passthrough(),av=z.object({RewardSlots:z.array(Mn).nullish()}).passthrough(),lv=z.object({PityRules:z.array(On).nullish()}).passthrough(),Ur=z.object({SlotPresets:z.record(z.string(),av).nullish(),PityPresets:z.record(z.string(),lv).nullish()}).passthrough();var uv=z.object({RuleID:z.string(),BoxIndex:z.number().nullish()}),Gm=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,LootboxID:z.string(),OpenedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish(),Results:z.array(O).nullish(),TriggeredPity:z.array(uv).nullish()}),cv=z.object({RewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),pv=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxDrops:H.nullish()}).passthrough(),hv=z.object({LootboxID:z.string(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:de.nullish(),RewardSlots:z.array(Mn).nullish(),PityRules:z.array(On).nullish(),Presets:cv.nullish(),RewardMultiplier:pi.nullish(),SupplyLimits:z.array(pv).nullish(),MaxOpenCount:z.number().nullish()}).passthrough(),dv=z.object({MaxOpenCount:z.number().nullish()}).passthrough(),ml=z.object({Definitions:z.record(z.string(),hv).nullish(),RewardPools:Ur.nullish(),Settings:dv.nullish()}).passthrough(),Nm=z.object({LootboxDefinitions:ml.nullish()}),Lr={GetDefinitions:"GetDefinitions",Open:"Open"};var Br=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(Lr.GetDefinitions,e,Nm)}open(e){return this.send(Lr.Open,e,Te(Gm))}};var mv=z.object({}).passthrough().transform(o=>o),fv=z.object({}).passthrough().transform(o=>o),gv=z.object({}).passthrough().transform(o=>o),yv=z.object({}).passthrough().transform(o=>o),Rv=z.object({}).passthrough().transform(o=>o),Cv=z.object({}).passthrough().transform(o=>o),_m=z.object({ServerTimeUtc:u,CalendarID:z.string(),DayNumber:z.number().nullish(),DailyState:mv,Resources:O.nullish(),Inventory:Q.nullish()}),Vm=z.object({ServerTimeUtc:u,AccrualID:z.string(),AccruedSeconds:H.nullish(),AppliedRatePerSecond:z.number().nullish(),IdleState:fv,Resources:O.nullish(),Inventory:Q.nullish()}),jm=z.object({ServerTimeUtc:u,ComebackID:z.string(),ClaimedTierIndex:z.number().nullish(),ComebackState:gv,Resources:O.nullish(),Inventory:Q.nullish()}),Fm=z.object({ServerTimeUtc:u,ClaimID:z.string(),ClaimState:yv,Resources:O.nullish(),Inventory:Q.nullish()}),Sv={None:"None",Ad:"Ad",Vip:"Vip"},Wm=z.object({ServerTimeUtc:u,WindowID:z.string(),Boost:z.string().nullish(),BaseAmount:H.nullish(),Multiplier:z.number().nullish(),Granted:H.nullish(),WindowState:Rv,Resources:O.nullish(),Inventory:Q.nullish()}),Km=z.object({Enabled:z.boolean(),Multiplier:z.number().nullish(),Progress:H.nullish(),Source:z.string().nullish(),SourceKey:z.string().nullish()}),xv=z.object({RewardMode:z.string().nullish(),RewardStackLowerTiers:z.boolean().nullish()}).passthrough(),bv=z.object({DayNumber:z.number().nullish(),Rewards:$.nullish(),IsMilestone:z.boolean().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),ii=z.object({Gate:te.nullish(),Limits:Pe.nullish()}).passthrough(),fl=z.object({Availability:J.nullish()}).passthrough(),Dv=z.object({Availability:z.record(z.string(),ii).nullish()}).passthrough(),Iv=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(bv).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:ii.nullish(),Presets:fl.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),Pv=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Multiplier:z.number().nullish()}).passthrough(),vv=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(Pv).nullish()}).passthrough(),Av=z.object({MinCharacterLevel:z.number().nullish(),RequirementsCharacterID:z.string().nullish(),Availability:ii.nullish(),RequiredItemIDs:z.array(z.string()).nullish(),RequiredEquippedItemIDs:z.array(z.string()).nullish()}).passthrough(),Tv=z.object({AccrualID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rate:vv.nullish(),Rewards:$.nullish(),MaxAccumulationSeconds:z.number().nullish(),MinClaimSeconds:z.number().nullish(),Requirements:Av.nullish(),FirstClaimMode:z.string().nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),wv=z.object({MinAbsenceSeconds:z.number().nullish(),Rewards:$.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),zv=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(wv).nullish(),ClaimCooldownSeconds:z.number().nullish(),ClaimWindowSeconds:z.number().nullish(),TrackPresenceOnRead:z.boolean().nullish(),Availability:ii.nullish(),Presets:fl.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),kv=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(),Mv=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:$.nullish(),PremiumLimitOverrides:z.array(kv).nullish(),Availability:ii.nullish(),Presets:fl.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),Ov=z.object({CurrencyID:z.string().nullish(),MaxBaseAmount:z.number().nullish(),AdPlacementID:z.string().nullish(),AdMultiplier:z.number().nullish(),VipMultiplier:z.number().nullish(),VipPremiumID:z.string().nullish(),Limits:z.record(z.string(),z.unknown()).nullish()}).passthrough(),gl=z.object({TierRewards:xv.nullish(),MilestoneRewardMultiplier:pi.nullish(),DailyCalendars:z.record(z.string(),Iv).nullish(),IdleAccruals:z.record(z.string(),Tv).nullish(),Comebacks:z.record(z.string(),zv).nullish(),Claims:z.record(z.string(),Mv).nullish(),Windows:z.record(z.string(),Ov).nullish(),Presets:Dv.nullish()}).passthrough(),Qm=z.object({RewardDefinitions:gl.nullish()}),Hm=z.object({Rewards:Cv.nullish()}),Et={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var Gr=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Et.GetRewardDefinitions,e,Qm)}getUserRewardsState(e){return this.send(Et.GetUserRewardsState,e,Hm)}getMilestoneRewardMultiplier(e){return this.send(Et.GetMilestoneRewardMultiplier,e,Km)}claimDailyReward(e){return this.send(Et.ClaimDailyReward,e,_m)}collectIdleAccrual(e){return this.send(Et.CollectIdleAccrual,e,Vm)}claimComebackReward(e){return this.send(Et.ClaimComebackReward,e,jm)}claimReward(e){return this.send(Et.ClaimReward,e,Fm)}claimRewardWindow(e){return this.send(Et.ClaimRewardWindow,e,Wm)}};var Nr=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(mt.GetTutorialDefinitions,e,hu)}getUserTutorialState(e){return this.send(mt.GetUserTutorialState,e,mi)}startFlow(e){return this.send(mt.StartFlow,e,Wt)}reportStepShown(e){return this.send(mt.ReportStepShown,e,Wt)}completeStep(e){return this.send(mt.CompleteStep,e,Wt)}completeStepsBatch(e){return this.send(mt.CompleteStepsBatch,e,fu)}skipStep(e){return this.send(mt.SkipStep,e,Wt)}skipFlow(e){return this.send(mt.SkipFlow,e,Wt)}claimFlowReward(e){return this.send(mt.ClaimFlowReward,e,mu)}resetFlow(e){return this.send(mt.ResetFlow,e,Wt)}};var Ev={Open:"Open",Application:"Application"},qv=z.enum(["Open","Application"]).catch("Open"),Uv={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},$m=z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),Lv={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},yl=z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),Bv={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var dn={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},Gv=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(),Jm=z.object({IsEnabled:z.boolean().nullish(),CreatorPortalUrl:z.string().nullish(),ParticipationMode:qv.nullish(),IsCreator:z.boolean().nullish(),CreatorStatus:$m.nullish(),VerificationCode:z.string().nullish(),TeamID:z.string().nullish(),Campaigns:z.array(Gv).nullish()}).passthrough(),Nv=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(),_v=z.object({CampaignID:z.string().nullish(),CurrencyKind:yl.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(),Nv).nullish(),ComputedAt:z.string().nullish()}).passthrough(),Vv=z.object({PayoutID:z.string().nullish(),CampaignID:z.string().nullish(),Amount:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:yl.nullish(),NetworkID:z.string().nullish(),PaidAt:z.string().nullish()}).passthrough(),Zm=z.object({ServerTimeUtc:z.string().nullish(),HoldDays:z.number().nullish(),Campaigns:z.array(_v).nullish(),Payouts:z.array(Vv).nullish()}).passthrough(),Ym=z.object({CampaignID:z.string().nullish(),PayoutID:z.string().nullish(),Claimed:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:yl.nullish(),NetworkID:z.string().nullish(),RemainingFraction:z.number().nullish(),IdempotentReplay:z.boolean().nullish(),Message:z.string().nullish()}).passthrough(),jv=z.object({To:z.string().nullish(),Amount:z.string().nullish()}).passthrough(),Fv=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(jv).nullish()}).passthrough(),Wv=z.object({Kind:z.string().nullish(),Target:z.string().nullish(),Required:z.number().nullish(),Actual:z.number().nullish(),Passed:z.boolean().nullish()}).passthrough(),Xm=z.object({Passed:z.boolean().nullish(),Approved:z.boolean().nullish(),Status:$m.nullish(),WalletMissing:z.boolean().nullish(),WalletConnectAllowed:z.boolean().nullish(),Conditions:z.array(Wv).nullish()}).passthrough(),Kv=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),Qv=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(Kv).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(),ef=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:Fv.nullish(),SolanaSignature:Qv.nullish(),StateDelta:zn.nullish()}).passthrough();var _r=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(dn.GetCommunityMarketingState,e,Jm)}getEarnings(e){return this.send(dn.GetEarnings,e,Zm)}claim(e){return this.send(dn.Claim,e,Ym)}checkJoinEligibility(e){return this.send(dn.CheckJoinEligibility,e,Xm)}withdrawCryptoReward(e){return this.send(dn.WithdrawCryptoReward,e,ef)}};var Vr=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(tt.GetChatDefinitions,e,Hu)}getChannels(e){return this.send(tt.GetChannels,e,Yi)}poll(e){return this.send(tt.Poll,e,$u)}getHistory(e){return this.send(tt.GetHistory,e,Ju)}getConversations(e){return this.send(tt.GetConversations,e,Xu)}sendMessage(e){return this.send(tt.SendMessage,e,Zu)}openDirectChannel(e){return this.send(tt.OpenDirectChannel,e,Yu)}markRead(e){return this.send(tt.MarkRead,e,An)}joinChannel(e){return this.send(tt.JoinChannel,e,An)}leaveChannel(e){return this.send(tt.LeaveChannel,e,An)}reportMessage(e){return this.send(tt.ReportMessage,e,ec)}ignoreUser(e){return this.send(tt.IgnoreUser,e,An)}unignoreUser(e){return this.send(tt.UnignoreUser,e,An)}};var jr=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(Tn.GetPushConfig,e,ic)}subscribePush(e){return this.send(Tn.SubscribePush,e,Yo)}unsubscribePush(e){return this.send(Tn.UnsubscribePush,e,Qe)}getPushSubscriptions(e){return this.send(Tn.GetPushSubscriptions,e,sc)}};var Fr=class extends B{constructor(e){super(e,"Localization");}send(e,t,n,i){let s=this.endpoint(e,t);return super.send(e,t,n,{throttleKey:t.Locale?`${s}:${t.Locale}`:s,...i})}getLocalizationManifest(e){return this.send(Ir.GetLocalizationManifest,e,dm)}getLocalizationTable(e){return this.send(Ir.GetLocalizationTable,e,mm)}};var Wr=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(Dt.GetQuestDefinitions,e,di)}getUserQuestState(e){return this.send(Dt.GetUserQuestState,e,eu)}refreshQuestCycles(e){return this.send(Dt.RefreshQuestCycles,e,Qe)}claimQuestReward(e){return this.send(Dt.ClaimQuestReward,e,Lo)}claimQuestRewardsBatch(e){return this.send(Dt.ClaimQuestRewardsBatch,e,iu)}claimMilestoneReward(e){return this.send(Dt.ClaimMilestoneReward,e,Bo)}claimMilestoneRewardsBatch(e){return this.send(Dt.ClaimMilestoneRewardsBatch,e,su)}claimGroupCompletionReward(e){return this.send(Dt.ClaimGroupCompletionReward,e,tu)}addQuestProgress(e){return this.send(Dt.AddQuestProgress,e,nu)}};var Kr=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(gt.GetActiveEvents,e,rs)}getDefinitions(e){return this.send(gt.GetDefinitions,e,ss)}getUserLteState(e){return this.send(gt.GetUserLteState,e,lc)}grantTokens(e){return this.send(gt.GrantTokens,e,O)}spendTokens(e){return this.send(gt.SpendTokens,e,ta)}claimMilestone(e){return this.send(gt.ClaimMilestone,e,na)}claimMilestonesBatch(e){return this.send(gt.ClaimMilestonesBatch,e,ia)}claimAllMilestones(e){return this.send(gt.ClaimAllMilestones,e,ia)}spendTokensBatch(e){return this.send(gt.SpendTokensBatch,e,uc)}grantTokensBatch(e){return this.send(gt.GrantTokensBatch,e,cc)}};var Qr=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ze.GetDefinitions,e,hs)}getLeaderboard(e){return this.send(Ze.GetLeaderboard,e,jn)}getMyProgress(e){return this.send(Ze.GetMyProgress,e,as)}submitScore(e){return this.send(Ze.SubmitScore,e,ls)}submitScoreFromSource(e){return this.send(Ze.SubmitScoreFromSource,e,ls)}claimCycleReward(e){return this.send(Ze.ClaimCycleReward,e,us)}claimMilestone(e){return this.send(Ze.ClaimMilestone,e,cs)}getFriendsLeaderboard(e){return this.send(Ze.GetFriendsLeaderboard,e,jn)}getLeaderboardsBatch(e){return this.send(Ze.GetLeaderboardsBatch,e,dc)}getProgressBatch(e){return this.send(Ze.GetProgressBatch,e,ps)}claimCycleRewardsBatch(e){return this.send(Ze.ClaimCycleRewardsBatch,e,mc)}claimMilestonesBatch(e){return this.send(Ze.ClaimMilestonesBatch,e,fc)}submitScoresBatch(e){return this.send(Ze.SubmitScoresBatch,e,gc)}claimAllRewardsBatch(e){return this.send(Ze.ClaimAllRewardsBatch,e,yc)}getOverviewBatch(e){return this.send(Ze.GetOverviewBatch,e,Rc)}};var Hr=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Ht.GetDefinitions,e,fs)}getActiveSeason(e){return this.send(Ht.GetActiveSeason,e,ms)}getUserState(e){return this.send(Ht.GetUserState,e,sa)}grantStatusTokens(e){return this.send(Ht.GrantStatusTokens,e,bc)}claimTierReward(e){return this.send(Ht.ClaimTierReward,e,ra)}claimTierRewardsBatch(e){return this.send(Ht.ClaimTierRewardsBatch,e,Dc)}};var $r=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(pn.GetDefinitions,e,wm)}getUserState(e){return this.send(pn.GetUserState,e,zm)}activateTrial(e){return this.send(pn.ActivateTrial,e,Er)}purchaseItemOrCurrency(e){return this.send(pn.PurchaseWithResources,e,Te(Er))}purchaseRealMoney(e){return this.send(pn.PurchaseRealMoney,e,Er)}};var Jr=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send($e.GetCharacterDefinitions,e,Cs)}getUserCharacters(e){return this.send($e.GetUserCharacters,e,wc)}unlockCharacter(e){return this.send($e.UnlockCharacter,e,Te(la))}upgradeStatLevel(e){return this.send($e.UpgradeStatLevel,e,Te(oa))}upgradeCharacterLevel(e){return this.send($e.UpgradeCharacterLevel,e,Te(aa))}equipItems(e){return this.send($e.EquipItems,e,zc)}unequipItems(e){return this.send($e.UnequipItems,e,kc)}unequipAllCharacters(e){return this.send($e.UnequipAllCharacters,e,Mc)}unlockCharactersBatch(e){return this.send($e.UnlockCharactersBatch,e,Bc)}upgradeCharacterLevelsBatch(e){return this.send($e.UpgradeCharacterLevelsBatch,e,Gc)}upgradeStatLevelsBatch(e){return this.send($e.UpgradeStatLevelsBatch,e,Nc)}unlockSkin(e){return this.send($e.UnlockSkin,e,Te(Oc))}equipSkin(e){return this.send($e.EquipSkin,e,Ec)}unequipSkin(e){return this.send($e.UnequipSkin,e,qc)}getCharacterSkins(e){return this.send($e.GetCharacterSkins,e,Uc)}selectCharacter(e){return this.send($e.SelectCharacter,e,Lc)}};var Zr=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(Mt.CreateMatch,e,Np)}updateMatch(e){return this.send(Mt.UpdateMatch,e,_p)}cancelMatch(e){return this.send(Mt.CancelMatch,e,Vp)}instantBattle(e){return this.send(Mt.InstantBattle,e,jp)}saveStrategy(e){return this.send(Mt.SaveStrategy,e,Qe)}getMyMatches(e){return this.send(Mt.GetMyMatches,e,Da)}getAvailableMatches(e){return this.send(Mt.GetAvailableMatches,e,Da)}getDefinitions(e){return this.send(Mt.GetDefinitions,e,Qp)}};var Hv={Arena:"Arena"},nf=z.string(),En={GetState:"GetState",RefreshOpponents:"RefreshOpponents",Attempt:"Attempt",ClaimMilestone:"ClaimMilestone"},$v=z.object({TierID:z.string().nullish(),MinPowerRatio:z.number().nullish(),MaxPowerRatio:z.number().nullish(),PointsOnWin:z.number().nullish(),BotStatScale:z.number().nullish()}).passthrough(),Jv=z.object({RuleID:z.string().nullish(),Tiers:z.array($v).nullish(),RefreshCooldownSeconds:z.number().nullish(),LiveOpponentActiveDays:z.number().nullish(),MaxCandidateReads:z.number().nullish(),RevengeEnabled:z.boolean().nullish(),RevengeCost:z.number().nullish(),RevengePoints:z.number().nullish(),WinReward:$.nullish()}).passthrough(),Zv=z.object({ChallengeID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish(),Mode:nf.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AttemptCost:z.number().nullish(),DailyAttemptLimit:z.number().nullish(),Points:Tt.nullish(),Milestones:z.record(z.string(),je).nullish(),ClaimMode:z.string().nullish(),Arena:Jv.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Yv=z.object({ChainID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:Ce.nullish(),Challenges:z.array(Zv).nullish(),Ticket:Tt.nullish(),Gate:te.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),sf=z.object({Chains:z.record(z.string(),Yv).nullish()}).passthrough(),rf=z.object({TierID:z.string().nullish(),OpponentID:z.string().nullish(),IsBot:z.boolean().nullish(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),Country:z.string().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),BotStatScale:z.number().nullish(),Defeated:z.boolean().nullish()}).passthrough(),Xv=z.object({RevengeID:z.string().nullish(),InstanceKey:z.string().nullish(),AttackerUserID:z.string().nullish(),AttackerName:z.string().nullish(),AttackerAvatarUrl:z.string().nullish(),AttackerPower:z.number().nullish(),CreatedAtUtc:u.nullish(),Used:z.boolean().nullish()}).passthrough(),eA=z.object({AttemptID:z.string().nullish(),InstanceKey:z.string().nullish(),OpponentID:z.string().nullish(),TierID:z.string().nullish(),IsRevenge:z.boolean().nullish(),Win:z.boolean().nullish(),PointsGranted:z.number().nullish(),TicketsSpent:z.number().nullish(),AtUtc:u.nullish()}).passthrough(),tA=z.object({Opponents:z.array(rf).nullish(),Revenges:z.array(Xv).nullish(),RevengeCost:z.number().nullish(),RevengePoints:z.number().nullish(),RefreshAvailableAtUtc:u.nullish()}).passthrough(),tf=z.object({ChallengeID:z.string().nullish(),Mode:nf.nullish(),InstanceKey:z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),AttemptCost:z.number().nullish(),AttemptsToday:z.number().nullish(),DailyAttemptLimit:z.number().nullish(),PointsEarned:z.number().nullish(),ClaimedMilestoneIDs:z.array(z.string()).nullish(),Arena:tA.nullish()}).passthrough(),nA=z.object({ChainID:z.string().nullish(),Tickets:z.number().nullish(),Active:tf.nullish(),Ended:z.array(tf).nullish()}).passthrough(),iA=z.object({ChainID:z.string().nullish(),InstanceKey:z.string().nullish(),TicketsBurned:z.number().nullish(),CurrencyID:z.string().nullish(),Converted:z.number().nullish(),CarriedToInstanceKey:z.string().nullish()}).passthrough(),Rl=z.object({Chains:z.array(nA).nullish(),ServerTimeUtc:u.nullish(),Burns:z.array(iA).nullish(),Rewards:O.nullish(),Inventory:Q.nullish()}).passthrough(),of=z.object({ChainID:z.string().nullish(),InstanceKey:z.string().nullish(),Attempt:eA.nullish(),IsReplay:z.boolean().nullish(),Battle:Qn.nullish(),Opponent:rf.nullish(),Tickets:z.number().nullish(),PointsEarned:z.number().nullish(),Rewards:O.nullish(),Inventory:Q.nullish()}).passthrough(),af=z.object({ChainID:z.string().nullish(),InstanceKey:z.string().nullish(),MilestoneID:z.string().nullish(),Rewards:O.nullish(),Inventory:Q.nullish()}).passthrough();var Yr=class extends B{constructor(e){super(e,"Challenge");}getState(e){return this.send(En.GetState,e,Rl)}refreshOpponents(e){return this.send(En.RefreshOpponents,e,Rl)}attempt(e){return this.send(En.Attempt,e,of)}claimMilestone(e){return this.send(En.ClaimMilestone,e,af)}};var sA={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},lf=z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),rA={None:"None",Min:"Min",Average:"Average",Max:"Max",Weighted:"Weighted"},oA=z.enum(["None","Min","Average","Max","Weighted"]).catch("None"),aA={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},lA=z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),uA={Clamp:"Clamp",Reject:"Reject"},cA=z.enum(["Clamp","Reject"]).catch("Clamp"),pA=z.object({ItemInstanceID:z.string().nullish(),ItemID:z.string().nullish(),Level:z.number().nullish(),Units:z.number().nullish()}),hA=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:At.nullish(),OutputLevel:z.number().nullish(),BurnedInstances:z.array(pA).nullish()}),uf=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u,Type:lf.nullish(),CraftID:z.string(),CraftedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),InputRarity:z.string().nullish(),OutputRarity:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish(),Results:z.array(hA).nullish()}),dA=z.object({CraftID:z.string().nullish(),Type:lf.nullish(),CatalogID:z.string().nullish(),CollectionID:z.string().nullish(),InputRarityID:z.string().nullish(),OutputRarityID:z.string().nullish(),RequiredItemCount:z.number().nullish(),PriceOptions:de.nullish(),OutputLevelMode:oA.nullish(),OutputLevelWeightPower:z.number().nullish(),InputSelection:lA.nullish(),OutputLevelOverflow:cA.nullish()}).passthrough(),Cl=z.object({Definitions:z.record(z.string(),dA).nullish()}).passthrough(),cf=z.object({ServerTimeUtc:u.nullish(),CraftDefinitions:Cl.nullish()}),Xr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var eo=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Xr.GetDefinitions,e,cf)}craft(e){return this.send(Xr.Craft,e,Te(uf))}};var mA=2e5,to=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,Te(Is),{timeoutMs:mA,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Is,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Fe.GetDefinitions,e,Zc)}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)}generateFromTemplate(e){return this.generate(Fe.GenerateFromTemplate,e)}estimateTemplatePrice(e){return this.send(Fe.EstimateTemplatePrice,e,Jc,{throttleKey:`AI:EstimateTemplatePrice:${e.FeatureKey??""}:${JSON.stringify(e.Params??{})}`})}generateThreeD(e){return this.generate(Fe.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Fe.GetThreeD,e)}listGenerations(e){return this.send(Fe.ListGenerations,e,Hc)}getGeneration(e){return this.readGeneration(Fe.GetGeneration,e)}};var fA={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},gA=z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),pf=z.object({}).passthrough().transform(o=>o),qn=z.object({CollectibleID:z.string(),Rarity:z.number().nullish(),IsSpecial:z.boolean().nullish(),IsDuplicate:z.boolean().nullish(),CollectionCurrencyConverted:z.number().nullish()}),hf=z.object({GrantedCollectibles:z.array(qn).nullish(),DuplicateCollectibles:z.array(qn).nullish(),CollectionCurrencyEarned:H.nullish()}),df=z.object({CreditsConfirmation:ye.nullish(),OpenedCount:z.number().nullish(),Packs:z.array(hf).nullish(),GrantedCollectibles:z.array(qn).nullish(),DuplicateCollectibles:z.array(qn).nullish(),CollectionCurrencyEarned:H.nullish(),NewCollectionCurrencyBalance:H.nullish(),NewlyCompletedSetIDs:z.array(z.string()).nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:O.nullish(),Inventory:Q.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),mf=z.object({OpenedCount:z.number().nullish(),Chests:z.array(hf).nullish(),GrantedCollectibles:z.array(qn).nullish(),DuplicateCollectibles:z.array(qn).nullish(),CollectionCurrencyEarned:H.nullish(),NewCollectionCurrencyBalance:H.nullish(),Resources:O.nullish(),Inventory:Q.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),ff=z.object({GrantedCollectibleID:z.string().nullish(),NewlyCompletedSetID:z.string().nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}),Sl=z.object({SetID:z.string(),Resources:O.nullish(),Inventory:Q.nullish()}),gf=z.array(Me(Sl)),yf=z.object({Resources:O.nullish(),Inventory:Q.nullish()}),yA=z.object({OfferID:z.string(),TitleID:z.string().nullish(),CollectionID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderPublicData:Ge.nullish(),OfferedCollectibleID:z.string().nullish(),OfferedCollectibleIsSpecial:z.boolean().nullish(),ReceiverUserID:z.string().nullish(),RequestedCollectibleID:z.string().nullish(),RequestedCollectibleIsSpecial:z.boolean().nullish(),Status:gA.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RespondedAtUtc:u.nullish(),DeclineReason:z.string().nullish(),IsSpecialTradeEvent:z.boolean().nullish(),SpecialTradeEventID:z.string().nullish()}).passthrough(),Rf=z.object({OfferID:z.string(),ExpiresAtUtc:u.nullish(),Resources:O.nullish()}),Cf=z.object({OfferID:z.string(),Resources:O.nullish()}),Sf=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()}),xf=z.object({OfferID:z.string(),Resources:O.nullish()}),xl=z.object({Offers:z.array(yA).nullish()}),RA=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(),CA=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(RA).nullish(),SetCompletionReward:$.nullish()}).passthrough(),SA=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(CA).nullish(),GrandPrize:$.nullish()}).passthrough(),bf=z.object({BonusRewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),xA=z.object({PackTypeID:z.string().nullish(),PriceOptions:de.nullish(),BonusRewardSlots:z.array(Mn).nullish(),PityRules:z.array(On).nullish(),Presets:bf.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(),bA=z.object({Rarity:z.number().nullish(),CollectionCurrencyGranted:z.number().nullish()}).passthrough(),DA=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(Mn).nullish(),PityRules:z.array(On).nullish(),Presets:bf.nullish(),Tier:z.number().nullish()}).passthrough(),IA=z.object({SpecialTradeEventID:z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),AllowedSpecialCollectibleIDs:z.array(z.string()).nullish(),SpecialTradeEventDailyTradeLimit:z.number().nullish()}).passthrough(),PA=z.object({MaxPackOpenCount:z.number().nullish(),MaxChestOpenCount:z.number().nullish()}).passthrough(),no=z.object({Collections:z.record(z.string(),SA).nullish(),PackTypes:z.record(z.string(),xA).nullish(),CollectionChests:z.array(DA).nullish(),DuplicateConversions:z.array(bA).nullish(),DailyTradeLimit:z.number().nullish(),CollectibleJokerCatalogID:z.string().nullish(),CollectibleJokerItemID:z.string().nullish(),SpecialTradeEvents:z.array(IA).nullish(),RewardPools:Ur.nullish(),Settings:PA.nullish()}).passthrough(),Xe={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var io=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Xe.GetDefinitions,e,no)}getUserState(e){return this.send(Xe.GetUserState,e,pf)}openPack(e){return this.send(Xe.OpenPack,e,Te(df))}openCollectionChest(e){return this.send(Xe.OpenCollectionChest,e,mf)}useCollectibleJoker(e){return this.send(Xe.UseCollectibleJoker,e,ff)}claimSetReward(e){return this.send(Xe.ClaimSetReward,e,Sl)}claimSetRewardsBatch(e){return this.send(Xe.ClaimSetRewardsBatch,e,gf)}claimGrandPrize(e){return this.send(Xe.ClaimGrandPrize,e,yf)}sendTradeOffer(e){return this.send(Xe.SendTradeOffer,e,Rf)}cancelTradeOffer(e){return this.send(Xe.CancelTradeOffer,e,Cf)}acceptTradeOffer(e){return this.send(Xe.AcceptTradeOffer,e,Sf)}declineTradeOffer(e){return this.send(Xe.DeclineTradeOffer,e,xf)}getMyTradeOffers(e){return this.send(Xe.GetMyTradeOffers,e,xl)}getIncomingTradeOffers(e){return this.send(Xe.GetIncomingTradeOffers,e,xl)}};var so=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(Pt.GetDefinitions,e,Ts)}getActiveEvent(e){return this.send(Pt.GetActiveEvent,e,ep)}getUserState(e){return this.send(Pt.GetUserState,e,As)}getGroupState(e){return this.send(Pt.GetGroupState,e,ma)}joinOrCreateGroup(e){return this.send(Pt.JoinOrCreateGroup,e,ma)}spin(e){return this.send(Pt.Spin,e,Te(np))}claimObjectReward(e){return this.send(Pt.ClaimObjectReward,e,fa)}claimGrandPrize(e){return this.send(Pt.ClaimGrandPrize,e,fa)}leaveGroup(e){return this.send(Pt.LeaveGroup,e,ip)}};var ro=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(kt.GetDefinition,e,mp)}getUserState(e){return this.send(kt.GetUserState,e,fp)}getActiveDeals(e){return this.send(kt.GetActiveDeals,e,ks)}dismissDeal(e){return this.send(kt.DismissDeal,e,yp)}executeNode(e){return this.send(kt.ExecuteNode,e,Te(gp))}recordShow(e){return this.send(kt.RecordShow,e,Rp)}claimMilestone(e){return this.send(kt.ClaimMilestone,e,Cp)}claimMilestonesBatch(e){return this.send(kt.ClaimMilestonesBatch,e,Sp)}};var vA=z.object({}).passthrough().transform(o=>o),AA=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:Pe.nullish()}).passthrough(),bl=z.object({IsEnabled:z.boolean().nullish(),ActivationReward:$.nullish(),InviteRewards:z.record(z.string(),je).nullish(),SpendRewards:z.array(AA).nullish(),Qualification:z.object({}).passthrough().transform(o=>o).nullish()}).passthrough(),Dl=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(),Df=z.object({ReferralDefinitions:bl.nullish()}).passthrough(),If=z.object({Referral:vA.nullish(),InviteUrl:z.string().nullish(),Qualification:Dl.nullish()}).passthrough(),Pf=z.object({QualificationPending:z.boolean().nullish(),Qualification:Dl.nullish()}).passthrough(),vf=z.object({ReferralCode:z.string().nullish(),ReferrerUserID:z.string().nullish(),IsFirstActivation:z.boolean().nullish(),Resources:O.nullish(),Inventory:Q.nullish(),QualificationPending:z.boolean().nullish(),Qualification:Dl.nullish()}).passthrough(),Il=z.object({RewardID:z.string().nullish(),Resources:O.nullish(),Inventory:Q.nullish()}).passthrough(),Af=wt(Il),nn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var oo=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(nn.GetDefinitions,e,Df)}getUserState(e){return this.send(nn.GetUserState,e,If)}activateReferralCode(e){return this.send(nn.ActivateReferralCode,e,vf)}claimInviteReward(e){return this.send(nn.ClaimInviteReward,e,Il)}claimInviteRewardsBatch(e){return this.send(nn.ClaimInviteRewardsBatch,e,Af)}checkQualification(e){return this.send(nn.CheckQualification,e,Pf)}};var ao=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(ct.GetDefinitions,e,Mp)}getMessages(e){return this.send(ct.GetMessages,e,Op)}getUnreadCount(e){return this.send(ct.GetUnreadCount,e,qs)}readMessages(e){return this.send(ct.ReadMessages,e,Ca)}claimReward(e){return this.send(ct.ClaimReward,e,Us)}claimRewardsBatch(e){return this.send(ct.ClaimRewardsBatch,e,Us)}claimAll(e){return this.send(ct.ClaimAll,e,Us)}deleteMessages(e){return this.send(ct.DeleteMessages,e,Ca)}sendGift(e){return this.send(ct.SendGift,e,Ep)}sendTransfer(e){return this.send(ct.SendTransfer,e,qp)}getGiftStatus(e){return this.send(ct.GetGiftStatus,e,Up)}};var lo=class extends B{constructor(e){super(e,"Clan");}getDefinitions(e){return this.send(Le.GetDefinitions,e,lh)}getMyClans(e){return this.send(Le.GetMyClans,e,$p)}searchClans(e){return this.send(Le.SearchClans,e,Ta)}getRecommendedClans(e){return this.send(Le.GetRecommendedClans,e,Ta)}getClan(e){return this.send(Le.GetClan,e,Jp)}getClanMembers(e){return this.send(Le.GetClanMembers,e,Yp)}getRankings(e){return this.send(Le.GetRankings,e,Xp)}getApplications(e){return this.send(Le.GetApplications,e,wa)}getMyInvites(e){return this.send(Le.GetMyInvites,e,wa)}getClanLog(e){return this.send(Le.GetClanLog,e,eh)}getRequests(e){return this.send(Le.GetRequests,e,nh)}getGifts(e){return this.send(Le.GetGifts,e,ih)}getRewards(e){return this.send(Le.GetRewards,e,sh)}getTreasury(e){return this.send(Le.GetTreasury,e,uh)}getProjects(e){return this.send(Le.GetProjects,e,ch)}getActivities(e){return this.send(Le.GetActivities,e,ph)}getClanQuests(e){return this.send(Le.GetClanQuests,e,hh)}getCompetitions(e){return this.send(Le.GetCompetitions,e,dh)}getBracket(e){return this.send(Le.GetBracket,e,mh)}getDiplomacy(e){return this.send(Le.GetDiplomacy,e,fh)}getRevenges(e){return this.send(Le.GetRevenges,e,gh)}getLeague(e){return this.send(Le.GetLeague,e,yh)}mutate(e,t){return this.send(e,t,ah)}};var uo=class extends B{constructor(e){super(e,"Avatar");}getDefinitions(e){return this.send(wn.GetDefinitions,e,js)}getAvatars(e){return this.send(wn.GetAvatars,e,Ch)}getShop(e){return this.send(wn.GetShop,e,Sh)}buyItem(e){return this.send(wn.BuyItem,e,xh)}};var sn={GetMyPartnership:"GetMyPartnership",Apply:"Apply",AcceptInvite:"AcceptInvite",GetStats:"GetStats",GetPayouts:"GetPayouts",ListCreators:"ListCreators"},TA={Off:"Off",InviteOnly:"InviteOnly",Moderated:"Moderated",Auto:"Auto"},wA={Applied:"Applied",Invited:"Invited",Active:"Active",Rejected:"Rejected",Removed:"Removed"},zA={ProgramOff:"PARTNER_PROGRAM_OFF",ApplicationsClosed:"PARTNER_APPLICATIONS_CLOSED",SignInRequired:"PARTNER_SIGN_IN_REQUIRED",AlreadyPartner:"PARTNER_ALREADY",AlreadyApplied:"PARTNER_ALREADY_APPLIED",Removed:"PARTNER_REMOVED",NoInvite:"PARTNER_NO_INVITE",BadInput:"PARTNER_BAD_INPUT",NotPartner:"PARTNER_NOT_FOUND",Conflict:"PARTNER_CONFLICT"},kA=z.enum(["Off","InviteOnly","Moderated","Auto"]).catch("Off"),MA=z.enum(["Applied","Invited","Active","Rejected","Removed"]),Pl=z.record(z.string(),z.string()).nullish(),OA=z.object({Mode:kA,DefaultSharePercent:z.number().nullish(),Terms:Pl,AskLinks:z.boolean().nullish(),AskAbout:z.boolean().nullish(),AskFollowers:z.boolean().nullish(),CanApply:z.boolean().nullish()}).passthrough(),EA=z.object({PublicName:z.string().nullish(),Links:z.array(z.string()).nullish(),About:z.string().nullish(),Followers:z.number().nullish(),SubmittedAt:z.string().nullish()}).passthrough(),qA=z.object({FeatureKey:z.string(),Name:Pl,PreviewUrl:z.string().nullish(),PreviewType:z.string().nullish()}).passthrough(),co=z.object({Program:OA,Status:MA.nullish(),SharePercent:z.number().nullish(),Templates:z.array(qA).nullish(),DecisionNote:z.string().nullish(),Application:EA.nullish(),SignInRequired:z.boolean().nullish()}).passthrough(),Tf=z.object({Days:z.number(),ByDay:z.array(z.object({Day:z.string(),Generations:z.number(),Paid:z.number(),PartnerCredits:z.number()}).passthrough()).nullish(),ByTemplate:z.array(z.object({FeatureKey:z.string(),Name:Pl,Generations:z.number(),Paid:z.number(),PartnerCredits:z.number()}).passthrough()).nullish(),Generations:z.number(),PeriodCredits:z.number(),AccruedCredits:z.number(),PaidOutCredits:z.number(),BalanceCredits:z.number()}).passthrough(),wf=z.object({Payouts:z.array(z.object({Credits:z.number(),Note:z.string().nullish(),PaidAt:z.string()}).passthrough()).nullish()}).passthrough(),UA=z.object({Id:z.string(),Name:z.string(),Links:z.array(z.string()).nullish(),FeatureKeys:z.array(z.string()).nullish()}).passthrough(),zf=z.object({Creators:z.array(UA).nullish()}).passthrough();var po=class extends B{constructor(e){super(e,"Partners");}getMyPartnership(e){return this.send(sn.GetMyPartnership,e,co)}apply(e){return this.send(sn.Apply,e,co)}acceptInvite(e){return this.send(sn.AcceptInvite,e,co)}getStats(e){return this.send(sn.GetStats,e,Tf)}getPayouts(e){return this.send(sn.GetPayouts,e,wf)}listCreators(e){return this.send(sn.ListCreators,e,zf)}};var ho=class extends B{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Ks.RequestAdPermit,e,bh)}completeView(e){return this.send(Ks.CompleteView,e,Dh)}};var mo=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(De.GetFriendsList,e,$n)}getIncomingRequests(e){return this.send(De.GetIncomingRequests,e,$n)}getOutgoingRequests(e){return this.send(De.GetOutgoingRequests,e,$n)}getRecommendedFriends(e){return this.send(De.GetRecommendedFriends,e,$n)}sendFriendRequest(e){return this.send(De.SendFriendRequest,e,Jn)}acceptFriendRequest(e){return this.send(De.AcceptFriendRequest,e,Jn)}declineFriendRequest(e){return this.send(De.DeclineFriendRequest,e,Jn)}removeFriend(e){return this.send(De.RemoveFriend,e,Jn)}getPlayerProfile(e){return this.send(De.GetPlayerProfile,e,wh)}getInbox(e){return this.send(De.GetInbox,e,zh)}markInboxSeen(e){return this.send(De.MarkInboxSeen,e,Zn)}getInboxUnread(e){return this.send(De.GetInboxUnread,e,Zn)}follow(e){return this.send(De.Follow,e,Yt)}unfollow(e){return this.send(De.Unfollow,e,Yt)}getFollowers(e){return this.send(De.GetFollowers,e,Js)}getFollowing(e){return this.send(De.GetFollowing,e,Js)}block(e){return this.send(De.Block,e,Yt)}unblock(e){return this.send(De.Unblock,e,Yt)}getBlocked(e){return this.send(De.GetBlocked,e,Js)}react(e){return this.send(De.React,e,Yt)}unreact(e){return this.send(De.Unreact,e,Yt)}getMyReactions(e){return this.send(De.GetMyReactions,e,Mh)}getEntityStates(e){return this.send(De.GetEntityStates,e,kh)}addComment(e){return this.send(De.AddComment,e,Zs)}editComment(e){return this.send(De.EditComment,e,Zs)}deleteComment(e){return this.send(De.DeleteComment,e,Eh)}getComments(e){return this.send(De.GetComments,e,Oh)}report(e){return this.send(De.Report,e,qh)}};var LA={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var mn=z.object({Target:z.string().nullish(),Operation:z.string().nullish(),Value:z.number().nullish()}).passthrough(),BA=z.object({BoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:de.nullish(),Effect:mn.nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),fo=z.object({Schedule:Ce.nullish(),Gate:te.nullish()}).passthrough(),vl=z.object({Availability:J.nullish(),Effects:J.nullish()}).passthrough(),GA=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(mn).nullish(),Availability:fo.nullish(),Presets:vl.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),NA=z.object({ChainedBoostID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Effects:z.array(mn).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),_A=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(NA).nullish(),Availability:fo.nullish(),Presets:vl.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),VA=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(dt).nullish(),Effects:z.array(mn).nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Availability:fo.nullish(),Presets:vl.nullish()}).passthrough(),jA=z.object({MaxAddPercent:z.number().nullish(),MaxMultiply:z.number().nullish(),MaxAddFlat:z.number().nullish()}).passthrough(),FA=z.object({Effects:z.array(mn).nullish()}).passthrough(),WA=z.object({Availability:z.record(z.string(),fo).nullish(),Effects:z.record(z.string(),FA).nullish()}).passthrough(),KA=z.object({StackingCaps:z.record(z.string(),jA).nullish()}).passthrough(),go=z.object({Definitions:z.record(z.string(),BA).nullish(),ScheduledBoosts:z.record(z.string(),GA).nullish(),BoostChains:z.record(z.string(),_A).nullish(),TriggeredBoosts:z.record(z.string(),VA).nullish(),Settings:KA.nullish(),Presets:WA.nullish()}).passthrough(),kf=z.object({InstanceID:z.string(),BoostID:z.string(),ActivatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RemainingCharges:z.number().nullish(),EffectSnapshot:mn.nullish(),SourceType:z.string().nullish(),SourceRef:z.string().nullish()}).passthrough();z.object({Date:u.nullish(),DailyCount:z.number().nullish(),LastFiredUtc:u.nullish()}).passthrough();var Mf=z.object({ServerTimeUtc:u.nullish(),Active:z.record(z.string(),kf).nullish()}),Of=z.object({CreditsConfirmation:ye.nullish(),ServerTimeUtc:u.nullish(),BoostID:z.string().nullish(),StackingPolicy:z.string().nullish(),ActivatedBoost:kf.nullish(),Resources:O.nullish()}),QA={Scheduled:"Scheduled",Chain:"Chain"},HA=z.object({Kind:z.string().nullish(),SourceID:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),PhaseOrder:z.number().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),Effects:z.array(mn).nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Ef=z.object({ServerTimeUtc:u.nullish(),Windows:z.array(HA).nullish()}),fn={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var yo=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(fn.GetDefinitions,e,go)}getActive(e){return this.send(fn.GetActive,e,Mf)}getActiveWindows(e){return this.send(fn.GetActiveWindows,e,Ef)}activate(e){return this.send(fn.Activate,e,Te(Of))}cleanupExpired(e){return this.send(fn.CleanupExpired,e,Qe)}};var Ro=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(vt.GetUserCustomDataDefinitions,e,$s)}getMyUserCustomData(e){return this.send(vt.GetMyUserCustomData,e,Ih)}getPublicUserCustomDataOf(e){return this.send(vt.GetPublicUserCustomDataOf,e,Oa)}setPrivateData(e){return this.send(vt.SetPrivateData,e,Ea)}setPublicData(e){return this.send(vt.SetPublicData,e,Ea)}deleteKey(e){return this.send(vt.DeleteKey,e,Qe)}batchSet(e){return this.send(vt.BatchSet,e,Ph)}batchDelete(e){return this.send(vt.BatchDelete,e,vh)}batchGetPublicUserCustomDataOf(e){return this.send(vt.BatchGetPublicUserCustomDataOf,e,Ah)}};var $A={Static:"Static",Runtime:"Runtime"},JA={Public:"Public",Private:"Private"},ZA=z.enum(["Client","Server","System"]).catch("Client"),YA=z.enum(["String","Int","Bool","Json"]).catch("String"),XA=z.object({Value:z.string().nullish(),UpdatedAt:u.nullish(),Version:z.number().nullish(),LastWriter:ZA.nullish(),ExpiresAt:u.nullish()}).passthrough(),qf=z.record(z.string(),XA),Al=z.object({StaticVersion:z.number().nullish(),RuntimeVersion:z.number().nullish(),Static:qf.nullish(),Runtime:qf.nullish(),NotModified:z.boolean().nullish()}),eT=z.object({KeyID:z.string(),Scope:z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:YA.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),Co=z.object({Keys:z.record(z.string(),eT).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),si={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var So=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(si.GetTitleCustomDataDefinitions,e,Co)}getPublicTitleData(e){return this.send(si.GetPublicTitleData,e,Al)}getPublicTitleDataKeys(e){return this.send(si.GetPublicTitleDataKeys,e,Al)}};var Uf=z.object({Theme:z.record(z.string(),z.string()).nullish(),Radius:z.number().nullish(),ButtonRadius:z.number().nullish(),Outline:z.number().nullish(),Background:z.string().nullish(),MotionSpeed:z.number().nullish(),MotionIntensity:z.number().nullish(),Particles:z.boolean().nullish(),SoundSet:z.string().nullish()}).passthrough();var tT={Mesh:"Mesh",Host:"Host"},Tl=z.enum(["Mesh","Host"]).catch("Mesh"),nT={ServerRelay:"ServerRelay",P2P:"P2P"},wl=z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),iT={Public:"Public",Private:"Private"},sT=z.enum(["Public","Private"]).catch("Public"),rT={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},oT=z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Lf=z.object({Urls:z.string().nullish(),Username:z.string().nullish(),Credential:z.string().nullish()}).passthrough(),aT=z.object({Enabled:z.boolean().nullish()}).passthrough(),Bf=z.object({SystemState:aT.nullish(),DefaultTopology:Tl.nullish(),AllowCreatorTopologyOverride:z.boolean().nullish(),DefaultChatMode:wl.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(Lf).nullish()}).passthrough(),lT=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(),uT=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),Topology:Tl.nullish(),ChatMode:wl.nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),MemberCount:z.number().nullish(),CreatedAt:z.number().nullish()}).passthrough(),cT=z.object({Seq:z.number().nullish(),Type:oT.nullish(),FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Kind:z.string().nullish(),Payload:z.string().nullish(),Ts:z.number().nullish()}).passthrough(),ri=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),OwnerUserID:z.string().nullish(),Topology:Tl.nullish(),ChatMode:wl.nullish(),Visibility:sT.nullish(),Status:z.string().nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),Members:z.array(lT).nullish(),IceServers:z.array(Lf).nullish(),Seq:z.number().nullish(),BannedUserIDs:z.array(z.string()).nullish()}).passthrough(),Gf=z.object({Removed:z.boolean().nullish(),Banned:z.boolean().nullish()}).passthrough(),Nf=z.object({WasBanned:z.boolean().nullish()}).passthrough(),zl=z.object({Closed:z.boolean().nullish(),NewHostUserID:z.string().nullish()}).passthrough(),_f=z.object({Rooms:z.array(uT).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}).passthrough(),Vf=z.object({Envelopes:z.array(cT).nullish(),MaxSeq:z.number().nullish()}).passthrough(),xo=z.object({Seq:z.number().nullish()}).passthrough(),st={CreateRoom:"CreateRoom",JoinRoom:"JoinRoom",LeaveRoom:"LeaveRoom",ListRooms:"ListRooms",GetRoom:"GetRoom",CloseRoom:"CloseRoom",Poll:"Poll",SendSignal:"SendSignal",SendChat:"SendChat",SetMemberState:"SetMemberState",ClaimHost:"ClaimHost",KickMember:"KickMember",UnbanMember:"UnbanMember"};var kl=z.object({TitleCustomData:Co.nullish(),Character:Cs.nullish(),Item:wr.nullish(),Currency:Es.nullish(),Store:Gi.nullish(),Lootbox:ml.nullish(),Quest:di.nullish(),TimedEvent:ss.nullish(),Leaderboard:hs.nullish(),Season:fs.nullish(),Reward:gl.nullish(),Collection:no.nullish(),Craft:Cl.nullish(),DealOffer:ga.nullish(),Premium:pl.nullish(),TimedBoost:go.nullish(),CoopEvent:Ts.nullish(),GameLoop:sr.nullish(),Match:Ia.nullish(),Challenge:sf.nullish(),Experiment:lm.nullish(),Blockchain:_a.nullish(),Marketplace:Ja.nullish(),Multiplayer:Bf.nullish(),UserCustomData:$s.nullish(),Referral:bl.nullish(),Localization:pm.nullish(),Analytics:Zd.nullish(),Social:Uh.nullish(),PlatformBridge:Lh.nullish(),GameSpec:z.string().nullish(),Look:Uf.nullish(),Avatar:js.nullish()}).passthrough();var gn={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var bo=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(gn.GetTitlePublicConfiguration,e,kl)}getTitlePublicConfigurationExcept(e){return this.send(gn.GetTitlePublicConfigurationExcept,e,kl)}getCurrencyDefinitions(e){return this.send(gn.GetCurrencyDefinitions,e,Es)}getItemDefinitions(e){return this.send(gn.GetItemDefinitions,e,wr)}getServerTime(e){return this.send(gn.GetServerTime,e,Qe)}};var Do=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(We.GetGameLoops,e,sr)}getBoardDefinition(e,t=false){return this.send(We.GetBoardDefinition,e,ir,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(We.GetBoardDefinitionForLevel,e,ir,{silent:t})}getUserBoardState(e){return this.send(We.GetUserBoardState,e,_h)}boardLoopRoll(e){return this.send(We.BoardLoopRoll,e,Hh)}boardLoopAttack(e){return this.send(We.BoardLoopAttack,e,Zh)}boardLoopRaid(e){return this.send(We.BoardLoopRaid,e,Ba)}boardLoopRaidFast(e){return this.send(We.BoardLoopRaidFast,e,Ba)}boardLoopBuild(e){return this.send(We.BoardLoopBuild,e,Yh)}boardSpecialChoose(e){return this.send(We.BoardSpecialChoose,e,Te(Xh))}boardSpecialApplyMultiplier(e){return this.send(We.BoardSpecialApplyMultiplier,e,ed)}boardRewardBoostApply(e){return this.send(We.BoardRewardBoostApply,e,Jh)}boardSpecialClaim(e){return this.send(We.BoardSpecialClaim,e,td)}getCommunityChestState(e){return this.send(We.GetCommunityChestState,e,sd)}joinOrCreateCommunityChest(e){return this.send(We.JoinOrCreateCommunityChest,e,rd)}claimCommunityChestMilestone(e){return this.send(We.ClaimCommunityChestMilestone,e,Ga)}claimCommunityChestGrandPrize(e){return this.send(We.ClaimCommunityChestGrandPrize,e,Ga)}leaveCommunityChest(e){return this.send(We.LeaveCommunityChest,e,od)}};var pT={Live:"Live",Latest:"Latest",Specific:"Specific"},hT={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},dT=z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),mT={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"},fT=z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),gT=z.object({Level:dT,Message:z.string().nullish(),Data:$t.nullish()}),yT=z.object({Error:fT,Message:z.string().nullish(),StackTrace:z.string().nullish()}),Ff=z.object({FunctionName:z.string().nullish(),Revision:z.number().nullish(),FunctionResult:$t.nullish(),FunctionResultTooLarge:z.boolean().nullish(),Logs:z.array(gT).nullish(),LogsTooLarge:z.boolean().nullish(),ExecutionTimeSeconds:z.number().nullish(),APIRequestsIssued:z.number().nullish(),Error:yT.nullish()}),Ml={Execute:"Execute"};var Io=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(Ml.Execute,e,Ff)}};var Po=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(it.GetDefinitions,e,gd)}getUserState(e){return this.send(it.GetUserState,e,yd)}depositToken(e){return this.send(it.DepositToken,e,Rd)}depositNFT(e){return this.send(it.DepositNFT,e,Cd)}requestTokenWithdrawal(e){return this.send(it.RequestTokenWithdrawal,e,Sd)}requestNFTWithdrawal(e){return this.send(it.RequestNFTWithdrawal,e,xd)}getTransactionHistory(e){return this.send(it.GetTransactionHistory,e,bd)}retryWithdrawal(e){return this.send(it.RetryWithdrawal,e,Dd)}confirmWithdrawal(e){return this.send(it.ConfirmWithdrawal,e,Id)}donateToDeveloper(e){return this.send(it.DonateToDeveloper,e,Wa)}donateToUsersPool(e){return this.send(it.DonateToUsersPool,e,Wa)}getPlayAccess(e){return this.send(it.GetPlayAccess,e,md)}confirmPlayAccess(e){return this.send(it.ConfirmPlayAccess,e,Xt)}};var vo=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Be.GetDefinitions,e,Ad)}getGroupedOffers(e){return this.send(Be.GetGroupedOffers,e,Td)}getOffersByItem(e){return this.send(Be.GetOffersByItem,e,Za)}getOffer(e){return this.send(Be.GetOffer,e,wd)}getBuyOrders(e){return this.send(Be.GetBuyOrders,e,Za)}getMyState(e){return this.send(Be.GetMyState,e,dr)}getHistory(e){return this.send(Be.GetHistory,e,kd)}createListing(e){return this.send(Be.CreateListing,e,ei)}cancelListing(e){return this.send(Be.CancelListing,e,Rt)}buy(e){return this.send(Be.Buy,e,Rt)}marketBuy(e){return this.send(Be.MarketBuy,e,Rt)}marketSell(e){return this.send(Be.MarketSell,e,Rt)}createAuction(e){return this.send(Be.CreateAuction,e,ei)}placeBid(e){return this.send(Be.PlaceBid,e,zd)}claimAuction(e){return this.send(Be.ClaimAuction,e,Rt)}createBuyOrder(e){return this.send(Be.CreateBuyOrder,e,ei)}cancelBuyOrder(e){return this.send(Be.CancelBuyOrder,e,Rt)}fillBuyOrder(e){return this.send(Be.FillBuyOrder,e,Rt)}createDirectTrade(e){return this.send(Be.CreateDirectTrade,e,ei)}respondDirectTrade(e){return this.send(Be.RespondDirectTrade,e,Rt)}cancelDirectTrade(e){return this.send(Be.CancelDirectTrade,e,Rt)}claimBack(e){return this.send(Be.ClaimBack,e,Rt)}};var Ao=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(st.CreateRoom,e,ri)}joinRoom(e){return this.send(st.JoinRoom,e,ri)}leaveRoom(e,t=false){return this.send(st.LeaveRoom,e,zl,{keepalive:t})}listRooms(e){return this.send(st.ListRooms,e,_f)}getRoom(e){return this.send(st.GetRoom,e,ri)}closeRoom(e){return this.send(st.CloseRoom,e,zl)}poll(e){return this.send(st.Poll,e,Vf)}sendSignal(e){return this.send(st.SendSignal,e,xo,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(st.ClaimHost,e,ri)}kickMember(e){return this.send(st.KickMember,e,Gf)}unbanMember(e){return this.send(st.UnbanMember,e,Nf)}sendChat(e){return this.send(st.SendChat,e,xo)}setMemberState(e){return this.send(st.SetMemberState,e,xo)}};var RT={Free:"Free",Price:"Price",Holding:"Holding"},Ol=z.enum(["Free","Price","Holding"]).catch("Free"),CT={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},ST=z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),xT={All:"All",Any:"Any"},bT=z.enum(["All","Any"]).catch("All"),DT={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},IT=z.enum(["Public","Unlisted","Friends"]).catch("Public"),PT={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},vT=z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),AT={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Kf=z.enum(["Purchase","Free","Holding"]).catch("Free"),TT={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},wT={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},zT=z.enum(["Creator","License","Free","Holding"]).catch("License"),kT=z.object({Type:i.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),Amount:z.number().nullish(),MinLevel:z.number().nullish()}).passthrough(),MT=z.object({Requirements:z.array(kT).nullish(),Match:bT.nullish(),Mode:ST.nullish()}).passthrough(),OT=z.object({OptionID:z.string().nullish(),Mode:Ol.nullish(),Price:pe.nullish(),Holding:MT.nullish()}).passthrough(),ET=z.object({AllowedMimeTypes:z.array(z.string()).nullish(),MaxBytes:z.number().nullish(),MaxCount:z.number().nullish(),Required:z.boolean().nullish()}).passthrough(),qT=z.object({DisplayName:z.string().nullish(),Enabled:z.boolean().nullish(),Files:z.record(z.string(),ET).nullish(),ThumbnailRequired:z.boolean().nullish(),AllowedAccessModes:z.array(Ol).nullish(),PricePolicy:hr.nullish(),PublishGate:te.nullish(),PublishFeeOptions:de.nullish(),TagVocabulary:z.array(z.string()).nullish(),MaxPublishedPerPlayer:z.number().nullish(),DailyPublishCap:z.number().nullish()}).passthrough(),UT=z.object({Allowed:z.array(Hn).nullish(),MaxRequirements:z.number().nullish()}).passthrough(),LT=z.object({AutoHideReportThreshold:z.number().nullish(),RequireApproval:z.boolean().nullish(),BlockedTerms:z.array(z.string()).nullish()}).passthrough(),BT=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(),GT=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Schedule:Ce.nullish(),Gate:te.nullish(),Order:z.number().nullish()}).passthrough(),NT=z.object({Enabled:z.boolean().nullish(),Gate:te.nullish(),Schedule:Ce.nullish(),ContentTypes:z.record(z.string(),qT).nullish(),PricePolicy:hr.nullish(),Commission:$a.nullish(),HoldingPolicy:UT.nullish(),Moderation:LT.nullish(),Limits:BT.nullish(),Featured:z.array(GT).nullish()}).passthrough(),_T=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(),yn=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),CreatorUserID:z.string().nullish(),IsOfficial:z.boolean().nullish(),CreatorPublicData:Ge.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:IT.nullish(),Access:z.array(OT).nullish(),Status:vT.nullish(),ModerationNote:z.string().nullish(),Stats:_T.nullish(),Revision:z.number().nullish(),ParentContentID:z.string().nullish(),FileCount:z.number().nullish(),TotalBytes:z.number().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),PublishedAt:u.nullish(),IsMine:z.boolean().nullish(),Owned:z.boolean().nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish()}).passthrough(),VT=z.object({OptionID:z.string().nullish(),Mode:Ol.nullish(),Available:z.boolean().nullish()}).passthrough(),Qf=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(),Hf=z.object({Definitions:NT.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish(),CanPublish:z.record(z.string(),z.boolean()).nullish(),Collections:z.array(Qf).nullish()}).passthrough(),To=z.object({Items:z.array(yn).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),$f=z.object({Content:yn.nullish(),AccessState:z.array(VT).nullish(),CanDownload:z.boolean().nullish()}).passthrough(),Jf=z.object({Collection:Qf.nullish(),Items:z.array(yn).nullish()}).passthrough(),Zf=z.object({CreatorUserID:z.string().nullish(),PublicData:Ge.nullish(),PublishedCount:z.number().nullish(),FollowerCount:z.number().nullish(),IsFollowing:z.boolean().nullish(),Items:z.array(yn).nullish()}).passthrough(),Wf=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(),Yf=z.object({ContentID:z.string().nullish(),Revision:z.number().nullish(),Uploads:z.array(Wf).nullish(),ThumbnailUpload:Wf.nullish(),ExpiresAt:u.nullish()}).passthrough(),Xf=z.object({CreditsConfirmation:ye.nullish(),Content:yn.nullish(),Resources:O.nullish()}).passthrough(),El=z.object({Content:yn.nullish()}).passthrough(),eg=z.object({ContentID:z.string().nullish(),OptionID:z.string().nullish(),Source:Kf.nullish(),AlreadyOwned:z.boolean().nullish(),AccessActive:z.boolean().nullish(),Settlement:Lt.nullish(),Resources:O.nullish(),CommissionTaken:pe.nullish()}).passthrough(),jT=z.object({Role:z.string().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish()}).passthrough(),tg=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),Revision:z.number().nullish(),AccessVia:zT.nullish(),Files:z.array(jT).nullish(),ThumbnailUrl:z.string().nullish(),ExpiresAt:u.nullish()}).passthrough(),FT=z.object({ContentID:z.string().nullish(),Source:Kf.nullish(),OptionID:z.string().nullish(),PricePaid:pe.nullish(),AcquiredAt:u.nullish(),Content:yn.nullish()}).passthrough(),ng=z.object({Licenses:z.array(FT).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),et={GetDefinitions:"GetDefinitions",Browse:"Browse",GetContent:"GetContent",GetCollection:"GetCollection",GetCreatorProfile:"GetCreatorProfile",BeginUpload:"BeginUpload",Publish:"Publish",UpdateContent:"UpdateContent",Unpublish:"Unpublish",GetMyContent:"GetMyContent",Acquire:"Acquire",GetDownload:"GetDownload",GetMyLicenses:"GetMyLicenses",GetMyFavorites:"GetMyFavorites"};var wo=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(et.GetDefinitions,e,Hf)}browse(e){return this.send(et.Browse,e,To)}getContent(e){return this.send(et.GetContent,e,$f)}getCollection(e){return this.send(et.GetCollection,e,Jf)}getCreatorProfile(e){return this.send(et.GetCreatorProfile,e,Zf)}beginUpload(e){return this.send(et.BeginUpload,e,Yf)}publish(e){return this.send(et.Publish,e,Te(Xf))}updateContent(e){return this.send(et.UpdateContent,e,El)}unpublish(e){return this.send(et.Unpublish,e,El)}getMyContent(e){return this.send(et.GetMyContent,e,To)}acquire(e){return this.send(et.Acquire,e,eg)}getDownload(e){return this.send(et.GetDownload,e,tg)}getMyLicenses(e){return this.send(et.GetMyLicenses,e,ng)}getMyFavorites(e){return this.send(et.GetMyFavorites,e,To)}};var zo=class extends B{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,n,i){return this.send(e,t,n,{throttleKey:`${this.endpoint(e,t)}|${i}`})}sendPublic(e,t,n,i){let r=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(r,t,n,{throttleKey:`${r}|${i}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,Ld,"defs")}get(e){return this.sendKeyed("Get",e,Xa,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Gd,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,el,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Nd,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,tl,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,tl,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,_d,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,jd,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Vd,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,Fd,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,Bd,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Wd,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,Xa,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,el,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var ko=class{settings;emitter;host;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;credits;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;challenge;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;clan;avatar;partners;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.host=e.host??N(),this.settings=Nl(e,this.host),this.emitter=new Gn,this.clientPlatform=e.clientPlatform??this.host.getClientPlatform(),this.acquisition=new on(this.host),this.acquisition.capture(),this.playtime=new Nn(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{}),this.host.supports.storePurchases&&this.purchase.restorePending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new Si({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e.fetch,debugLogging:this.settings.debugLogging,throttleMs:e.throttleMs,maxRequestsPerSecond:e.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new Ii(this.emitter),this.cache=new vi(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:n})=>{this.userService.noteStateVersions(t,n);}),this.authStore=new Ai(this.host.storage,this.settings.titleID),this.api={authentication:new Pr(this),user:new vr(this),currency:new Ar(this),item:new zr(this),store:new kr(this),purchase:new qr(this),lootbox:new Br(this),reward:new Gr(this),quest:new Wr(this),tutorial:new Nr(this),communityMarketing:new _r(this),chat:new Vr(this),push:new jr(this),localization:new Fr(this),timedEvent:new Kr(this),leaderboard:new Qr(this),season:new Hr(this),premium:new $r(this),character:new Jr(this),match:new Zr(this),challenge:new Yr(this),craft:new eo(this),ai:new to(this),collection:new io(this),coopEvent:new so(this),dealOffer:new ro(this),referral:new oo(this),mailbox:new ao(this),clan:new lo(this),avatar:new uo(this),partners:new po(this),advertising:new ho(this),social:new mo(this),timedBoost:new yo(this),userCustomData:new Ro(this),titleCustomData:new So(this),title:new bo(this),gameLoop:new Do(this),cloudCode:new Io(this),blockchain:new Po(this),marketplace:new vo(this),multiplayer:new Ao(this),workshop:new wo(this),dataCollections:new zo(this),analytics:new br(this),experiment:new Dr(this)},this.userService=new Oi(this),this.cache.attachState(this.userService),this.auth=new wi(this),this.currency=new qi(this),this.item=new Ui(this),this.store=new _i(this),this.credits=new Vi(this),this.purchase=new ji(this),this.checkout=new Fi(this),this.lootbox=new Wi(this),this.reward=new Qi(this),this.quest=new is(this),this.tutorial=new $i(this),this.communityMarketing=new Ji(this),this.chat=new Xi(this),this.push=new es(this),this.localization=new ns(this),this.timedEvent=new os(this),this.leaderboard=new ds(this),this.season=new gs(this),this.premium=new ys(this),this.character=new Ss(this),this.match=new xs(this),this.challenge=new bs(this),this.craft=new Ds(this),this.ai=new Ps(this),this.collection=new vs(this),this.coopEvent=new ws(this),this.dealOffer=new Ms(this),this.referral=new Os(this),this.mailbox=new Ls(this),this.clan=new _s(this),this.avatar=new Fs(this),this.partners=new Ws(this),this.ads=new Qs(this),this.social=new Ys(this),this.timedBoost=new Xs(this),this.userCustomData=new er(this),this.titleCustomData=new tr(this),this.title=new nr(this),this.gameLoop=new or(this),this.cloudCode=new ar(this),this.blockchain=new ur(this),this.marketplace=new mr(this),this.multiplayer=new fr(this),this.workshop=new gr(this),this.dataCollections=new Rr(this),this.analytics=new Sr(this),this.experiments=new xr(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.host.getFullURL(),RelatedEntityID:a()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var Mo=class{ctx;constructor(e){this.ctx=new ko(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,n={}){let i=this.ctx.buildAuthedBaseRequest(),s=tn(this.ctx.settings.titleID,e,t,i.UserID??"");return this.ctx.transport.post(s,{...i,...n},z.unknown(),{ticket:i.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get challenge(){return this.ctx.challenge}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get clan(){return this.ctx.clan}get avatar(){return this.ctx.avatar}get partners(){return this.ctx.partners}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get host(){return this.ctx.host}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function KT(o){return new Mo(o)}var ig="idos_sso",sg="state",ql="idos:sso:state",QT="https://idosgames.com/sso/",HT=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],$T=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function JT(){if(typeof window>"u")return false;let{origin:o}=window.location;return HT.includes(o)||$T.test(o)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function ZT(){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(ig);if(!t)return null;let n=e.get(sg)??"",i=nw();return sw(e),iw(),i&&n!==i?null:{code:t,state:n}}function YT(o){if(typeof window>"u")return;let e=o.returnTo??XT(),t=ew();tw(t);let n=new URL(o.ssoUrl??QT);n.searchParams.set("title",o.titleID),n.searchParams.set("return_to",e),n.searchParams.set("state",t),window.location.assign(n.toString());}function XT(){let{origin:o,pathname:e,search:t}=window.location;return `${o}${e}${t}`}function ew(){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 tw(o){try{window.sessionStorage.setItem(ql,o);}catch{}}function nw(){try{return window.sessionStorage.getItem(ql)}catch{return null}}function iw(){try{window.sessionStorage.removeItem(ql);}catch{}}function sw(o){o.delete(ig),o.delete(sg);let e=o.toString(),{pathname:t,search:n}=window.location;window.history.replaceState(null,"",`${t}${n}${e?`#${e}`:""}`);}var rw={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 ow(o,e="Something went wrong. Please try again."){return o?rw[o]??o:e}function aw(o,e){return !!o?.Claims?.[e]?.ClaimedAt}function lw(o){let e=o?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function uw(o,e){return o?.Claims?.[e]?.PremiumTiers??[]}function og(o,e,t,n=1){if(!o)return e;let i=o.Base??e,s=Math.max(0,t-n),r;switch(o.Shape??"Flat"){case "PerStep":r=i+(o.PerStep??0)*s;break;case "PerStepRate":r=i*(1+(o.PerStepRate??0)*s);break;case "Geometric":r=i*Math.pow(1+(o.GrowthRate??0),s);break;case "Table":r=i*rg(o,t,1);break;case "TableAbsolute":r=rg(o,t,i);break;default:r=i;break}return Number.isNaN(r)?i:(o.MinResult!=null&&r<o.MinResult&&(r=o.MinResult),o.MaxResult!=null&&r>o.MaxResult&&(r=o.MaxResult),r)}function cw(o,e,t=1){return og(o,1,e,t)}function pw(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 ag(o.Points).length>0;default:return o.MinResult!=null||o.MaxResult!=null}}function hw(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 ag(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 rg(o,e,t){let n=ag(o.Points);if(n.length===0)return t;let i=null,s=null,r=null;for(let p of n)(r===null||p.AtStep>r.AtStep)&&(r=p),p.AtStep<=e&&(i===null||p.AtStep>=i.AtStep)&&(i=p),p.AtStep>e&&(s===null||p.AtStep<s.AtStep)&&(s=p);if(i===null)return t;if(s===null){let p=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-i.AtStep)/(s.AtStep-i.AtStep);return i.Value+p*(s.Value-i.Value)}case "Geometric":{if(i.Value<=0||s.Value<=0){let m=(e-i.AtStep)/(s.AtStep-i.AtStep);return i.Value+m*(s.Value-i.Value)}let p=(e-i.AtStep)/(s.AtStep-i.AtStep);return i.Value*Math.pow(s.Value/i.Value,p)}default:return i.Value}}function lg(o,e){return e?.BonusMode??o?.SetSettings?.BonusMode??"Cumulative"}function ug(o,e,t){if(!o?.Bonuses||e<=0)return [];let n=o.Bonuses.filter(i=>!!i&&(i.Pieces??0)>0&&(i.Pieces??0)<=e).sort((i,s)=>(i.Pieces??0)-(s.Pieces??0));if(n.length===0)return [];if(t==="HighestOnly"){let i=n[n.length-1]?.Pieces??0;return n.filter(s=>(s.Pieces??0)===i)}return n}function dw(o,e){let t=e?.Sets,n=e?.Catalogs;if(!t||!o||!n||Object.keys(t).length===0)return [];let i=new Map;for(let[p,m]of Object.entries(o)){if(!p||p.startsWith("@")||!m?.ItemID)continue;let W=fw(n,m.ItemID,m.CatalogID??null)?.Metadata?.CollectionID;!W||!(W in t)||i.set(W,(i.get(W)??0)+1);}let s=[...i.keys()].sort((p,m)=>p<m?-1:p>m?1:0),r=[];for(let p of s){let m=t[p];if(!m)continue;let R=i.get(p)??0,W=lg(e,m);r.push({SetID:p,Definition:m,Pieces:R,Mode:W,ActiveTiers:ug(m,R,W)});}return r}function mw(o,e){if(!o||!e)return 0;let t=0;for(let n of Object.values(o))for(let i of Object.values(n?.Items??{}))i?.Metadata?.CollectionID===e&&t++;return t}function fw(o,e,t){if(t){let i=o[t]?.Items?.[e];if(i)return i}let n=null;for(let i of Object.values(o)){let s=i?.Items?.[e];if(s){if(n)return null;n=s;}}return n}var gw={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Ul=z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),yw={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Rw=z.enum(["Top","Bottom","Left","Right"]).catch("Top"),Cw=z.object({PlacementID:z.string().nullish(),Type:Ul.nullish(),Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),CreditsRewarded:z.number().nullish(),AllowedProviderIDs:z.array(z.string()).nullish()}).passthrough(),Sw=z.object({DefaultCreditsPerView:z.number().nullish(),MaxCreditsBalance:z.number().nullish(),DailyCreditEarnCap:z.number().nullish(),DailyViewCap:z.number().nullish(),MinSecondsBetweenViews:z.number().nullish()}).passthrough(),xw=z.object({CooldownSeconds:z.number().nullish(),MinSessionTimeBeforeFirstSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),bw=z.object({Enabled:z.boolean().nullish(),Position:Rw.nullish(),RefreshIntervalSeconds:z.number().nullish()}).passthrough(),Dw=z.object({Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish()}).passthrough(),Iw=z.object({MaxImpressionsPerHour:z.number().nullish(),MaxImpressionsPerDay:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),Pw=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),DisableInterstitials:z.boolean().nullish(),DisableBanners:z.boolean().nullish(),DisableAppOpen:z.boolean().nullish()}).passthrough(),vw=z.object({RequirePersonalizedAdsConsent:z.boolean().nullish(),RequireTrackingConsent:z.boolean().nullish(),CurrentPolicyVersion:z.string().nullish(),RegulatedRegions:z.array(z.string()).nullish()}).passthrough(),Aw=z.object({RequireServerSideVerification:z.boolean().nullish(),PendingRequestTtlSeconds:z.number().nullish(),MaxPendingRequestsPerUser:z.number().nullish()}).passthrough(),Tw=z.object({AndroidUnitID:z.string().nullish(),IosUnitID:z.string().nullish(),WebUnitID:z.string().nullish(),Type:Ul.nullish()}).passthrough(),ww={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},zw=z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),kw=z.object({ProviderID:z.string().nullish(),Kind:zw.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(),Tw).nullish()}).passthrough();z.object({Enabled:z.boolean().nullish(),Placements:z.record(z.string(),Cw).nullish(),Providers:z.record(z.string(),kw).nullish(),RewardedVideo:Sw.nullish(),Interstitial:xw.nullish(),Banner:bw.nullish(),AppOpen:Dw.nullish(),FrequencyCapping:Iw.nullish(),PremiumAdReductions:z.array(Pw).nullish(),Consent:vw.nullish(),Verification:Aw.nullish()}).passthrough();var Mw=z.object({RewardedVideoCredit:z.number().nullish(),TotalEarned:z.number().nullish(),TotalSpent:z.number().nullish()}).passthrough(),Ow=z.object({PlacementID:z.string().nullish(),LastShownAt:u.nullish(),LastCompletedAt:u.nullish(),TotalImpressions:z.number().nullish(),TotalCompletions:z.number().nullish(),ConsecutiveFailures:z.number().nullish()}).passthrough(),Ew=z.object({Date:u.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(),qw=z.object({SessionID:z.string().nullish(),SessionStartAt:u.nullish(),Impressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish()}).passthrough(),Uw=z.object({PersonalizedAdsConsent:z.boolean().nullish(),TrackingConsent:z.boolean().nullish(),PolicyVersion:z.string().nullish(),Region:z.string().nullish(),ConsentGivenAt:u.nullish(),ConsentRevokedAt:u.nullish()}).passthrough(),Lw=z.object({RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),Type:Ul.nullish(),IssuedAt:u.nullish(),ExpiresAt:u.nullish(),CreditsToAward:z.number().nullish()}).passthrough(),Bw=z.object({InvalidSsvCount:z.number().nullish(),OrphanCompletions:z.number().nullish(),FastCompletions:z.number().nullish(),LastFlaggedAt:u.nullish()}).passthrough();z.object({Credits:Mw.nullish(),Placements:z.record(z.string(),Ow).nullish(),Daily:Ew.nullish(),Session:qw.nullish(),LastImpressionAt:u.nullish(),LastInterstitialAt:u.nullish(),LastRewardedAt:u.nullish(),LastAppOpenAt:u.nullish(),TotalImpressions:z.number().nullish(),TotalRewardedCompletions:z.number().nullish(),AdsDisabledUntil:u.nullish(),Consent:Uw.nullish(),PendingRequests:z.record(z.string(),Lw).nullish(),FraudFlags:Bw.nullish(),UpdatedAt:u.nullish()}).passthrough();
2
+ export{Fe as AIAction,kC as AIErrorCode,ln as AIGenerationStatus,Jt as AIModality,Vs as AVATAR_MAX_USERS,eb as AVATAR_SHOP_PAGE_SIZE,on as AcquisitionCapture,ww as AdProviderKind,gw as AdType,Ks as AdvertisingAction,rl as AnalyticsAction,nP as AnalyticsDropReason,sl as AnalyticsEventNaming,Ot as AnalyticsLimits,Bb as AttackOutcome,Ke as AuthenticationAction,en as AutomaticEvent,wn as AvatarAction,Xx as AvatarErrors,yw as BannerPosition,it as BlockchainAction,wD as BlockchainNetworkType,ud as BlockchainOperationCategory,BD as BlockchainTransactionStatus,OD as BlockchainTransactionType,sx as BodyPart,QA as BoostWindowKind,Gs as CLAN_DEFAULT_KIND_ID,En as ChallengeAction,Hv as ChallengeMode,$e as CharacterAction,tt as ChatAction,CR as ChatAuthorType,yR as ChatBlockedTermAction,hR as ChatChannelType,fR as ChatDirectAudience,dR as ChatPartitioning,xR as ChatReportReason,Le as ClanAction,vx as ClanCompetitionType,Px as ClanErrors,Dx as ClanInviteType,xx as ClanJoinMode,Ix as ClanPermission,Ax as ClanRelation,Ml as CloudCodeAction,mT as CloudCodeErrorCode,hT as CloudCodeLogLevel,pT as CloudCodeRevisionSelection,Xe as CollectionAction,mI as CommissionSink,SD as CommunityChestMemberStatus,CD as CommunityChestStatus,Uv as CommunityCreatorStatus,dn as CommunityMarketingAction,Bv as CommunityMetricKind,Ev as CommunityParticipationMode,Lv as CommunityPayoutCurrencyKind,wS as ConversionRateMode,Pt as CoopEventAction,KC as CoopGroupStatus,QC as CoopMemberStatus,Xr as CraftAction,aA as CraftInputSelectionMode,rA as CraftOutputLevelMode,uA as CraftOutputLevelOverflow,sA as CraftType,Vn as CreditsConfirmationStatus,Fy as CreditsError,Kn as CurrencyAction,TS as CurrencyStatus,Mg as CurveInterpolation,zg as CurveShape,_t as CustomDataBucket,pb as CustomDataValueType,lb as CustomDataWriter,Gl as DEFAULT_BASE_URL,EI as DataAccessMode,zI as DataCollectionKind,VI as DataCollectionSchemaMode,ZI as DataCollectionsAction,BI as DataCounterKind,MI as DataFieldType,OI as DataFieldVisibility,NI as DataOwnerDeletedPolicy,UI as DataRefKind,pS as DealComparisonOperator,iS as DealNodeRuntimeStatus,cS as DealNodeType,kt as DealOfferAction,nS as DealOfferActivationStatus,Cr as EVENT_NAME_PATTERN,rT as EnvelopeType,ll as ExperimentAction,dP as ExperimentGoalKind,Tb as FRIENDS_FROM_PLATFORM,vP as FodderSelectionMode,IP as FodderValuationMode,mb as FriendActionStatus,fb as FriendSource,We as GameLoopAction,Mo as IDosGamesClient,FP as IapProductType,sv as IapPurchaseStatus,Tr as ItemAction,LP as ItemSetBonusMode,ED as KycStatus,UD as KycTier,Ze as LeaderboardAction,Ir as LocalizationAction,RP as LocalizationMissingKeyMode,Lr as LootboxAction,$S as MAILBOX_COUNTER_CAP,ct as MailboxAction,jS as MailboxCategory,HS as MailboxErrors,FS as MailboxLetterSource,KS as MailboxRewardModule,pr as MarketGoodsType,dI as MarketOfferStatus,hI as MarketOfferType,Be as MarketplaceAction,Mt as MatchAction,rx as MatchStatus,st as MultiplayerAction,nT as MultiplayerChatMode,tT as MultiplayerTopology,cR as OFFER_NOT_IN_ROTATION,ka as PLATFORM_AD_PROVIDER,zA as PartnerErrors,TA as PartnerProgramMode,wA as PartnerStatus,sn as PartnersAction,_S as PeerPayoutSource,VS as PeerPayoutStatus,zb as PlatformFriendsMode,wb as PlatformProfileMode,QD as PlayAccessMode,gP as PlayerExperimentStatus,Nn as PlaytimeTracker,pn as PremiumAction,hn as PurchaseAction,Tn as PushAction,nt as PushPermissionState,qR as PushTopic,OR as PushTransport,Dt as QuestAction,jg as QuestObjectiveSource,Wg as QuestPrerequisiteMode,Ng as QuestStatus,Ub as RaidMode,nn as ReferralAction,Et as RewardAction,Sv as RewardWindowBoost,iT as RoomVisibility,wC as SKIN_ALREADY_OWNED,ca as SKIN_SLOT,Ht as SeasonAction,De as SocialAction,xb as SocialContentStatus,Rb as SocialEntityType,bb as SocialInboxVerb,Cb as SocialReactionKind,Sb as SocialReportReason,Lb as SpecialChoiceMode,Gt as StoreAction,Qy as StoreRotationMode,VP as StoreType,fn as TimedBoostAction,LA as TimedBoostStackingPolicy,gt as TimedEventAction,gn as TitleAction,si as TitleCustomDataAction,JA as TitleDataBucket,$A as TitleDataScope,fA as TradeOfferStatus,GD as TransactionDirection,mt as TutorialAction,oy as TutorialBoardAction,iy as TutorialFlowStatus,Ig as TutorialGateMode,ty as TutorialRestartPolicy,ry as TutorialScriptModule,Xg as TutorialStepCompletionMode,Gn as TypedEmitter,Ct as UserAction,vt as UserCustomDataAction,FD as WalletGateBalanceSource,kD as WalletLinkType,RT as WorkshopAccessMode,wT as WorkshopAccessVia,et as WorkshopAction,PT as WorkshopContentStatus,xT as WorkshopHoldingMatch,CT as WorkshopHoldingMode,AT as WorkshopLicenseSource,TT as WorkshopSort,DT as WorkshopVisibility,ug as activeSetTiers,ow as authErrorText,YT as beginSsoRedirect,lw as claimedMilestoneIDs,mw as countSetMembers,KT as createIDosGamesClient,Dn as cryptoShortfallFromError,cw as curveMultiplier,wy as defineView,Xd as describeUserAgent,lg as effectiveSetMode,og as evaluateCurve,uw as grantedPremiumTiers,Wn as isAIGenerationTerminal,pw as isCurveConfigured,aw as isMilestoneClaimed,RC as isReservedSlot,JT as isSsoAvailable,lr as normalizeBlockchainCategory,MC as parseAIErrorCode,ZT as readSsoCodeFromUrl,dw as resolveItemSets,hw as roundAmount,XI as where,jy as zPaymentProof,Li as zPriceOption,de as zPriceOptions};